PianoRollComponent.cpp 394 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754
  1. #include "ui/ShotShowing.h"
  2. #include "ui/WorkflowExtras.h" // round 190pf (the chord highlight switch)
  3. #include "ui/FlMods.h"
  4. #include "ui/Motion.h"
  5. #include "ui/FileChoosers.h"
  6. #include "ui/PianoRollComponent.h"
  7. #include "core/ZoomAnchor.h"
  8. #include "core/MuteKeys.h"
  9. #include "core/RulerGestures.h" // round 190nq (#227)
  10. #include "ui/ChordHelper.h"
  11. #include "ui/MixerComponent.h"
  12. #include "ui/PaintAB.h"
  13. #include "core/ChordReadout.h"
  14. #include "core/ClipLoopOps.h"
  15. #include "core/RowBands.h"
  16. #include "core/PastePlace.h"
  17. #include "ui/WindowClipboard.h" // issue #232 stage 2 (round 190nz)
  18. #include "core/LayoutStyle.h"
  19. #include "core/TrackOnly.h"
  20. #include "core/KeyMap.h"
  21. #include "core/NoteNames.h"
  22. #include "core/TransportEdit.h"
  23. #include "ui/UiTrace.h"
  24. #include "ui/TextCache.h"
  25. #include "core/EditorPolish.h"
  26. #include "core/MagicLasso.h"
  27. #include "core/EventEdit.h"
  28. #include "core/MarkerPlan.h"
  29. #include "core/NoteEdit.h"
  30. #include "core/FlSettings.h"
  31. #include "core/Details190mr.h"
  32. #include "core/NoteTools.h"
  33. #include "core/ScaleDetect.h"
  34. #include "core/Mpe.h"
  35. #include "core/NoteCurves.h"
  36. #include "core/NoteConditions.h"
  37. #include "core/NoteChance.h"
  38. #include "core/DrawMode.h"
  39. #include "core/Rack.h"
  40. #include <array>
  41. #include "engine/MidiFileIo.h"
  42. #include "engine/Mp3Format.h"
  43. #include "core/PianoRollTools.h"
  44. #include "ui/BrowserComponent.h"
  45. #include "ui/Dialogs.h"
  46. #include "ui/MidiClipboard.h"
  47. #include "ui/MidiToolsPanel.h"
  48. #include "ui/ToolWindow.h"
  49. #include "engine/Text.h"
  50. #include <optional>
  51. #include "ui/AutomationUi.h"
  52. #include "ui/EventEditor.h"
  53. #include "ui/HintBar.h"
  54. #include "platform/Paths.h"
  55. #include "ui/I18n.h"
  56. #include "ui/Theme.h"
  57. namespace lynx
  58. {
  59. namespace
  60. {
  61. bool isBlackKey (int key)
  62. {
  63. const auto n = key % 12;
  64. return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
  65. }
  66. // Round 190jo (design190ia FM-15 / FM-16): FL's note, lit from the top (its upper part +6 %, the rest -4 % of its colour,
  67. // after FL's top-to-bottom gradient) with a 1 px edge at 72 % of it, radius 2 (one flat fill on rows under 8 px); `edge`: the state's outline (selected, hovered),
  68. // transparent for the note's own edge. The label is dark on a light note and light on a dark one (≥ 4.5:1 on the
  69. // velocity range of LYNX's red), bold, at the small text size.
  70. void paintNoteBody (juce::Graphics& g, juce::Rectangle<float> r, juce::Colour fill, juce::Colour edge)
  71. {
  72. // (perf: two solid fills instead of a gradient, whose brush the Direct2D renderer makes again for every note; the
  73. // upper half lighter reads as FL's top-lit note)
  74. g.setColour (fill.withMultipliedBrightness (0.96f));
  75. g.fillRoundedRectangle (r, 2.0f);
  76. if (r.getHeight() >= 8.0f)
  77. {
  78. g.setColour (fill.withMultipliedBrightness (1.06f));
  79. g.fillRect (juce::Rectangle<float> (r.getX() + 1.0f, r.getY() + 1.0f, r.getWidth() - 2.0f, std::floor (r.getHeight() * 0.45f)));
  80. }
  81. g.setColour (edge.isTransparent() ? fill.withMultipliedBrightness (0.72f) : edge);
  82. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  83. }
  84. juce::Colour noteLabelColour (juce::Colour fill)
  85. {
  86. return fill.getPerceivedBrightness() > 0.5f ? theme::colour::bg0 : theme::colour::textPrimary;
  87. }
  88. juce::Font noteLabelFont (int rowHeight)
  89. {
  90. return theme::font (juce::jmin (theme::type::small, gesture::labelHeight (rowHeight) - 1.0f), true);
  91. }
  92. // FL-style name: key 60 = C5.
  93. juce::String keyName (int key)
  94. {
  95. return juce::String (notenames::keyName (key)); // Settings › General › Note names (round 165f)
  96. }
  97. // (round 190ea: never out of range: an empty pattern when a hand-built song has none; an edit keeps one first)
  98. const Pattern& currentPattern (const Song& s)
  99. {
  100. return s.activePattern();
  101. }
  102. Pattern& currentPattern (Song& s)
  103. {
  104. return s.activePattern();
  105. }
  106. // "\t" + the key map's shortcut of `id` for a menu item (empty when unbound or no key map is connected)
  107. juce::String keyText (const std::string& id)
  108. {
  109. return PianoRollComponent::shortcutText ? PianoRollComponent::shortcutText (id) : juce::String();
  110. }
  111. struct NamedIntervals
  112. {
  113. const char* name;
  114. std::vector<int> intervals;
  115. };
  116. const std::vector<NamedIntervals>& chords()
  117. {
  118. static const std::vector<NamedIntervals> list {
  119. { TR_NOOP ("Note"), { 0 } }, { TR_NOOP ("Major"), { 0, 4, 7 } }, { TR_NOOP ("Minor"), { 0, 3, 7 } }, { "Dim", { 0, 3, 6 } },
  120. { "Aug", { 0, 4, 8 } }, { "Sus2", { 0, 2, 7 } }, { "Sus4", { 0, 5, 7 } }, { "7", { 0, 4, 7, 10 } },
  121. { "Maj7", { 0, 4, 7, 11 } }, { "m7", { 0, 3, 7, 10 } }, { "m9", { 0, 3, 7, 10, 14 } }, { TR_NOOP ("Octave"), { 0, 12 } },
  122. };
  123. return list;
  124. }
  125. const std::vector<notetools::ScaleInfo>& scales()
  126. {
  127. return notetools::scales();
  128. }
  129. // a detected chord in the chosen note names (Settings › General, round 165f): "Do m7/Mib"; "" when none
  130. juce::String chordName (const std::vector<int>& keys)
  131. {
  132. // FL's own names (round 181b, core/ChordReadout.h): the same for the panel, this readout and the bubble
  133. if ((int) keys.size() < chordread::minKeys || (int) keys.size() > chordread::maxKeys)
  134. return {};
  135. std::array<std::string, 12> notes;
  136. for (int pc = 0; pc < 12; ++pc)
  137. {
  138. auto name = juce::String (notenames::pitchName (pc));
  139. if (name.endsWithChar ('#'))
  140. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266F);
  141. else if (name.length() > 1 && name.endsWithChar ('b'))
  142. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266D);
  143. notes[(std::size_t) pc] = name.toStdString();
  144. }
  145. chordread::NameOptions options;
  146. options.notes = &notes;
  147. const auto named = chordread::nameKeys (keys, options);
  148. const auto text = juce::String::fromUTF8 (named.text.c_str());
  149. return named.novelty ? tr (text) : text;
  150. }
  151. // View › Background waveform (round 168g): one for every editor, like FL's (PTR_DAT_015e2698 / DAT_016ba824)
  152. struct BackgroundWave
  153. {
  154. juce::File file;
  155. std::vector<float> lo, hi; // per peak block
  156. double sampleRate = 44100.0;
  157. std::int64_t samples = 0;
  158. static constexpr int perPeak = 256;
  159. };
  160. std::shared_ptr<const BackgroundWave>& backgroundWave()
  161. {
  162. static std::shared_ptr<const BackgroundWave> wave;
  163. return wave;
  164. }
  165. bool& backgroundWaveOn()
  166. {
  167. static bool on = false;
  168. return on;
  169. }
  170. bool isScoreFile (const juce::File& f) { return f.hasFileExtension ("fsc"); }
  171. bool isMidiFile (const juce::File& f) { return f.hasFileExtension ("mid;midi"); }
  172. } // namespace
  173. // Live's Randomization Amount slider: a 38 x 13 box, 1 px #111111 edge, the value's share of 127 filled teal (#007383)
  174. // over #242424, the number in the middle [SHOT live-01-velocity-lane.png x 566…603, y 980…992]. Drag up / down or the
  175. // wheel change it; typed digits then Enter set it and randomize (manual 10.5.12), Escape forgets them.
  176. class PianoRollComponent::LiveAmountBox final : public juce::Component, public juce::SettableTooltipClient
  177. {
  178. public:
  179. std::function<void()> onEnter;
  180. LiveAmountBox()
  181. {
  182. setWantsKeyboardFocus (true);
  183. setTitle (tr ("Randomization Amount"));
  184. setTooltip (tr ("Randomization Amount: velocities move up or down by up to this much (drag, or type a number and press Enter)"));
  185. }
  186. void paint (juce::Graphics& g) override
  187. {
  188. const auto r = getLocalBounds();
  189. g.setColour (juce::Colour (0xff111111));
  190. g.fillRect (r);
  191. const auto inner = r.reduced (1);
  192. g.setColour (juce::Colour (0xff242424));
  193. g.fillRect (inner);
  194. const auto value = typed.isNotEmpty() ? juce::jlimit (0, 127, typed.getIntValue()) : PianoRollComponent::liveRandomizeAmount;
  195. g.setColour (juce::Colour (0xff007383));
  196. g.fillRect (inner.withWidth (juce::roundToInt ((float) inner.getWidth() * (float) value / 127.0f)));
  197. g.setColour (typed.isNotEmpty() ? juce::Colour (0xffffad56) : juce::Colour (0xffb0b0b0));
  198. g.setFont (theme::font (theme::type::caption));
  199. textcache::drawText (g, typed.isNotEmpty() ? typed : juce::String (value), r, juce::Justification::centred, false);
  200. }
  201. void mouseDown (const juce::MouseEvent&) override
  202. {
  203. dragFrom = PianoRollComponent::liveRandomizeAmount;
  204. grabKeyboardFocus();
  205. }
  206. void mouseDrag (const juce::MouseEvent& e) override { set (dragFrom - e.getDistanceFromDragStartY() / 2); }
  207. void mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& w) override
  208. {
  209. set (PianoRollComponent::liveRandomizeAmount + (w.deltaY > 0 ? 1 : w.deltaY < 0 ? -1 : 0));
  210. }
  211. bool keyPressed (const juce::KeyPress& key) override
  212. {
  213. const auto c = key.getTextCharacter();
  214. if (c >= '0' && c <= '9' && typed.length() < 3)
  215. {
  216. typed << juce::String::charToString (c);
  217. repaint();
  218. return true;
  219. }
  220. if (key.isKeyCode (juce::KeyPress::backspaceKey) && typed.isNotEmpty())
  221. {
  222. typed = typed.dropLastCharacters (1);
  223. repaint();
  224. return true;
  225. }
  226. if (key.isKeyCode (juce::KeyPress::returnKey) && typed.isNotEmpty())
  227. {
  228. typeForCheck (typed);
  229. return true;
  230. }
  231. if (key.isKeyCode (juce::KeyPress::escapeKey) && typed.isNotEmpty())
  232. {
  233. typed.clear();
  234. repaint();
  235. return true;
  236. }
  237. return false;
  238. }
  239. void focusLost (FocusChangeType) override
  240. {
  241. typed.clear();
  242. repaint();
  243. }
  244. // the value typed and validated with Enter: set, then the notes randomized
  245. void typeForCheck (const juce::String& text)
  246. {
  247. typed.clear();
  248. set (text.getIntValue());
  249. if (onEnter != nullptr)
  250. onEnter();
  251. }
  252. private:
  253. void set (int v)
  254. {
  255. v = juce::jlimit (1, 127, v);
  256. if (v != PianoRollComponent::liveRandomizeAmount)
  257. {
  258. PianoRollComponent::liveRandomizeAmount = v;
  259. repaint();
  260. }
  261. }
  262. juce::String typed;
  263. int dragFrom = 0;
  264. };
  265. PianoRollComponent::PianoRollComponent (AudioEngine& e)
  266. : engine (e)
  267. {
  268. gpuPlayhead.onHidden = [this] { repaint (playheadColumn (playheadTick)); }; // (round 190ip: painted again)
  269. auto sender = [this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); };
  270. previewNotes.setSender (sender);
  271. listenNotes.setSender (sender);
  272. setWantsKeyboardFocus (false);
  273. setMouseClickGrabsKeyboardFocus (false);
  274. for (auto* bar : { &hBar, &vBar })
  275. {
  276. bar->addListener (this);
  277. bar->setAutoHide (false);
  278. addAndMakeVisible (bar);
  279. }
  280. // the overview strip is the horizontal scroller (FL's Piano Roll has its preview bar on top)
  281. hBar.setVisible (false);
  282. overview.paintContent = [this] (juce::Graphics& g, juce::Rectangle<float> area, double total) { paintOverview (g, area, total); };
  283. overview.onChange = [this] (double start, double length) {
  284. const auto width = (double) gridArea().getWidth();
  285. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, width / juce::jmax (1.0, length));
  286. scrollTicks = juce::jmax (0.0, start);
  287. updateScrollBars();
  288. repaint();
  289. };
  290. overview.onShowAll = [this] { zoomAll(); };
  291. addAndMakeVisible (overview);
  292. grid::fillEditorBox (snapBox);
  293. snapBox.setTooltip (tr ("Piano Roll snap (magnet): \"Main\" follows the snap in the toolbar, or pick this window's own; hold Alt while dragging to ignore it"));
  294. ui::setQuickTip (snapBox, tr ("Piano Roll snap"));
  295. snapBox.setWantsKeyboardFocus (false);
  296. snapBox.setMouseClickGrabsKeyboardFocus (false);
  297. snapBox.onChange = [this] { repaint(); };
  298. addAndMakeVisible (snapBox);
  299. // round 190hr: the reference's grid value and menu (docked only)
  300. liveGridButton.setConnectedEdges (0);
  301. liveGridButton.setTooltip (tr ("Grid: adaptive or fixed, narrower (Ctrl+1) or wider (Ctrl+2), triplet (Ctrl+3), snap (Ctrl+4), fixed / adaptive (Ctrl+5)"));
  302. liveGridButton.onClick = [this] {
  303. liveGridMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&liveGridButton));
  304. };
  305. addChildComponent (liveGridButton);
  306. tools.onChange = [this] (EditTool) {
  307. stopListening();
  308. updateCursor (juce::ModifierKeys::currentModifiers);
  309. };
  310. tools.onZoomMenu = [this] (juce::Component& button) { // (round 190mp, DE-74)
  311. quickZoomMenu ("pianoRoll.", [this] (const std::string& id) { return runAction (id); }, shortcutText, false)
  312. .showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&button));
  313. };
  314. addAndMakeVisible (tools);
  315. 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"));
  316. channelBox.setWantsKeyboardFocus (false);
  317. channelBox.setMouseClickGrabsKeyboardFocus (false);
  318. channelBox.onChange = [this] {
  319. if (channelBox.getSelectedId() == allChannelsId)
  320. {
  321. setAllChannels (true);
  322. return;
  323. }
  324. const auto channel = channelBox.getSelectedId() - 1;
  325. setAllChannels (false);
  326. if (channel >= 0 && channel < (int) engine.getSong().channels.size() && channel != engine.getSelectedChannel())
  327. engine.setSelectedChannel (channel);
  328. };
  329. channelBox.onStep = [this] (int direction, bool all) {
  330. setAllChannels (false);
  331. stepChannel (direction, ! all);
  332. };
  333. addAndMakeVisible (channelBox);
  334. ghostButton.setClickingTogglesState (true);
  335. ghostButton.setToggleState (showGhosts, juce::dontSendNotification);
  336. ghostButton.setOnColour (theme::colour::bg6);
  337. ghostButton.setIconColourWhenOn (theme::colour::textPrimary);
  338. ghostButton.setFlat (true);
  339. ghostButton.setTooltip (tr ("Ghost notes: show the other channels' notes (Alt+V) and, outlined, this channel's notes in the clips "
  340. "playing at the same time; double right-click one to edit its channel; Ctrl+Alt+V makes them editable"));
  341. ui::setQuickTip (ghostButton, tr ("Ghost notes"), "Alt+V");
  342. ui::setQuickTip (moreButton, tr ("Note tools"));
  343. ui::setQuickTip (scaleSnapButton, tr ("Snap to scale"));
  344. ghostButton.onClick = [this] {
  345. showGhosts = ghostButton.getToggleState();
  346. repaint();
  347. };
  348. ghostButton.onRightClick = [this] { // FL: the ghost notes button's menu picks the channels (round 166d)
  349. ghostChannelsMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&ghostButton));
  350. };
  351. moreButton.setFlat (true);
  352. moreButton.setTooltip (tr ("Note operations, left-edge resizing and MIDI import/export"));
  353. moreButton.onClick = [this] { showMoreMenu(); };
  354. scaleSnapButton.setOnColour (theme::colour::bg6);
  355. scaleSnapButton.setIconColourWhenOn (theme::colour::accent);
  356. scaleSnapButton.setFlat (true);
  357. scaleSnapButton.setTooltip (tr ("Snap notes to the scale: new and moved notes, and incoming MIDI, land on the chosen scale"));
  358. scaleSnapButton.onClick = [this] { setScaleSnap (! scaleSnap); };
  359. // Follow (FL: "Auto scrolling"): the view pages along with the playhead while the pattern plays
  360. followButton.setOnColour (theme::colour::bg6);
  361. followButton.setIconColourWhenOn (theme::colour::accent);
  362. followButton.setFlat (true);
  363. followButton.setClickingTogglesState (false);
  364. followButton.setToggleState (EditorGlobals::get().isFollowing (true), juce::dontSendNotification);
  365. followButton.setTooltip (tr ("Follow: the Piano Roll scrolls along with the playhead while this pattern plays; off, you can look around freely"));
  366. ui::setQuickTip (followButton, tr ("Follow the playhead"));
  367. followButton.onClick = [this] { runAction ("pianoRoll.follow"); };
  368. playButton.setFlat (true);
  369. playButton.setClickingTogglesState (false);
  370. playButton.setIconColourWhenOn (theme::colour::accent); // FL: stays a play icon, in the theme colour while playing
  371. playButton.setTooltip (tr ("Play / pause the pattern [RMB] stop and go back to where playback started (again: to the pattern start)"));
  372. playButton.onClick = [this] { if (onPlayPause) onPlayPause(); };
  373. playButton.onRightClick = [this] { if (onPlayRightClick) onPlayRightClick(); };
  374. for (auto* b : { &playButton, &ghostButton, &scaleSnapButton, &moreButton, &followButton })
  375. {
  376. b->setWantsKeyboardFocus (false);
  377. b->setMouseClickGrabsKeyboardFocus (false);
  378. addAndMakeVisible (*b);
  379. }
  380. for (int i = 0; i < (int) chords().size(); ++i)
  381. {
  382. chordBox.addItem (tr (chords()[(std::size_t) i].name), i + 1);
  383. if (i == 0) // round 190nu (LYNX extra, discussion #105): the clicked degree's chord in the key of its region
  384. chordBox.addItem (tr ("Scale degree chord"), degreeStampId);
  385. }
  386. chordBox.setSelectedId (1, juce::dontSendNotification);
  387. chordBox.onPopup = [this] { return stampMenu(); }; // (round 190nu: FL's stamp button opens the Stamp menu; the options of the degree chord on top)
  388. chordBox.setTooltip (tr ("Clicking creates this chord (the clicked note is the root)"));
  389. // scale: root x type
  390. for (int s = 0; s < (int) scales().size(); ++s)
  391. {
  392. if (s == 0)
  393. {
  394. scaleBox.addItem (tr (scales()[0].name), 1);
  395. // FL's View › Scale highlighting › Automatic (round 190jv, core/ScaleDetect.h): the key guessed from the notes
  396. scaleBox.addItem (tr ("Automatic"), autoScaleId);
  397. continue;
  398. }
  399. for (int root = 0; root < 12; ++root)
  400. scaleBox.addItem (tr ("{0} {1}", { juce::String (notenames::pitchName (root)), tr (scales()[(std::size_t) s].name) }), s * 100 + root + 1);
  401. }
  402. scaleBox.setSelectedId (1, juce::dontSendNotification);
  403. scaleSnapButton.setEnabled (false); // until a scale is chosen
  404. scaleBox.setTooltip (tr ("Highlights the notes of a scale"));
  405. // issue #203 (round 190ll): the FL layout's click opens FL's Scale highlighting menu (root and scale apart)
  406. scaleBox.onPopup = [this] { return scaleHighlightMenu(); };
  407. // docked (Clip-launch: Live's Clip View Scale; Simple: BandLab's Smart View): a root box and a scale box
  408. for (int root = 0; root < 12; ++root)
  409. scaleRootBox.addItem (juce::String (notenames::pitchName (root)), root + 1);
  410. scaleNameBox.addItem (tr (scales()[0].name), 1);
  411. scaleNameBox.addItem (tr ("Automatic"), autoScaleId);
  412. for (int s = 1; s < (int) scales().size(); ++s)
  413. scaleNameBox.addItem (tr (scales()[(std::size_t) s].name), s * 100);
  414. scaleRootBox.setTooltip (tr ("Root note"));
  415. scaleNameBox.setTooltip (tr ("Highlights the notes of a scale"));
  416. scaleRootBox.onChange = [this] {
  417. splitRoot = juce::jlimit (0, 11, scaleRootBox.getSelectedId() - 1);
  418. if (scaleIndex() > 0)
  419. setScale (splitRoot, scaleIndex());
  420. };
  421. scaleNameBox.onChange = [this] {
  422. const auto id = scaleNameBox.getSelectedId();
  423. if (id == autoScaleId)
  424. setAutoScale (true);
  425. else
  426. setScale (scaleIndex() > 0 ? scaleRoot() : splitRoot, id >= 100 ? id / 100 : 0);
  427. };
  428. for (auto* box : { &scaleRootBox, &scaleNameBox })
  429. {
  430. box->setWantsKeyboardFocus (false);
  431. box->setMouseClickGrabsKeyboardFocus (false);
  432. addChildComponent (box);
  433. }
  434. refreshScaleBoxes();
  435. // round 170e: an icon (FL's slide tool is one) instead of the word "Slide"
  436. slideButton.setClickingTogglesState (true);
  437. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)"));
  438. ui::setQuickTip (slideButton, tr ("Slide notes"));
  439. slideButton.setWantsKeyboardFocus (false);
  440. slideButton.setMouseClickGrabsKeyboardFocus (false);
  441. slideButton.setOnColour (theme::colour::bg6);
  442. slideButton.setIconColourWhenOn (theme::colour::accent);
  443. slideButton.setFlat (true);
  444. addAndMakeVisible (slideButton);
  445. ui::setQuickTip (chordBox, tr ("Chord stamp"));
  446. ui::setQuickTip (scaleBox, tr ("Scale"));
  447. chordBox.iconLit = [this] { return chordBox.getSelectedId() > 1; };
  448. scaleBox.iconLit = [this] { return scaleIndex() > 0; };
  449. colourButton.setTooltip (tr ("Note colour: new notes get this colour. Click: choose it, colour the selection (Alt+C), "
  450. "select by colour (Shift+C)"));
  451. ui::setQuickTip (colourButton, tr ("Note colour"));
  452. colourButton.setWantsKeyboardFocus (false);
  453. colourButton.setMouseClickGrabsKeyboardFocus (false);
  454. colourButton.onClick = [this] { showColourMenu(); };
  455. addAndMakeVisible (colourButton);
  456. chordLabel.setJustificationType (juce::Justification::centred);
  457. chordLabel.setFont (theme::font (theme::type::caption, true));
  458. chordLabel.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  459. chordLabel.setTooltip (tr ("Chord: the chord of the keys held on the MIDI keyboard or the typing piano, else of the selected notes"));
  460. chordLabel.setInterceptsMouseClicks (true, false);
  461. addAndMakeVisible (chordLabel);
  462. // "Show chord name for selection" (round 168g): FL shows it as a hint 16 px into the editor's top-left corner
  463. chordBubble.setJustificationType (juce::Justification::centred);
  464. chordBubble.setFont (theme::font (theme::type::body, true));
  465. chordBubble.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  466. chordBubble.setColour (juce::Label::backgroundColourId, theme::colour::bg4.withAlpha (0.94f));
  467. chordBubble.setColour (juce::Label::outlineColourId, theme::colour::accent.withAlpha (0.8f));
  468. chordBubble.setInterceptsMouseClicks (false, false);
  469. addChildComponent (chordBubble);
  470. for (auto* box : { static_cast<IconComboBox*> (&chordBox), static_cast<IconComboBox*> (&scaleBox) })
  471. {
  472. box->setWantsKeyboardFocus (false);
  473. box->setMouseClickGrabsKeyboardFocus (false);
  474. box->onChange = [this] {
  475. publishScale();
  476. refreshScaleBoxes(); // (issue #203: the docked root / scale boxes show the choice)
  477. scaleSnapButton.setEnabled (scaleIndex() > 0);
  478. if (rows.count < 128 || foldToScale)
  479. updateKeyRows(); // the folded rows follow the scale
  480. repaint();
  481. };
  482. addAndMakeVisible (box);
  483. }
  484. addNoteLanes();
  485. laneBox.setTooltip (tr ("What the bottom lane edits"));
  486. laneBox.setSelectedId (1, juce::dontSendNotification);
  487. laneBox.setWantsKeyboardFocus (false);
  488. laneBox.setMouseClickGrabsKeyboardFocus (false);
  489. laneBox.onChange = [this] {
  490. if (fitKeysToNotes) // (round gap190og: the Live footer comes and goes with the Velocity lane)
  491. resized();
  492. repaint();
  493. };
  494. addAndMakeVisible (laneBox);
  495. // round gap190og (detail-047): Live's Velocity Controls (shown by resized only in the docked Live look)
  496. liveRandomize.setButtonText (tr ("Randomize"));
  497. liveRandomize.setTooltip (tr ("Randomize: the selected notes' velocities (all the notes with none selected) move at random by up to the amount beside it"));
  498. liveRandomize.setWantsKeyboardFocus (false);
  499. liveRandomize.onClick = [this] { liveRandomizeVelocity(); };
  500. addChildComponent (liveRandomize);
  501. liveRandomAmount = std::make_unique<LiveAmountBox>();
  502. liveRandomAmount->onEnter = [this] { liveRandomizeVelocity(); };
  503. addChildComponent (*liveRandomAmount);
  504. // round 190on (P10): "+" adds a lane above (only while stacked lanes are offered; core/StackedLanes.h)
  505. addLaneButton.setTooltip (tr ("Add a lane above (stacked lanes, LYNX)"));
  506. addLaneButton.setWantsKeyboardFocus (false);
  507. addLaneButton.setMouseClickGrabsKeyboardFocus (false);
  508. addLaneButton.onClick = [this] { addStackedLane(); };
  509. addChildComponent (addLaneButton);
  510. setOpaque (true); // paints every pixel: nothing behind it is redrawn while scrolling
  511. engine.addChangeListener (this);
  512. EditorGlobals::get().addChangeListener (this);
  513. refreshChannelBox();
  514. showingTimer = std::make_unique<ui::TimerWhileShowing> (*this, static_cast<juce::Timer&> (*this), 30); // (stopped while hidden; round 174f)
  515. }
  516. PianoRollComponent::~PianoRollComponent()
  517. {
  518. stopListening();
  519. previewNotes.releaseAll();
  520. EditorGlobals::get().removeChangeListener (this);
  521. engine.removeChangeListener (this);
  522. }
  523. juce::Rectangle<int> PianoRollComponent::gridArea() const
  524. {
  525. return getLocalBounds().withTrimmedLeft (keyboardWidth).withTrimmedTop (headerHeight)
  526. .withTrimmedRight (scrollBarSize).withTrimmedBottom (velocityHeight + eventPaneBarArea().getHeight() + liveFooterHeight());
  527. }
  528. // Round gap190og (detail-047): Live's footer under the editor lanes holds the Velocity Controls; LYNX draws it while the
  529. // dock shows the Velocity lane in the Live look (elsewhere 0: the Pattern layout's Piano roll and the FL look stay as they are)
  530. int PianoRollComponent::liveFooterHeight() const
  531. {
  532. return liveNotes() && ! mpeStacked && velocityHeight >= 24 && laneBox.getSelectedId() == laneVelocity ? liveFooterBar : 0;
  533. }
  534. void PianoRollComponent::liveFooterCheck()
  535. {
  536. if (liveFooterHeight() != laidFooter)
  537. {
  538. resized();
  539. repaint();
  540. }
  541. }
  542. void PianoRollComponent::liveRandomizeVelocity()
  543. {
  544. // the selected notes, or every note of the channel shown when none is selected (manual 10.5.12)
  545. const auto target = selectionOrAll();
  546. if (target.empty())
  547. return;
  548. const auto amount = liveRandomizeAmount;
  549. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
  550. editNotes ([&target, amount, seed] (Pattern& p) { cliploop::randomizeVelocity (p, target, amount, seed); });
  551. repaint();
  552. }
  553. juce::Rectangle<int> PianoRollComponent::eventPaneArea() const
  554. {
  555. const auto grid = gridArea();
  556. return { grid.getX(), grid.getBottom() + eventPaneBarArea().getHeight(), grid.getWidth(), velocityHeight };
  557. }
  558. juce::Rectangle<int> PianoRollComponent::velocityArea() const
  559. {
  560. if (! laneAreaOverride.isEmpty())
  561. return laneAreaOverride;
  562. if (stacked.empty())
  563. return eventPaneArea();
  564. return laneAreas().back();
  565. }
  566. // --- round 190on (research190oe P10): stacked controller lanes (core/StackedLanes.h) --------------------------------------
  567. std::vector<juce::Rectangle<int>> PianoRollComponent::laneAreas() const
  568. {
  569. const auto pane = eventPaneArea();
  570. if (stacked.empty())
  571. return { pane };
  572. std::vector<float> weights;
  573. for (const auto& l : stacked)
  574. weights.push_back (l->spec.weight);
  575. weights.push_back (bottomWeight);
  576. const auto heights = stackedlanes::heights (weights, pane.getHeight(), 0);
  577. std::vector<juce::Rectangle<int>> out;
  578. auto y = pane.getY();
  579. for (const auto h : heights)
  580. {
  581. out.push_back ({ pane.getX(), y, pane.getWidth(), h });
  582. y += h;
  583. }
  584. return out;
  585. }
  586. std::vector<std::pair<juce::Rectangle<int>, int>> PianoRollComponent::laneAreasForTests() const
  587. {
  588. std::vector<std::pair<juce::Rectangle<int>, int>> out;
  589. const auto areas = laneAreas();
  590. for (std::size_t i = 0; i < areas.size(); ++i)
  591. out.push_back ({ areas[i], i < stacked.size() ? stackedLaneId (*stacked[i]) : laneBox.getSelectedId() });
  592. return out;
  593. }
  594. PianoRollComponent::LaneScope::LaneScope (PianoRollComponent& o, int index)
  595. : owner (o), savedId (o.laneOverride), savedPainting (o.paintingLane), savedArea (o.laneAreaOverride)
  596. {
  597. owner.paintingLane = index;
  598. if (index >= 0)
  599. owner.enterLane (index);
  600. else
  601. {
  602. owner.laneOverride = 0;
  603. owner.laneAreaOverride = {};
  604. }
  605. }
  606. PianoRollComponent::LaneScope::~LaneScope()
  607. {
  608. owner.laneOverride = savedId;
  609. owner.paintingLane = savedPainting;
  610. owner.laneAreaOverride = savedArea;
  611. }
  612. void PianoRollComponent::enterLane (int index)
  613. {
  614. if (index < 0 || index >= (int) stacked.size())
  615. {
  616. laneOverride = 0;
  617. laneAreaOverride = {};
  618. return;
  619. }
  620. laneOverride = stackedLaneId (*stacked[(std::size_t) index]);
  621. laneAreaOverride = laneAreas()[(std::size_t) index];
  622. }
  623. int PianoRollComponent::stackedLaneId (const StackedLane& lane) const
  624. {
  625. if (lane.spec.target)
  626. {
  627. const auto it = std::find (eventTargets.begin(), eventTargets.end(), *lane.spec.target);
  628. return it == eventTargets.end() ? laneVelocity : eventLaneIdBase + (int) (it - eventTargets.begin());
  629. }
  630. return juce::jlimit (laneVelocity, laneVelocityRange, lane.spec.property);
  631. }
  632. juce::String PianoRollComponent::laneName() const
  633. {
  634. if (laneOverride != 0)
  635. for (const auto& l : stacked)
  636. if (stackedLaneId (*l) == laneOverride)
  637. return l->box.getText();
  638. return laneBox.getText();
  639. }
  640. int PianoRollComponent::stackedLaneAt (juce::Point<int> p) const
  641. {
  642. if (stacked.empty())
  643. return -1;
  644. const auto areas = laneAreas();
  645. for (std::size_t i = 0; i + 1 < areas.size(); ++i)
  646. if (areas[i].withX (0).withWidth (areas[i].getRight()).contains (p))
  647. return (int) i;
  648. return -1;
  649. }
  650. int PianoRollComponent::laneBoundaryAt (juce::Point<int> p) const
  651. {
  652. if (stacked.empty() || p.x < keyboardWidth)
  653. return -1;
  654. const auto areas = laneAreas();
  655. for (std::size_t i = 0; i + 1 < areas.size(); ++i)
  656. if (std::abs (p.y - areas[i].getBottom()) <= 2 && areas[i].getRight() > p.x)
  657. return (int) i;
  658. return -1;
  659. }
  660. bool PianoRollComponent::stackingEnabled() const
  661. {
  662. return stackedlanes::enabled (layoutstyle::current() == layoutstyle::Style::clipLaunch, stackedLanesExtra) && ! mpeStacked;
  663. }
  664. void PianoRollComponent::rebuildStackedBoxes()
  665. {
  666. for (auto& l : stacked)
  667. {
  668. auto& box = l->box;
  669. box.clear (juce::dontSendNotification);
  670. box.addItem (tr ("Velocity"), laneVelocity);
  671. box.addItem (tr ("Pan"), lanePan);
  672. box.addItem (tr ("Fine pitch"), laneFinePitch);
  673. box.addItem (tr ("Release"), laneRelease);
  674. box.addItem (tr ("Mod X"), laneModX);
  675. box.addItem (tr ("Mod Y"), laneModY);
  676. box.addItem (tr ("Chance"), laneChance);
  677. box.addItem (tr ("Velocity range (LYNX)"), laneVelocityRange);
  678. if (! eventTargets.empty())
  679. box.addSectionHeading (tr ("Pattern events"));
  680. for (int k = 0; k < (int) eventTargets.size(); ++k)
  681. box.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
  682. box.setSelectedId (stackedLaneId (*l), juce::dontSendNotification);
  683. }
  684. }
  685. void PianoRollComponent::loadStackedLanes()
  686. {
  687. for (auto& l : stacked)
  688. {
  689. removeChildComponent (&l->box);
  690. removeChildComponent (&l->close);
  691. }
  692. stacked.clear();
  693. stackingWas = stackingEnabled();
  694. if (stackingWas)
  695. for (const auto& spec : stackedlanes::fromText (stackedLanesSaved, &bottomWeight, laneVelocityRange))
  696. {
  697. auto lane = std::make_unique<StackedLane>();
  698. lane->spec = spec;
  699. stacked.push_back (std::move (lane));
  700. }
  701. for (auto& l : stacked)
  702. {
  703. auto* raw = l.get();
  704. raw->box.setTooltip (tr ("What this lane edits"));
  705. raw->box.setWantsKeyboardFocus (false);
  706. raw->box.setMouseClickGrabsKeyboardFocus (false);
  707. raw->box.onChange = [this, raw] {
  708. const auto id = raw->box.getSelectedId();
  709. if (id >= eventLaneIdBase && id - eventLaneIdBase < (int) eventTargets.size())
  710. raw->spec.target = eventTargets[(std::size_t) (id - eventLaneIdBase)];
  711. else
  712. {
  713. raw->spec.target.reset();
  714. raw->spec.property = id;
  715. }
  716. saveStackedLanes();
  717. repaint();
  718. };
  719. raw->close.setTooltip (tr ("Remove this lane"));
  720. raw->close.setWantsKeyboardFocus (false);
  721. raw->close.setMouseClickGrabsKeyboardFocus (false);
  722. raw->close.onClick = [this, raw] {
  723. for (int i = 0; i < (int) stacked.size(); ++i)
  724. if (stacked[(std::size_t) i].get() == raw)
  725. {
  726. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<PianoRollComponent> (this), i] {
  727. if (safe != nullptr)
  728. safe->removeStackedLane (i);
  729. });
  730. return;
  731. }
  732. };
  733. addAndMakeVisible (raw->box);
  734. addAndMakeVisible (raw->close);
  735. }
  736. // the lanes' event targets are in the choosers' lists
  737. rebuildLaneBox (std::nullopt, true);
  738. rebuildStackedBoxes();
  739. layoutEventPane();
  740. resized();
  741. repaint();
  742. }
  743. void PianoRollComponent::stackedLanesChanged()
  744. {
  745. loadStackedLanes();
  746. }
  747. void PianoRollComponent::saveStackedLanes()
  748. {
  749. std::vector<stackedlanes::Lane> specs;
  750. for (const auto& l : stacked)
  751. specs.push_back (l->spec);
  752. stackedLanesSaved = stackedlanes::toText (specs, bottomWeight);
  753. if (EditorGlobals::get().onOptionsChanged)
  754. EditorGlobals::get().onOptionsChanged();
  755. }
  756. void PianoRollComponent::addStackedLane()
  757. {
  758. if (! stackingEnabled() || (int) stacked.size() >= stackedlanes::maxAdded)
  759. return;
  760. // a property the lanes don't show yet (velocity, pan, mod X, mod Y, release, fine pitch, chance, then velocity again)
  761. int property = laneVelocity;
  762. for (const auto candidate : { laneVelocity, lanePan, laneModX, laneModY, laneRelease, laneFinePitch, laneChance })
  763. {
  764. const auto used = laneBox.getSelectedId() == candidate
  765. || std::any_of (stacked.begin(), stacked.end(), [&] (const auto& l) { return ! l->spec.target && l->spec.property == candidate; });
  766. if (! used)
  767. {
  768. property = candidate;
  769. break;
  770. }
  771. }
  772. addStackedLaneForSnapshot (property);
  773. }
  774. void PianoRollComponent::addStackedLaneForSnapshot (int property, std::optional<AutomationTarget> target)
  775. {
  776. std::vector<stackedlanes::Lane> specs;
  777. for (const auto& l : stacked)
  778. specs.push_back (l->spec);
  779. if ((int) specs.size() >= stackedlanes::maxAdded)
  780. return;
  781. stackedlanes::Lane lane;
  782. lane.property = property;
  783. lane.target = target;
  784. specs.insert (specs.begin(), lane); // (the new lane at the top: the lanes already there keep their places)
  785. stackedLanesSaved = stackedlanes::toText (specs, bottomWeight);
  786. loadStackedLanes();
  787. if (fitKeysToNotes) // (the docked editor grows its lanes' area, as its MPE tab does)
  788. layoutEventPane();
  789. saveStackedLanes();
  790. }
  791. void PianoRollComponent::removeStackedLane (int index)
  792. {
  793. if (index < 0 || index >= (int) stacked.size())
  794. return;
  795. std::vector<stackedlanes::Lane> specs;
  796. for (int i = 0; i < (int) stacked.size(); ++i)
  797. if (i != index)
  798. specs.push_back (stacked[(std::size_t) i]->spec);
  799. stackedLanesSaved = stackedlanes::toText (specs, bottomWeight);
  800. loadStackedLanes();
  801. saveStackedLanes();
  802. }
  803. void PianoRollComponent::dragInLaneForSnapshot (int lane, int fromX, int toX, float from, float to)
  804. {
  805. const auto areas = laneAreas();
  806. if (lane < 0 || lane >= (int) areas.size())
  807. return;
  808. const auto area = areas[(std::size_t) lane];
  809. const auto yOf = [&area] (float v) { return area.getBottom() - 2 - juce::roundToInt (v * (float) (area.getHeight() - 8)); };
  810. auto source = juce::Desktop::getInstance().getMainMouseSource();
  811. const auto now = juce::Time::getCurrentTime();
  812. const auto event = [&] (int x, float v, juce::ModifierKeys mods) {
  813. const juce::Point<float> at ((float) x, (float) yOf (v));
  814. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, this, this, now, at, now, 1, false);
  815. };
  816. const auto left = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  817. mouseDown (event (fromX, from, left));
  818. mouseDrag (event (toX, to, left));
  819. mouseUp (event (toX, to, {}));
  820. }
  821. // --- the event editor's divider (round 190fz; FL's TQuickSplitter, the facts in core/EventPaneSplit.h) ---------------
  822. namespace
  823. {
  824. juce::File eventPaneFile() { return platform::settingsFile ("piano-roll-event-pane.txt"); }
  825. } // namespace
  826. evpane::State& PianoRollComponent::eventPaneState()
  827. {
  828. static evpane::State state = evpane::fromText (eventPaneFile().loadFileAsString().toStdString());
  829. return state;
  830. }
  831. void PianoRollComponent::saveEventPaneState()
  832. {
  833. eventPaneFile().replaceWithText (juce::String (evpane::toText (eventPaneState())));
  834. }
  835. juce::Rectangle<int> PianoRollComponent::eventPaneBarArea() const
  836. {
  837. if (fitKeysToNotes) // the Clip-launch dock keeps its short fixed lane (Live's detail view; no divider there)
  838. return {};
  839. return { 0, eventPaneBarTop, getWidth(), evpane::barThickness };
  840. }
  841. void PianoRollComponent::layoutEventPane()
  842. {
  843. if (fitKeysToNotes)
  844. {
  845. // (round 190jd: the MPE tab's lanes, 40 px each as Live's, + the "Show Lane" footer; at most half of the dock,
  846. // at least 22 px a lane, so the notes stay in view; core/MpeTab.h)
  847. if (mpeStacked)
  848. velocityHeight = mpetab::areaHeight (mpetab::countOf (mpeShownLanes), getHeight() - headerHeight);
  849. else if (! stacked.empty()) // round 190on (P10): 40 px a lane, as the MPE tab's, at most half of the dock
  850. velocityHeight = juce::jlimit (compactVelocityHeight, juce::jmax (compactVelocityHeight, (getHeight() - headerHeight) / 2), 40 * ((int) stacked.size() + 1));
  851. eventPaneBarTop = getHeight() - velocityHeight - liveFooterHeight();
  852. return;
  853. }
  854. // the bar's travel: from under the ruler (the grid folded away) to the bottom edge (the event editor folded away);
  855. // the remembered place is a fraction of it, so a taller or shorter window keeps the proportion (FL)
  856. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  857. eventPaneBarTop = evpane::barTopOf (eventPaneState().aspect, top, bottom);
  858. velocityHeight = juce::jmax (0, getHeight() - eventPaneBarTop - evpane::barThickness);
  859. }
  860. void PianoRollComponent::eventPaneChanged()
  861. {
  862. resized();
  863. repaint();
  864. ui::Hint hint; // FL's hint bar shows the place as a percentage while it changes ("80%")
  865. hint.value = juce::String (evpane::percentOf (eventPaneState().aspect)) + "%";
  866. ui::postHint (hint);
  867. }
  868. void PianoRollComponent::moveEventPaneBar (int y)
  869. {
  870. if (fitKeysToNotes)
  871. return;
  872. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  873. eventPaneState().aspect = evpane::aspectOf (evpane::clampBar (y, top, bottom), top, bottom);
  874. eventPaneChanged();
  875. }
  876. void PianoRollComponent::toggleEventPaneAlternate()
  877. {
  878. if (fitKeysToNotes)
  879. return;
  880. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  881. evpane::toggleAlternate (eventPaneState(), evpane::aspectOf (eventPaneBarTop, top, bottom));
  882. eventPaneChanged();
  883. saveEventPaneState();
  884. }
  885. void PianoRollComponent::resetEventPane()
  886. {
  887. if (fitKeysToNotes)
  888. return;
  889. evpane::resetToDefault (eventPaneState());
  890. eventPaneChanged();
  891. saveEventPaneState();
  892. }
  893. double PianoRollComponent::tickToX (double tick) const
  894. {
  895. return keyboardWidth + (tick - scrollTicks) * pixelsPerTick;
  896. }
  897. double PianoRollComponent::xToTick (int x) const
  898. {
  899. return (x - keyboardWidth) / pixelsPerTick + scrollTicks;
  900. }
  901. int PianoRollComponent::keyToY (int key) const
  902. {
  903. return headerHeight + rowFor (key) * rowHeight - scrollY;
  904. }
  905. int PianoRollComponent::rowFor (int key) const noexcept
  906. {
  907. key = juce::jlimit (0, 127, key);
  908. const auto row = rows.rowOfKey[(std::size_t) key];
  909. return row >= 0 ? row : rows.rowOfKey[(std::size_t) rows.step (key, 0)]; // a folded key: the row above it
  910. }
  911. void PianoRollComponent::updateKeyRows()
  912. {
  913. // keep the key at the top of the view where it is when the rows change (fold on/off, another scale)
  914. const auto topKey = yToKey (headerHeight);
  915. rows = ! padRows.empty() ? notetools::keyRowsOf (padRows) : notetools::keyRows (scaleRoot(), scaleIndex(), foldToScale);
  916. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), rowFor (topKey) * rowHeight);
  917. updateScrollBars();
  918. repaint();
  919. }
  920. std::vector<int> PianoRollComponent::wantedPadRows() const
  921. {
  922. const auto& song = engine.getSong();
  923. const auto channel = engine.getSelectedChannel();
  924. if (! EditorGlobals::get().clipLaunchWorkflow || allChannels || channel < 0 || channel >= (int) song.channels.size()
  925. || ! rack::isDrumRack (song.channels[(std::size_t) channel]))
  926. return {};
  927. return rack::filledPadKeys (*rack::rackOf (song.channels[(std::size_t) channel].patcher));
  928. }
  929. void PianoRollComponent::syncPadRows()
  930. {
  931. if (auto wanted = wantedPadRows(); wanted != padRows)
  932. {
  933. padRows = std::move (wanted);
  934. updateKeyRows();
  935. }
  936. }
  937. void PianoRollComponent::setFoldToScale (bool on)
  938. {
  939. foldToScale = on;
  940. updateKeyRows();
  941. }
  942. int PianoRollComponent::yToKey (int y) const
  943. {
  944. const auto row = juce::jlimit (0, juce::jmax (0, rows.count - 1), (y - headerHeight + scrollY) / rowHeight);
  945. return rows.keyOfRow[(std::size_t) row];
  946. }
  947. void PianoRollComponent::setKeyStyle (pianokeys::Style style)
  948. {
  949. if (style == keyStyle)
  950. return;
  951. keyStyle = style;
  952. if (EditorGlobals::get().onOptionsChanged)
  953. EditorGlobals::get().onOptionsChanged(); // (the main window saves it and repaints the other editors)
  954. repaint();
  955. }
  956. int PianoRollComponent::keyboardKeyAt (int x, int y) const
  957. {
  958. const auto key = yToKey (y);
  959. if (! pianokeys::whiteKeysMeet (keyStyle) || folded())
  960. return key;
  961. // "Piano keys" / FL's keys: right of a black key the white keys above and below it meet in the middle of its row
  962. const auto next = pianokeys::keyAt (keyStyle, key, y - keyToY (key), rowHeight, x, blackKeyWidth);
  963. return juce::isPositiveAndBelow (next, 128) && rows.shown (next) ? next : key;
  964. }
  965. std::int64_t PianoRollComponent::gridTicks() const
  966. {
  967. if (liveGridOn()) // round 190hr: the reference's grid while docked in the Clip-launch detail view
  968. return liveGrid.snap ? std::max<std::int64_t> (1, livegrid::stepTicks (liveGrid, pixelsPerTick)) : 1;
  969. const auto bar = engine.getSong().barTicks();
  970. const auto& option = grid::resolve (snapBox);
  971. switch (option.kind)
  972. {
  973. case grid::Kind::none: return 1;
  974. case grid::Kind::ticks: return option.ticks;
  975. case grid::Kind::bar: return bar;
  976. case grid::Kind::screen:
  977. case grid::Kind::nearest: break;
  978. }
  979. return noteedit::screenStep (pixelsPerTick, bar);
  980. }
  981. std::vector<std::int64_t> PianoRollComponent::snapCandidates() const
  982. {
  983. // edges of this channel's notes (except the ones being dragged) and of the visible ghosts
  984. std::vector<std::int64_t> out;
  985. const auto& notes = currentPattern (engine.getSong()).notes;
  986. for (int i = 0; i < (int) notes.size(); ++i)
  987. {
  988. const auto& n = notes[(std::size_t) i];
  989. if ((! edits (n) && (! showGhosts || ! ghostShown (n.channel))) || std::find (dragIndices.begin(), dragIndices.end(), i) != dragIndices.end())
  990. continue;
  991. out.push_back (n.start);
  992. out.push_back (n.start + n.length);
  993. }
  994. return out;
  995. }
  996. std::int64_t PianoRollComponent::snap (double tick, bool enabled) const
  997. {
  998. if (! enabled)
  999. return (std::int64_t) std::floor (tick);
  1000. if (! liveGridOn() && grid::resolve (snapBox).kind == grid::Kind::nearest)
  1001. return noteedit::snapNearest (tick, snapCandidates(), 10.0 / pixelsPerTick, gridTicks());
  1002. return noteedit::snapDown (tick, gridTicks());
  1003. }
  1004. std::int64_t PianoRollComponent::newNoteLength() const
  1005. {
  1006. const auto fixed = EditorGlobals::get().getDefaultNoteLength();
  1007. return fixed > 0 ? fixed : lastLength;
  1008. }
  1009. std::int64_t PianoRollComponent::viewLengthTicks() const
  1010. {
  1011. const auto& song = engine.getSong();
  1012. const auto bar = song.barTicks();
  1013. // pattern + 4 bars of headroom to grow
  1014. return currentPattern (song).effectiveLength (song.meter()) + 4 * bar;
  1015. }
  1016. void PianoRollComponent::updateScrollBars()
  1017. {
  1018. const auto grid = gridArea();
  1019. const auto total = (double) viewLengthTicks();
  1020. hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
  1021. hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
  1022. vBar.setRangeLimits (0.0, (double) rows.count * rowHeight, juce::dontSendNotification);
  1023. vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
  1024. scrollTicks = hBar.getCurrentRangeStart();
  1025. scrollY = (int) vBar.getCurrentRangeStart();
  1026. overview.minLength = grid.getWidth() / (maxPixelsPerTick);
  1027. overview.setRange (total, scrollTicks, grid.getWidth() / pixelsPerTick);
  1028. }
  1029. void PianoRollComponent::setTitleBarInsets (int left, int right)
  1030. {
  1031. if (left != titleInsetLeft || right != titleInsetRight)
  1032. {
  1033. titleInsetLeft = left;
  1034. titleInsetRight = right;
  1035. resized();
  1036. }
  1037. }
  1038. void PianoRollComponent::resized()
  1039. {
  1040. layoutEventPane(); // (round 190fz: the grid / event editor heights from the divider's place)
  1041. const auto h = toolbarHeight - 6;
  1042. auto bar = juce::Rectangle<int> (4 + titleInsetLeft, 3, juce::jmax (0, getWidth() - 8 - titleInsetLeft - titleInsetRight), h);
  1043. // groups that don't fit in a narrow window are hidden (the tools and the grid always show). The menu button always
  1044. // keeps its place: the optional groups only take what is left beside it (round 190j: on a 1024 px screen the
  1045. // groups before it used up the bar and the Piano roll menu could not be opened).
  1046. const auto reserved = h + 6;
  1047. auto place = [&bar, reserved] (juce::Component& c, int width, bool optional = false) {
  1048. const auto fits = ! optional || width <= bar.getWidth() - reserved;
  1049. c.setVisible (fits);
  1050. c.setBounds (fits ? bar.removeFromLeft (juce::jmin (width, bar.getWidth())) : juce::Rectangle<int>());
  1051. bar.removeFromLeft (juce::jmin (6, bar.getWidth()));
  1052. };
  1053. place (playButton, h);
  1054. place (channelBox, 150);
  1055. place (tools, tools.getIdealWidth (h));
  1056. if (liveGridOn()) // round 190hr: the reference's grid value in place of FL's snap box
  1057. {
  1058. snapBox.setVisible (false);
  1059. liveGridButton.setButtonText (liveGrid.snap ? juce::String (livegrid::stepText (gridTicks(), liveGrid.triplet)) + juce::String::fromUTF8 (" \xe2\x96\xbe")
  1060. : tr ("Off") + juce::String::fromUTF8 (" \xe2\x96\xbe"));
  1061. place (liveGridButton, 72);
  1062. }
  1063. else
  1064. {
  1065. liveGridButton.setVisible (false);
  1066. place (snapBox, 128);
  1067. }
  1068. place (ghostButton, h);
  1069. place (followButton, h);
  1070. place (slideButton, h, true);
  1071. place (colourButton, h, true);
  1072. // the chord stamp shrinks to its icon and arrow before it is hidden (discussion #10; FL's stamp is an icon button)
  1073. place (chordBox, 100 <= bar.getWidth() - reserved ? 100 : pianoroll::compactChordBoxWidth, true);
  1074. if (splitScaleBoxes()) // (issue #203: docked, the root and the scale apart, as Live's Clip View and BandLab)
  1075. {
  1076. scaleBox.setVisible (false);
  1077. place (scaleRootBox, 52, true);
  1078. if (scaleRootBox.isVisible())
  1079. place (scaleNameBox, 124, true);
  1080. else
  1081. scaleNameBox.setVisible (false);
  1082. }
  1083. else
  1084. {
  1085. scaleRootBox.setVisible (false);
  1086. scaleNameBox.setVisible (false);
  1087. place (scaleBox, 164, true);
  1088. }
  1089. if (splitScaleBoxes() ? scaleNameBox.isVisible() : scaleBox.isVisible())
  1090. place (scaleSnapButton, h);
  1091. else
  1092. scaleSnapButton.setVisible (false);
  1093. place (moreButton, h);
  1094. place (chordLabel, 84, true);
  1095. // round 190on (P10): the stacked lanes follow the switch and the layout; with them offered, the "+" sits right of the
  1096. // bottom lane's chooser and each added lane has its chooser and "×" (FL's single lane is unchanged otherwise)
  1097. if (stackingWas != stackingEnabled())
  1098. return loadStackedLanes(); // (it lays everything out again)
  1099. const auto offered = stackingWas && velocityHeight >= 24 && ! mpeStacked;
  1100. const auto buttonSide = 20, chooserWidth = keyboardWidth - 4 - (offered ? buttonSide + 2 : 0);
  1101. laneBox.setBounds (2, velocityArea().getY() + 4, chooserWidth, 20);
  1102. addLaneButton.setBounds (2 + chooserWidth + 2, velocityArea().getY() + 4, buttonSide, buttonSide);
  1103. laidFooter = liveFooterHeight();
  1104. if (const auto footer = laidFooter; footer > 0)
  1105. {
  1106. // Live's footer (capture x 500…559 the button, 566…603 the amount; both 13 px high, 3 px under the footer's line)
  1107. const auto y = getHeight() - footer + 3;
  1108. // (Live: the lane chooser sits in the footer, at its left; rollup 0.1.31 step 5: with stacked lanes offered, round
  1109. // 190on's "+" stays beside it there, at the footer's size)
  1110. const auto footerSide = 15;
  1111. laneBox.setBounds (4, y - 1, keyboardWidth - 8 - (offered ? footerSide + 2 : 0), 15);
  1112. addLaneButton.setBounds (laneBox.getRight() + 2, y - 1, footerSide, footerSide);
  1113. liveRandomize.setBounds (keyboardWidth + 22, y, 60, 13);
  1114. liveRandomAmount->setBounds (liveRandomize.getRight() + 6, y, 38, 13);
  1115. liveRandomize.setVisible (true);
  1116. liveRandomAmount->setVisible (true);
  1117. }
  1118. else
  1119. {
  1120. liveRandomize.setVisible (false);
  1121. liveRandomAmount->setVisible (false);
  1122. }
  1123. laneBox.setVisible (velocityHeight >= 24 && ! mpeStacked); // (the event editor folded away: FL hides its target panel too; the MPE tab names its lanes)
  1124. addLaneButton.setVisible (offered && (int) stacked.size() < stackedlanes::maxAdded);
  1125. {
  1126. const auto areas = laneAreas();
  1127. for (std::size_t i = 0; i < stacked.size() && i < areas.size(); ++i)
  1128. {
  1129. const auto shown = offered && areas[i].getHeight() >= 22;
  1130. stacked[i]->box.setBounds (2, areas[i].getY() + juce::jmin (4, (areas[i].getHeight() - 20) / 2), chooserWidth, 20);
  1131. stacked[i]->close.setBounds (2 + chooserWidth + 2, stacked[i]->box.getY(), buttonSide, buttonSide);
  1132. stacked[i]->box.setVisible (shown);
  1133. stacked[i]->close.setVisible (shown);
  1134. }
  1135. }
  1136. overview.setBounds (keyboardWidth, toolbarHeight, getWidth() - keyboardWidth - zoomWheelSize, overviewHeight);
  1137. vBar.setBounds (getWidth() - scrollBarSize, headerHeight, scrollBarSize, gridArea().getHeight());
  1138. updateScrollBars();
  1139. }
  1140. void PianoRollComponent::squeezeToolbarForSnapshot (int pixels)
  1141. {
  1142. setTitleBarInsets (titleInsetLeft, titleInsetRight + pixels);
  1143. }
  1144. void PianoRollComponent::scrollToNotes (bool fitPattern)
  1145. {
  1146. const auto& song = engine.getSong();
  1147. int low = 128, high = -1;
  1148. for (const auto& n : currentPattern (song).notes)
  1149. if (edits (n))
  1150. {
  1151. low = juce::jmin (low, n.key);
  1152. high = juce::jmax (high, n.key);
  1153. }
  1154. refreshChannelBox();
  1155. if (fitKeysToNotes && high >= 0 && gridArea().getHeight() > 0) // docked: every note's row in the short view, as far as the key height allows
  1156. {
  1157. const auto span = std::abs (rowFor (low) - rowFor (high)) + 3;
  1158. rowHeight = juce::jlimit (gesture::minKeyHeight, undockedRowHeight, gridArea().getHeight() / span);
  1159. }
  1160. const auto centreKey = high >= 0 ? (low + high) / 2 : 66;
  1161. scrollY = rowFor (centreKey) * rowHeight - gridArea().getHeight() / 2;
  1162. scrollTicks = 0.0;
  1163. // FL opens the Piano Roll with the whole pattern across the view (at least one bar)
  1164. if (fitPattern && gridArea().getWidth() > 0)
  1165. {
  1166. const auto bar = (double) song.barTicks();
  1167. const auto length = juce::jmax (bar, (double) currentPattern (song).effectiveLength (song.meter()));
  1168. pixelsPerTick = juce::jlimit (4.0 / ticksPerStep, 64.0 / ticksPerStep, gridArea().getWidth() / length);
  1169. }
  1170. updateScrollBars();
  1171. repaint();
  1172. }
  1173. // --- selection ---------------------------------------------------------------
  1174. std::vector<int> PianoRollComponent::chordIntervals() const
  1175. {
  1176. const auto index = juce::jlimit (0, (int) chords().size() - 1, chordBox.getSelectedId() - 1);
  1177. auto intervals = chords()[(std::size_t) index].intervals;
  1178. // FL 2026's top-down stamp (REA round 153): the clicked key is the chord's highest note
  1179. if (chordTopDown && intervals.size() > 1)
  1180. {
  1181. const auto top = *std::max_element (intervals.begin(), intervals.end());
  1182. for (auto& i : intervals)
  1183. i -= top;
  1184. std::reverse (intervals.begin(), intervals.end()); // the clicked (top) note first: it leads the drag
  1185. }
  1186. return intervals;
  1187. }
  1188. // --- round 190nu: key regions and the Scale degree chord (core/KeyRegions.h) ------------------------------------------
  1189. keyregions::Degrees PianoRollComponent::scaleDegreesAt (std::int64_t tick) const
  1190. {
  1191. const auto state = keyregions::stateAt (currentPattern (engine.getSong()), tick);
  1192. if (state.kind == keyregions::State::key)
  1193. return keyregions::degreesOf (state.value);
  1194. if (state.kind == keyregions::State::none)
  1195. return {};
  1196. if (isAutoScale()) // (the guessed key: 0..11 major, 12..23 minor)
  1197. {
  1198. if (autoKey < 0)
  1199. return {};
  1200. return autoKey < 12 ? keyregions::Degrees { autoKey, { 0, 2, 4, 5, 7, 9, 11 } } : keyregions::Degrees { autoKey - 12, { 0, 2, 3, 5, 7, 8, 10 } };
  1201. }
  1202. if (scaleIndex() > 0)
  1203. return { scaleRoot(), notetools::scales()[(std::size_t) scaleIndex()].intervals };
  1204. return {};
  1205. }
  1206. std::vector<int> PianoRollComponent::stampKeys (int key, std::int64_t tick) const
  1207. {
  1208. std::vector<int> out;
  1209. const auto add = [&out] (int k) {
  1210. if (k >= 0 && k <= 127 && std::find (out.begin(), out.end(), k) == out.end())
  1211. out.push_back (k);
  1212. };
  1213. if (isDegreeStamp())
  1214. {
  1215. int root = key;
  1216. const auto chord = keyregions::diatonicChord (scaleDegreesAt (tick), key, degreeSize, degreeInversion, root);
  1217. if (chord.empty())
  1218. add (key); // (no key here: a single note; the hint says so)
  1219. else
  1220. {
  1221. // the root leads the drag, then the other notes from the lowest up
  1222. const auto rootAt = std::find_if (chord.begin(), chord.end(), [] (int i) { return ((i % 12) + 12) % 12 == 0; });
  1223. add (root + (rootAt != chord.end() ? *rootAt : 0));
  1224. for (const auto i : chord)
  1225. add (root + i);
  1226. }
  1227. return out;
  1228. }
  1229. const auto snapped = snapKey (key);
  1230. for (const auto interval : chordIntervals())
  1231. if (snapped + interval <= 127 && snapped + interval >= 0)
  1232. add (snapKey (snapped + interval)); // with scale snap the chord follows the scale
  1233. return out;
  1234. }
  1235. void PianoRollComponent::addKeyMarker (std::int64_t tick, const keyregions::State& state)
  1236. {
  1237. engine.editSong ([tick, state] (Song& s) { keyregions::addKeyMarker (currentPattern (s), tick, state); });
  1238. repaint();
  1239. }
  1240. void PianoRollComponent::addKeyRegion (std::int64_t from, std::int64_t to, const keyregions::State& state)
  1241. {
  1242. engine.editSong ([from, to, state] (Song& s) { keyregions::addKeyRegion (currentPattern (s), from, to, state); });
  1243. repaint();
  1244. }
  1245. int PianoRollComponent::scaleIndex() const
  1246. {
  1247. const auto id = scaleBox.getSelectedId();
  1248. return id <= 1 || id == autoScaleId ? 0 : id / 100;
  1249. }
  1250. int PianoRollComponent::scaleRoot() const
  1251. {
  1252. const auto id = scaleBox.getSelectedId();
  1253. return id <= 1 || id == autoScaleId ? 0 : (id % 100) - 1;
  1254. }
  1255. bool PianoRollComponent::inScale (int key) const
  1256. {
  1257. if (isAutoScale()) // (round 190jv: the guessed key's scale; no guess, no key in it)
  1258. return scaledetect::inScale (autoKey, key);
  1259. return scaleIndex() > 0 && notetools::inScale (key, scaleRoot(), scaleIndex());
  1260. }
  1261. // FL's Automatic scale highlighting (round 190jv, core/ScaleDetect.h): FL guesses again after every edit and selection
  1262. // change; here the guess is made again when the song, the pattern, the channel or the selection changed since the last
  1263. // paint (no timer, nothing while idle)
  1264. void PianoRollComponent::updateAutoKey()
  1265. {
  1266. if (! isAutoScale())
  1267. return;
  1268. const auto stamp = engine.getSongStamp();
  1269. const auto& song = engine.getSong();
  1270. const auto channel = engine.getSelectedChannel();
  1271. if (autoKeyValid && stamp == autoKeyStamp && song.currentPattern == autoKeyPattern && channel == autoKeyChannel
  1272. && allChannels == autoKeyAllChannels && selection == autoKeySelection)
  1273. return;
  1274. autoKeyValid = true;
  1275. autoKeyStamp = stamp;
  1276. autoKeyPattern = song.currentPattern;
  1277. autoKeyChannel = channel;
  1278. autoKeyAllChannels = allChannels;
  1279. autoKeySelection = selection;
  1280. autoKey = scaledetect::detect (currentPattern (song).notes, [this] (const Note& n) { return edits (n); },
  1281. [this] (int i) { return isSelected (i); });
  1282. }
  1283. int PianoRollComponent::snapKey (int key) const
  1284. {
  1285. return scalesnap::drawKey (snapScale(), key);
  1286. }
  1287. scalesnap::Scale PianoRollComponent::snapScale() const
  1288. {
  1289. return { scaleRoot(), scaleIndex(), scaleSnap };
  1290. }
  1291. void PianoRollComponent::setScaleSnap (bool on)
  1292. {
  1293. scaleSnap = on;
  1294. scaleSnapButton.setToggleState (on, juce::dontSendNotification);
  1295. publishScale();
  1296. repaint();
  1297. }
  1298. // Issue #203 (round 190ll): the docked root / scale boxes show the scale box's choice (a root chosen while no scale is
  1299. // stays in the root box and goes with the scale picked next)
  1300. void PianoRollComponent::refreshScaleBoxes()
  1301. {
  1302. const auto scale = scaleIndex();
  1303. if (scale > 0)
  1304. splitRoot = scaleRoot();
  1305. scaleRootBox.setSelectedId (splitRoot + 1, juce::dontSendNotification);
  1306. scaleNameBox.setSelectedId (isAutoScale() ? autoScaleId : scale > 0 ? scale * 100 : 1, juce::dontSendNotification);
  1307. scaleRootBox.setEnabled (! isAutoScale()); // (Automatic guesses the root too)
  1308. }
  1309. void PianoRollComponent::publishScale()
  1310. {
  1311. engine.setInputScale (scaleSnap ? scaleIndex() : 0, scaleRoot());
  1312. }
  1313. bool PianoRollComponent::isSelected (int index) const
  1314. {
  1315. return std::binary_search (selection.begin(), selection.end(), index);
  1316. }
  1317. std::vector<int> PianoRollComponent::channelNotes() const
  1318. {
  1319. const auto& notes = currentPattern (engine.getSong()).notes;
  1320. std::vector<int> out;
  1321. for (int i = 0; i < (int) notes.size(); ++i)
  1322. if (edits (notes[(std::size_t) i]) && rows.shown (notes[(std::size_t) i].key)) // (folded-away notes are left alone)
  1323. out.push_back (i);
  1324. return out;
  1325. }
  1326. std::vector<int> PianoRollComponent::selectionOrAll() const
  1327. {
  1328. return selection.empty() ? channelNotes() : selection;
  1329. }
  1330. void PianoRollComponent::setSelection (std::vector<int> indices)
  1331. {
  1332. std::sort (indices.begin(), indices.end());
  1333. indices.erase (std::unique (indices.begin(), indices.end()), indices.end());
  1334. selection = std::move (indices);
  1335. repaint();
  1336. }
  1337. void PianoRollComponent::selectAll()
  1338. {
  1339. setSelection (channelNotes());
  1340. }
  1341. bool PianoRollComponent::refuseFrozenEdit()
  1342. {
  1343. const auto& song = engine.getSong();
  1344. const auto channel = engine.getSelectedChannel();
  1345. if (channel < 0 || channel >= (int) song.channels.size() || ! song.channels[(std::size_t) channel].freeze.on())
  1346. return false;
  1347. ui::postNotice ({ tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)", { juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()) }), {} },
  1348. 3000);
  1349. return true;
  1350. }
  1351. void PianoRollComponent::editNotes (const std::function<void (Pattern&)>& edit, bool undoable)
  1352. {
  1353. if (refuseFrozenEdit())
  1354. return;
  1355. engine.editSong ([&edit] (Song& s) { edit (currentPattern (s)); }, undoable);
  1356. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  1357. }
  1358. void PianoRollComponent::sortNotes()
  1359. {
  1360. auto tracked = selection;
  1361. tracked.push_back (dragNote);
  1362. // only reorders: no undo step of its own needed
  1363. engine.editSong ([&tracked] (Song& s) { noteedit::sortTracking (currentPattern (s), tracked); }, false);
  1364. dragNote = tracked.back();
  1365. tracked.pop_back();
  1366. setSelection (tracked);
  1367. }
  1368. juce::Rectangle<float> PianoRollComponent::stretchHandle() const
  1369. {
  1370. // a tab on the right end of the selection, vertically centred on it (clamped into the grid)
  1371. const auto& notes = currentPattern (engine.getSong()).notes;
  1372. std::int64_t start = 0, end = 0;
  1373. int top = -1, bottom = 128;
  1374. bool any = false;
  1375. for (auto i : selection)
  1376. {
  1377. if (i < 0 || i >= (int) notes.size() || ! edits (notes[(std::size_t) i]))
  1378. continue;
  1379. const auto& n = notes[(std::size_t) i];
  1380. start = any ? juce::jmin (start, n.start) : n.start;
  1381. end = any ? juce::jmax (end, n.start + n.length) : n.start + n.length;
  1382. top = juce::jmax (top, n.key);
  1383. bottom = juce::jmin (bottom, n.key);
  1384. any = true;
  1385. }
  1386. if (! any || end <= start)
  1387. return {};
  1388. const auto grid = gridArea().toFloat();
  1389. const auto x = (float) tickToX ((double) end);
  1390. const auto y0 = (float) keyToY (top), y1 = (float) (keyToY (bottom) + rowHeight);
  1391. const auto cy = juce::jlimit (grid.getY() + 10.0f, juce::jmax (grid.getY() + 10.0f, grid.getBottom() - 10.0f), (y0 + y1) * 0.5f);
  1392. const auto r = juce::Rectangle<float> (x + 2.0f, cy - 9.0f, 9.0f, 18.0f);
  1393. return grid.intersects (r) ? r : juce::Rectangle<float>();
  1394. }
  1395. void PianoRollComponent::drumPaintAt (juce::Point<int> p, bool snapOn)
  1396. {
  1397. // one short hit per grid cell and key, on whatever key is under the mouse (FL's drum painting)
  1398. const auto cell = juce::jmax<std::int64_t> (1, snapOn ? gridTicks() : ticksPerStep);
  1399. const auto start = juce::jmax<std::int64_t> (0, snapOn ? snap (xToTick (p.x), true) : noteedit::snapDown (xToTick (p.x), cell));
  1400. const auto key = snapKey (yToKey (p.y));
  1401. if (start == lastDrumCell && key == lastDrumKey)
  1402. return;
  1403. lastDrumCell = start;
  1404. lastDrumKey = key;
  1405. const auto channel = engine.getSelectedChannel();
  1406. if (polish::hasNoteInCell (currentPattern (engine.getSong()), channel, key, start, cell))
  1407. return;
  1408. Note n;
  1409. noteTemplate.applyTo (n);
  1410. n.start = start;
  1411. n.length = cell;
  1412. n.key = key;
  1413. n.channel = channel;
  1414. n.colour = noteColour;
  1415. editNotes ([&n] (Pattern& pat) { noteedit::paste (pat, { n }, 0); });
  1416. if (key != previewKey)
  1417. previewEdit (key, n.velocity);
  1418. }
  1419. // --- painting ------------------------------------------------------------------
  1420. void PianoRollComponent::paintOverview (juce::Graphics& g, juce::Rectangle<float> area, double total)
  1421. {
  1422. // the channel's notes across the whole view length, pitch mapped onto the strip's height; the part past
  1423. // the pattern's end is darker; bar lines every bar (every 4 when they get dense)
  1424. using namespace theme::colour;
  1425. const auto& song = engine.getSong();
  1426. const auto& pattern = currentPattern (song);
  1427. const auto channel = engine.getSelectedChannel();
  1428. const auto scale = area.getWidth() / juce::jmax (1.0, total);
  1429. const auto bar = (double) song.barTicks();
  1430. const auto end = (float) (pattern.effectiveLength (song.meter()) * scale);
  1431. g.setColour (bg2);
  1432. g.fillRect (area.withWidth (juce::jmin (area.getWidth(), end)));
  1433. const auto every = bar * scale < 6.0 ? 4 : 1;
  1434. g.setColour (gridBar.withAlpha (0.6f));
  1435. for (int b = every; b * bar < total; b += every)
  1436. g.fillRect ((float) (area.getX() + b * bar * scale), area.getY(), 1.0f, area.getHeight());
  1437. int low = 128, high = -1;
  1438. for (const auto& n : pattern.notes)
  1439. if (edits (n))
  1440. {
  1441. low = juce::jmin (low, n.key);
  1442. high = juce::jmax (high, n.key);
  1443. }
  1444. if (high < 0)
  1445. return;
  1446. const auto span = (float) juce::jmax (12, high - low + 1);
  1447. const auto mid = (low + high) / 2.0f;
  1448. const auto inner = area.reduced (0.0f, 2.0f);
  1449. auto colour = accent;
  1450. if (channel < (int) song.channels.size() && song.channels[(std::size_t) channel].colour != 0)
  1451. colour = theme::tame (juce::Colour (song.channels[(std::size_t) channel].colour));
  1452. colour = colour.interpolatedWith (textPrimary, 0.35f); // reads on the dark strip at any channel colour
  1453. for (const auto& n : pattern.notes)
  1454. {
  1455. if (! edits (n))
  1456. continue;
  1457. const auto y = inner.getCentreY() - ((float) n.key - mid) / span * inner.getHeight();
  1458. const auto x = area.getX() + (float) (n.start * scale);
  1459. g.setColour (n.muted ? colour.withAlpha (0.35f) : colour);
  1460. g.fillRect (x, juce::jlimit (inner.getY(), inner.getBottom() - 2.0f, y - 1.0f),
  1461. juce::jmax (1.0f, (float) (n.length * scale) - 0.5f), 2.0f);
  1462. }
  1463. }
  1464. bool PianoRollComponent::liveNotes() const { return fitKeysToNotes && ! liveNoteColour.isTransparent() && theme::livelook::active(); }
  1465. void PianoRollComponent::paint (juce::Graphics& g)
  1466. {
  1467. const uitrace::Scope trace ("PianoRollComponent paint", true, g.getClipBounds());
  1468. const auto& song = engine.getSong();
  1469. const auto& pattern = currentPattern (song);
  1470. const auto channel = engine.getSelectedChannel();
  1471. const auto grid = gridArea();
  1472. const auto patternLength = pattern.effectiveLength (song.meter());
  1473. const auto bar = song.barTicks();
  1474. const auto snapGrid = gridTicks();
  1475. updateAutoKey(); // (round 190jv: View › Scale highlighting › Automatic)
  1476. // the overview follows the notes (edits, undo, another channel or pattern) and the view
  1477. {
  1478. // (round 190gp: hashed again only when the song, the pattern or the channel changed since the last paint;
  1479. // LYNX_PAINT_SAVINGS=0 hashes on every paint, as before)
  1480. const auto stamp = engine.getSongStamp();
  1481. if (! ui::paintSavings() || stamp != overviewStamp || song.currentPattern != overviewPattern || channel != overviewChannel)
  1482. {
  1483. overviewStamp = stamp;
  1484. overviewPattern = song.currentPattern;
  1485. overviewChannel = channel;
  1486. auto signature = (std::size_t) song.currentPattern * 1000003u + (std::size_t) channel * 7919u + pattern.notes.size();
  1487. for (const auto& n : pattern.notes)
  1488. signature = signature * 31u + (std::size_t) (n.start * 131 + n.length * 7 + n.key + n.channel * 257 + (n.muted ? 1 : 0));
  1489. if (signature != overviewSignature)
  1490. {
  1491. overviewSignature = signature;
  1492. overview.repaint();
  1493. }
  1494. }
  1495. overview.setRange ((double) viewLengthTicks(), scrollTicks, grid.getWidth() / pixelsPerTick);
  1496. }
  1497. using namespace theme::colour;
  1498. g.fillAll (bg1);
  1499. g.setColour (bg3);
  1500. g.fillRect (0, 0, getWidth(), toolbarHeight);
  1501. g.setColour (border);
  1502. g.fillRect (0, toolbarHeight - 1, getWidth(), 1);
  1503. // round 190jo (design190ia FM-18): the grid a step clearer (rows 1.07:1 and beat lines 1.15:1 before; FL's and Live's
  1504. // users ask for a readable grid), derived from the theme's tokens so a theme still applies; the Playlist keeps its own
  1505. const auto lift = [] (juce::Colour c, float amount) { return c.interpolatedWith (textPrimary, amount); };
  1506. const auto prBar = lift (gridBar, 0.06f), prBeat = lift (gridBeat, 0.05f), prStep = lift (gridStep, 0.035f);
  1507. const auto prRowBlack = rowBlack.interpolatedWith (juce::Colours::black, 0.1f);
  1508. // rollup 0.1.31 step 3 (owner: key regions looked much fainter than FL's, pair-01 of round 190nu): a row in the scale
  1509. // (key regions, a chosen scale, Automatic) is the white-key row lifted above the 1 px row line, as FL's in-scale rows
  1510. // are (FL 2026: row 1.18 x its line in luma, out-of-scale rows below the in-scale ones); here 0.07 to textPrimary takes
  1511. // rowWhite from 1.27:1 under the line to 1.18:1 over it, and the out-of-scale rows keep the black-key shade
  1512. const auto prRowIn = rowWhite.interpolatedWith (textPrimary, 0.07f);
  1513. // issue #205 (round 190lw): a selected note's row band (FL 2026 capture: BANDNOTE)
  1514. const auto rowBand = [] (juce::Colour row, bool live) { return row.interpolatedWith (textPrimary, live ? 0.10f : 0.10f); };
  1515. auto drawVerticalGrid = [&] (juce::Rectangle<int> area) {
  1516. // grid lines: bar > beat > snap (unless too dense)
  1517. const auto step = snapGrid * pixelsPerTick >= 6.0 ? snapGrid : (std::int64_t) ppq;
  1518. const auto first = (std::int64_t) std::floor (scrollTicks / (double) step);
  1519. const auto last = (std::int64_t) std::ceil (xToTick (area.getRight()) / (double) step);
  1520. for (auto i = first; i <= last; ++i)
  1521. {
  1522. const auto tick = i * step;
  1523. const auto x = (float) tickToX ((double) tick);
  1524. g.setColour (tick % bar == 0 ? prBar : tick % ppq == 0 ? prBeat : prStep);
  1525. g.drawVerticalLine ((int) x, (float) area.getY(), (float) area.getBottom());
  1526. }
  1527. };
  1528. // round 190ge: what this paint may change. A moving playhead repaints a 14-pixel column many times a second, and
  1529. // every note drawn outside it (a rounded rectangle is a path to build and fill) was work for no pixel: the notes,
  1530. // ghosts and velocity markers whose drawing lies wholly outside are skipped (the pixels stay the same)
  1531. const auto dirtyArea = g.getClipBounds();
  1532. const auto cull = ui::paintSavings(); // (LYNX_PAINT_SAVINGS=0: everything drawn, as before)
  1533. const auto outside = [&dirtyArea, cull] (const juce::Rectangle<float>& r, float margin) {
  1534. return cull && ! r.expanded (margin).getSmallestIntegerContainer().intersects (dirtyArea);
  1535. };
  1536. const auto liveLookNotes = liveNotes(); // (round 190jn: docked in the Clip View's Live look)
  1537. // --- grid ------------------------------------------------------------
  1538. {
  1539. juce::Graphics::ScopedSaveState state (g);
  1540. g.reduceClipRegion (grid);
  1541. const auto autoRows = isAutoScale();
  1542. const auto chosenScale = scaleIndex() > 0; // (round 190kd: read once per paint, not per row)
  1543. // issue #205 (round 190lw): FL's row bands — the rows of the selected notes lit across the whole grid, and while a
  1544. // note is pressed or dragged, the rows of the notes that follow the mouse (the hover band no longer goes away)
  1545. const auto noteDrag = drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft;
  1546. auto bandRows = rowbands::of (pattern.notes, selection);
  1547. if (noteDrag)
  1548. bandRows |= rowbands::of (pattern.notes, dragIndices);
  1549. // round 190nu (core/KeyRegions.h): FL's key markers shade each region's rows for its own key (before the first one,
  1550. // and after a Default one, the editor's own scale as before); only the regions in view, none without key markers
  1551. struct RegionRows
  1552. {
  1553. int x0, x1;
  1554. keyregions::State state;
  1555. keyregions::Degrees degrees;
  1556. };
  1557. std::vector<RegionRows> regionRows;
  1558. // round 190pf (P13): the Chord lane's chord at the song position lights its notes' rows (the scale's shade, the
  1559. // rows out of the chord the black-key shade); it wins over the scale and the key regions while it shows
  1560. const auto chordRows = gridHighlights && ! liveLookNotes && shownChord.root >= 0;
  1561. if (gridHighlights && ! liveLookNotes && ! chordRows && keyregions::hasKeyMarkers (pattern))
  1562. {
  1563. const auto rightTick = (std::int64_t) xToTick (grid.getRight()) + 1;
  1564. for (const auto& span : keyregions::spans (pattern, std::max<std::int64_t> (rightTick, 1)))
  1565. {
  1566. auto x0 = (int) std::floor (tickToX ((double) span.from)), x1 = (int) std::ceil (tickToX ((double) span.to));
  1567. x0 = std::max (x0, grid.getX());
  1568. x1 = std::min (x1, grid.getRight());
  1569. if (x1 > x0)
  1570. regionRows.push_back ({ x0, x1, span.state, span.state.kind == keyregions::State::key ? keyregions::degreesOf (span.state.value) : keyregions::Degrees {} });
  1571. }
  1572. if (! regionRows.empty()) // (the last region goes on past the right edge)
  1573. regionRows.back().x1 = grid.getRight();
  1574. }
  1575. for (int key = 0; key < 128; ++key)
  1576. {
  1577. const auto y = keyToY (key);
  1578. if (! rows.shown (key) || y > grid.getBottom() || y + rowHeight < grid.getY())
  1579. continue;
  1580. // Note grid highlights (Alt+B, round 168g): off, every row looks the same (FL's "BlackKeys" option)
  1581. auto row = gridHighlights && blackKeyRows && isBlackKey (key) ? prRowBlack : rowWhite; // (FL's Default: none, #212)
  1582. if (gridHighlights && autoRows) // FL's Automatic (round 190jv): the rows out of the guessed key dark; no guess, none
  1583. row = autoKey < 0 ? rowWhite : scaledetect::inScale (autoKey, key) ? prRowIn : prRowBlack;
  1584. else if (gridHighlights && chosenScale)
  1585. // a chosen scale as FL shades it (round 190kd, owner's decision; FL 2026 shot: the rows out of the scale
  1586. // take the black-key shade, the rows in it the white-key one, black keys or not; rollup step 6: 190jo's
  1587. // black-key shade `prRowBlack`, as step 5 did for Automatic)
  1588. row = inScale (key) ? prRowIn : prRowBlack;
  1589. if (chordRows)
  1590. row = (shownChord.mask & (1 << (key % 12))) != 0 ? prRowIn : prRowBlack;
  1591. if (liveLookNotes) // (round 190jn: Live's note editor, one grey with a darker line under each row)
  1592. row = juce::Colour (0xff464f53);
  1593. if (bandRows.test ((std::size_t) key))
  1594. row = rowBand (row, liveLookNotes);
  1595. else if (key == hover.key && drag == Drag::none)
  1596. row = row.interpolatedWith (textPrimary, 0.04f); // the row under the mouse
  1597. if (regionRows.empty())
  1598. {
  1599. g.setColour (row);
  1600. g.fillRect (grid.getX(), y, grid.getWidth(), rowHeight);
  1601. }
  1602. else
  1603. for (const auto& r : regionRows)
  1604. {
  1605. auto shade = row; // (the editor's own scale)
  1606. if (r.state.kind != keyregions::State::editor)
  1607. {
  1608. shade = r.state.kind == keyregions::State::key ? (r.degrees.contains (key) ? prRowIn : prRowBlack)
  1609. : (blackKeyRows && isBlackKey (key) ? prRowBlack : rowWhite);
  1610. if (bandRows.test ((std::size_t) key))
  1611. shade = rowBand (shade, false);
  1612. else if (key == hover.key && drag == Drag::none)
  1613. shade = shade.interpolatedWith (textPrimary, 0.04f);
  1614. }
  1615. g.setColour (shade);
  1616. g.fillRect (r.x0, y, r.x1 - r.x0, rowHeight);
  1617. }
  1618. // (round 190jn: Live's darker line under each row; round 190jo FM-15: FL's 1 px line under every row, the note
  1619. // sits above it)
  1620. if (liveLookNotes || rowHeight >= 10)
  1621. {
  1622. g.setColour (liveLookNotes ? juce::Colour (0xff3d4548) : prStep);
  1623. g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
  1624. }
  1625. if (! padRows.empty() || key % 12 == (folded() ? scaleRoot() : 0)) // folded: the octave line under each root (pads: each row)
  1626. {
  1627. g.setColour (prBeat);
  1628. g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
  1629. }
  1630. }
  1631. drawVerticalGrid (grid);
  1632. paintBackgroundWave (g, grid);
  1633. // the time selection (Ctrl+drag on the ruler): Insert / Delete space, Trim
  1634. if (timeFrom >= 0 && timeTo > timeFrom)
  1635. {
  1636. g.setColour (selectionFill.withMultipliedAlpha (0.45f));
  1637. g.fillRect (juce::Rectangle<float> ((float) tickToX ((double) timeFrom), (float) grid.getY(),
  1638. (float) ((double) (timeTo - timeFrom) * pixelsPerTick), (float) grid.getHeight()));
  1639. }
  1640. // outside the pattern is darkened
  1641. const auto endX = (float) tickToX ((double) patternLength);
  1642. g.setColour (bg0.withAlpha (0.55f));
  1643. g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
  1644. // ghost notes (Alt+V). This channel's notes in the other clips that play at the same time in the
  1645. // Playlist: hollow outlines. The other channels of this pattern: solid grey (a bit brighter, with
  1646. // their channel colour on the edge, when Ctrl+Alt+V makes them editable)
  1647. if (showGhosts)
  1648. {
  1649. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, channel))
  1650. {
  1651. if (! rows.shown (n.key))
  1652. continue;
  1653. const auto r = noteRect (n.start, n.length, n.key);
  1654. if (r.getRight() < (float) grid.getX() || r.getX() > (float) grid.getRight() || outside (r, 2.0f))
  1655. continue;
  1656. g.setColour (textPrimary.withAlpha (0.30f));
  1657. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1658. }
  1659. }
  1660. // round 190rc (Discord 11-24, sidthenugget): in Track-only mode and the Simple layout a clip holds one instrument,
  1661. // so the ghosts are the other tracks' notes playing at the same time (drawn as FL's ghosts; not editable)
  1662. if (showGhosts && (trackonly::active() || layoutstyle::current() == layoutstyle::Style::simple))
  1663. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, channel, 2000, true))
  1664. {
  1665. if (! ghostShown (n.channel) || ! rows.shown (n.key))
  1666. continue;
  1667. const auto r = noteRect (n.start, n.length, n.key);
  1668. if (r.getRight() < (float) grid.getX() || r.getX() > (float) grid.getRight() || outside (r, 2.0f))
  1669. continue;
  1670. g.setColour (textPrimary.withAlpha (0.14f));
  1671. g.fillRoundedRectangle (r, 2.0f);
  1672. g.setColour (textPrimary.withAlpha (0.22f));
  1673. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1674. }
  1675. for (const auto& n : pattern.notes)
  1676. {
  1677. if (edits (n) || ! showGhosts || ! ghostShown (n.channel) || ! rows.shown (n.key))
  1678. continue;
  1679. const auto r = noteRect (n.start, n.length, n.key);
  1680. if (outside (r, 2.0f))
  1681. continue;
  1682. const auto hovered = &n - pattern.notes.data() == hover.ghost;
  1683. // (round 190jo FM-20: FL's ghosts are full-row bars, 1.48:1 over the field with a 1 px edge, no label: the
  1684. // light text at 14 % with a 22 % edge reads the same on LYNX's dark rows)
  1685. g.setColour (textPrimary.withAlpha (hovered ? 0.20f : editGhosts ? 0.17f : 0.14f));
  1686. g.fillRoundedRectangle (r, 2.0f);
  1687. g.setColour (textPrimary.withAlpha (hovered ? 0.40f : editGhosts ? 0.30f : 0.22f));
  1688. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1689. if (editGhosts && n.channel >= 0 && n.channel < (int) song.channels.size() && song.channels[(std::size_t) n.channel].colour != 0)
  1690. {
  1691. g.setColour (theme::tame (juce::Colour (song.channels[(std::size_t) n.channel].colour)).withAlpha (0.7f));
  1692. g.fillRect (r.withWidth (2.0f).reduced (0.0f, 1.0f));
  1693. }
  1694. }
  1695. for (int i = 0; i < (int) pattern.notes.size(); ++i)
  1696. {
  1697. const auto& n = pattern.notes[(std::size_t) i];
  1698. if (! edits (n) || ! rows.shown (n.key))
  1699. continue;
  1700. const auto r = noteRect (n.start, n.length, n.key);
  1701. if (outside (r, 2.0f)) // (its outline, grips, marks and label all lie inside r)
  1702. continue;
  1703. const auto selected = isSelected (i);
  1704. const auto hovered = i == hover.note && drag == Drag::none;
  1705. // a selected muted note keeps a muted look (round 167k: Alt+M on a selection showed no change)
  1706. auto fill = selected ? (n.muted ? accentHover.interpolatedWith (noteMuted, 0.6f) : accentHover.brighter (0.15f))
  1707. : n.muted ? noteMuted : theme::noteGroupColour (n.colour, n.velocity);
  1708. if (liveLookNotes && ! selected && ! n.muted) // Live: the clip's colour × 0.86 with a black edge, square
  1709. {
  1710. fill = theme::liveShade (liveNoteColour, 0.86f).withAlpha (1.0f);
  1711. if (hovered)
  1712. fill = fill.brighter (0.18f);
  1713. g.setColour (fill);
  1714. g.fillRect (r);
  1715. g.setColour (juce::Colours::black);
  1716. g.drawRect (r, 1.0f);
  1717. }
  1718. else
  1719. {
  1720. if (hovered)
  1721. fill = fill.brighter (0.18f);
  1722. paintNoteBody (g, r, fill, selected ? textPrimary : hovered ? textPrimary.withAlpha (0.75f) : juce::Colour());
  1723. }
  1724. // "All" channels: whose note it is, by the channel's colour on its left edge (issue #12)
  1725. if (allChannels && n.channel >= 0 && n.channel < (int) song.channels.size() && r.getWidth() > 5.0f)
  1726. {
  1727. const auto c = song.channels[(std::size_t) n.channel].colour;
  1728. g.setColour ((c != 0 ? theme::tame (juce::Colour (c)) : textPrimary.withAlpha (0.5f)).withAlpha (0.9f));
  1729. g.fillRect (r.withWidth (2.5f).reduced (0.0f, 1.5f).translated (1.0f, 0.0f));
  1730. }
  1731. // the edge under the mouse shows its grip
  1732. if (hovered && (hover.zone == gesture::Zone::rightEdge || hover.zone == gesture::Zone::leftEdge))
  1733. {
  1734. const auto gripX = hover.zone == gesture::Zone::rightEdge ? r.getRight() - 3.0f : r.getX() + 1.0f;
  1735. g.setColour (textPrimary);
  1736. g.fillRoundedRectangle (gripX, r.getY() + 2.0f, 2.0f, juce::jmax (2.0f, r.getHeight() - 4.0f), 1.0f);
  1737. }
  1738. if (n.group != 0 && r.getWidth() > 10.0f) // grouped: a small link mark at the top right
  1739. {
  1740. g.setColour (bg0.withAlpha (0.7f));
  1741. g.fillEllipse (r.getRight() - 6.0f, r.getY() + 1.5f, 3.5f, 3.5f);
  1742. }
  1743. // round 190pm (P19): ratchets as thin dividers where each strike starts, a Condition as a small bar along the bottom
  1744. // edge (LYNX's own marks, clear of the label; drawn only on notes that have them)
  1745. if (n.hasRatchets() && n.repeat == 0 && r.getWidth() > 8.0f && r.getHeight() > 4.0f)
  1746. {
  1747. const auto strikes = noterepeat::ratchetCount (n);
  1748. g.setColour (bg0.withAlpha (0.55f));
  1749. for (int k = 1; k < strikes; ++k)
  1750. {
  1751. const auto x = r.getX() + r.getWidth() * (float) k / (float) strikes;
  1752. if (x - r.getX() >= 2.0f)
  1753. g.fillRect (juce::Rectangle<float> (x - 0.5f, r.getY() + 2.0f, 1.0f, r.getHeight() - 4.0f));
  1754. }
  1755. }
  1756. if (n.hasCondition() && r.getWidth() > 12.0f && r.getHeight() > 6.0f)
  1757. {
  1758. g.setColour (bg0.withAlpha (0.7f));
  1759. g.fillRect (juce::Rectangle<float> (r.getX() + 3.0f, r.getBottom() - 3.0f, juce::jmin (8.0f, r.getWidth() - 6.0f), 1.5f));
  1760. }
  1761. // a Chance below 100 % (round 187c): a small triangle in the top-left corner, as Live 12 marks it ("A small
  1762. // triangle is displayed in the upper-left corner of notes with probability values less than 100%")
  1763. if ((n.chance < 1.0f || n.chanceGroup != 0) && r.getWidth() > 6.0f && r.getHeight() > 5.0f)
  1764. {
  1765. juce::Path corner;
  1766. const auto size = juce::jmin (6.0f, r.getHeight() - 2.0f);
  1767. corner.addTriangle (r.getX() + 1.0f, r.getY() + 1.0f, r.getX() + 1.0f + size, r.getY() + 1.0f, r.getX() + 1.0f, r.getY() + 1.0f + size);
  1768. g.setColour (bg0.withAlpha (0.75f));
  1769. g.fillPath (corner);
  1770. }
  1771. if (n.porta) // porta (round 190oa, DE-81, capture 190oa fl-pr-porta-mark: FL's "/" ~10 × 7 px near the note's right
  1772. { // end, 3 px in, centred, in the note's label colour)
  1773. const auto w = juce::jmin (10.0f, juce::jmax (3.0f, r.getWidth() - 6.0f)), h = juce::jmin (7.0f, r.getHeight() - 4.0f);
  1774. const auto x1 = r.getRight() - 3.0f, cy = r.getCentreY();
  1775. g.setColour (bg0.withAlpha (0.65f));
  1776. g.drawLine (x1 - w, cy + h * 0.5f, x1, cy - h * 0.5f, 2.0f);
  1777. }
  1778. if (n.slide) // slide mark: FL's manual (Piano roll): "slide notes have a small triangle on the right" (round 190kn, DE-80)
  1779. {
  1780. // issue #272 (round 190qo, FL 2026 capture shots/fl/272-fl-slide-mark-x8.png): FL's mark is a small right
  1781. // triangle, its right angle at the bottom right (◢), 7 x 7 px on a 15 px note, centred in the note's
  1782. // height, its right side 2 px in from the note's right edge. LYNX drew a ▶ wedge over the note's whole
  1783. // height, which looked like a differently shaped note.
  1784. const auto size = juce::jmin (7.0f, r.getHeight() - 4.0f, juce::jmax (3.0f, r.getWidth() - 4.0f));
  1785. if (size >= 2.0f)
  1786. {
  1787. const auto right = r.getRight() - 2.0f, bottom = r.getCentreY() + size * 0.5f;
  1788. juce::Path mark;
  1789. mark.addTriangle (right - size, bottom, right, bottom, right, bottom - size);
  1790. g.setColour (bg0.withAlpha (0.65f));
  1791. g.fillPath (mark);
  1792. }
  1793. }
  1794. if (gesture::noteLabelFits (r.getWidth(), rowHeight)) // the note's name, readable on its colour
  1795. {
  1796. // (round 190jo FM-16: a dark label on a light note, as FL's: bg0 on LYNX red is 5.3:1, the light label was
  1797. // 2.3:1; bold, 3 px in from the left as FL's)
  1798. g.setColour (noteLabelColour (fill));
  1799. g.setFont (noteLabelFont (rowHeight));
  1800. textcache::drawText (g, keyName (n.key), r.withTrimmedLeft (n.porta ? 11.0f : 3.0f).withTrimmedRight (n.slide ? 11.0f : 3.0f), juce::Justification::centredLeft, true);
  1801. }
  1802. }
  1803. // round 177d: the notes being played into a take grow with the playhead until they are released (then the
  1804. // recorded note takes their place); FL 2026 draws them so, as ordinary notes (REA_rodada177d §1.3, g03)
  1805. if (engine.isLiveRecording())
  1806. for (const auto& n : engine.liveRecording().held)
  1807. {
  1808. if (! edits (n) || ! rows.shown (n.key))
  1809. continue;
  1810. const auto r = noteRect (n.start, n.length, n.key);
  1811. const auto fill = theme::noteGroupColour (n.colour, n.velocity);
  1812. paintNoteBody (g, r, fill, {});
  1813. if (gesture::noteLabelFits (r.getWidth(), rowHeight))
  1814. {
  1815. g.setColour (noteLabelColour (fill));
  1816. g.setFont (noteLabelFont (rowHeight));
  1817. textcache::drawText (g, keyName (n.key), r.reduced (3.0f, 0.0f), juce::Justification::centredLeft, true);
  1818. }
  1819. }
  1820. // the selection's stretch handle: a tab at its right end with two grips
  1821. if (const auto handle = stretchHandle(); ! handle.isEmpty() && (drag == Drag::none || drag == Drag::stretch))
  1822. {
  1823. const auto lit = hover.stretch || drag == Drag::stretch;
  1824. g.setColour (lit ? accentHover : accent.withAlpha (0.85f));
  1825. g.fillRoundedRectangle (handle, 3.0f);
  1826. g.setColour (onAccent.withAlpha (0.9f));
  1827. g.fillRect (handle.getCentreX() - 2.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  1828. g.fillRect (handle.getCentreX() + 1.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  1829. if (lit) // the stretched span, from the anchor to the handle
  1830. {
  1831. g.setColour (accent.withAlpha (0.5f));
  1832. const auto x0 = (float) tickToX ((double) (drag == Drag::stretch ? stretchAnchor : 0));
  1833. if (drag == Drag::stretch)
  1834. g.drawVerticalLine ((int) x0, (float) grid.getY(), (float) grid.getBottom());
  1835. g.drawVerticalLine ((int) handle.getX() - 2, (float) grid.getY(), (float) grid.getBottom());
  1836. }
  1837. }
  1838. if (! mpeLaneAreas().empty()) // (round 190hy: as Live's MPE view, each note's pitch curve over it)
  1839. paintMpePitchOnNotes (g, grid);
  1840. // round 190nu: the Scale degree chord a click would write, as outlines with its numeral and name (LYNX's look: the
  1841. // accent outline, a faint fill; only while the degree stamp is chosen and the mouse rests on the empty grid)
  1842. if (degreeGhost.tick >= 0 && ! degreeGhost.keys.empty())
  1843. {
  1844. const auto x = (float) tickToX ((double) degreeGhost.tick);
  1845. const auto w = juce::jmax (6.0f, (float) ((double) degreeGhost.length * pixelsPerTick) - 1.0f);
  1846. float top = (float) grid.getBottom(), bottom = (float) grid.getY();
  1847. for (const auto k : degreeGhost.keys)
  1848. if (rows.shown (k))
  1849. {
  1850. const auto r = juce::Rectangle<float> (x, (float) keyToY (k) + 1.0f, w, (float) rowHeight - 2.0f);
  1851. g.setColour (accent.withAlpha (0.16f));
  1852. g.fillRoundedRectangle (r, 2.0f);
  1853. g.setColour (accent.withAlpha (0.85f));
  1854. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1855. top = juce::jmin (top, r.getY());
  1856. bottom = juce::jmax (bottom, r.getBottom());
  1857. }
  1858. if (top - 20.0f < (float) grid.getY()) // (no room above the chord: the label goes under it)
  1859. top = bottom + 20.0f;
  1860. if (degreeGhost.label.isNotEmpty())
  1861. {
  1862. g.setFont (theme::font (theme::type::caption, true));
  1863. const auto tw = juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), degreeGhost.label) + 10;
  1864. const auto tag = juce::Rectangle<float> (x, top - 18.0f, (float) tw, 16.0f);
  1865. g.setColour (bg4.withAlpha (0.94f));
  1866. g.fillRoundedRectangle (tag, 3.0f);
  1867. g.setColour (accent.withAlpha (0.8f));
  1868. g.drawRoundedRectangle (tag.reduced (0.5f), 3.0f, 1.0f);
  1869. g.setColour (textPrimary);
  1870. g.drawText (degreeGhost.label, tag.toNearestInt(), juce::Justification::centred, false);
  1871. }
  1872. }
  1873. if (! rubberBand.isEmpty())
  1874. {
  1875. g.setColour (selectionFill);
  1876. g.fillRect (rubberBand);
  1877. g.setColour (theme::colour::selection);
  1878. g.drawRect (rubberBand);
  1879. }
  1880. if (drag == Drag::knife)
  1881. {
  1882. juce::Path cut;
  1883. cut.startNewSubPath (knifeFrom.toFloat());
  1884. cut.lineTo (knifeTo.toFloat());
  1885. juce::Path dashed;
  1886. const float dash[] = { 5.0f, 3.0f };
  1887. juce::PathStrokeType (1.5f).createDashedStroke (dashed, cut, dash, 2);
  1888. g.setColour (textPrimary);
  1889. g.fillPath (dashed);
  1890. }
  1891. if (playheadTick >= 0.0 && ! gpuPlayhead.isShowing()) // (round 190ip: the GPU moves it while playing)
  1892. {
  1893. g.setColour (playhead);
  1894. g.drawVerticalLine ((int) tickToX (playheadTick), (float) grid.getY(), (float) grid.getBottom());
  1895. }
  1896. }
  1897. // --- velocity lane -----------------------------------------------------
  1898. // (round 190on, P10: once for each stacked lane, top to bottom, then the bottom lane; with none, once as before)
  1899. for (int laneIndex = 0; laneIndex <= (int) stacked.size(); ++laneIndex)
  1900. {
  1901. const LaneScope laneScope (*this, laneIndex < (int) stacked.size() ? laneIndex : -1);
  1902. {
  1903. const auto lane = velocityArea();
  1904. g.setColour (rowWhite); // (round 190jo FM-19: FL's lane is the roll's field with its beat lines, not a darker well)
  1905. g.fillRect (lane);
  1906. juce::Graphics::ScopedSaveState state (g);
  1907. g.reduceClipRegion (lane);
  1908. drawVerticalGrid (lane);
  1909. g.setColour (border);
  1910. g.drawHorizontalLine (lane.getY(), (float) lane.getX(), (float) lane.getRight());
  1911. const auto usable = (float) lane.getHeight() - 8.0f;
  1912. const auto bipolar = laneIsBipolar();
  1913. const auto base = bipolar ? (float) lane.getBottom() - 2.0f - usable * 0.5f : (float) lane.getBottom();
  1914. if (bipolar)
  1915. {
  1916. g.setColour (textPrimary.withAlpha (0.15f));
  1917. g.drawHorizontalLine ((int) base, (float) lane.getX(), (float) lane.getRight());
  1918. }
  1919. if (const auto target = eventLaneTarget()) // pattern events: held values, a dot on each event
  1920. {
  1921. const auto* events = eventedit::findLane (pattern, *target);
  1922. if (events != nullptr && ! events->events.empty())
  1923. {
  1924. juce::Path held;
  1925. const auto yOf = [&] (float v) { return (float) lane.getBottom() - 2.0f - usable * v; };
  1926. auto x = (float) tickToX (0.0);
  1927. auto y = yOf (events->events.front().value);
  1928. held.startNewSubPath (x, y);
  1929. for (const auto& ev : events->events)
  1930. {
  1931. const auto ex = (float) tickToX ((double) ev.tick);
  1932. held.lineTo (ex, y);
  1933. y = yOf (ev.value);
  1934. held.lineTo (ex, y);
  1935. }
  1936. held.lineTo ((float) lane.getRight(), y);
  1937. g.setColour (accent.withAlpha (0.85f));
  1938. g.strokePath (held, juce::PathStrokeType (1.5f));
  1939. for (const auto& ev : events->events)
  1940. g.fillEllipse ((float) tickToX ((double) ev.tick) - 2.5f, yOf (ev.value) - 2.5f, 5.0f, 5.0f);
  1941. }
  1942. else
  1943. {
  1944. g.setColour (textDisabled);
  1945. g.setFont (theme::font (theme::type::small));
  1946. textcache::drawText (g, tr ("No events yet: draw them here"), lane.reduced (8, 4), juce::Justification::centredLeft, true);
  1947. }
  1948. }
  1949. const auto mpeLanes = mpeLaneAreas(); // (round 190hy: the notes' MPE curves instead of their stems)
  1950. if (! mpeLanes.empty())
  1951. {
  1952. const auto range = drag == Drag::mpePoint || drag == Drag::mpeDraw ? mpeDragRange : mpePitchRange();
  1953. for (const auto& [area, id] : mpeLanes)
  1954. if (isMpeLane (id))
  1955. paintMpeLane (g, area, id, range);
  1956. else
  1957. paintMpeValueLane (g, area, id); // (round 190jd: the MPE tab's Velocity / Release Velocity lanes)
  1958. }
  1959. else
  1960. {
  1961. // the lane's name in it, as FL writes it next to "Control" (round 149: the box on the left is narrow)
  1962. g.setColour (theme::colour::textSecondary.withAlpha (0.8f));
  1963. g.setFont (theme::font (theme::type::caption, true));
  1964. textcache::drawText (g, laneName(), lane.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  1965. }
  1966. // round 190mf (DL-80, capture 190mf B2): in the Clip View's Live look the hovered note's velocity marker and its
  1967. // stem turn Live's blue (91,140,255); while a velocity is dragged the selected markers are Live's light cyan
  1968. // (176,221,235), and the lane header shows the value at the marker's height (paint's lane label below)
  1969. const auto liveVelocity = liveNotes() && laneId() == laneVelocity;
  1970. liveVelocityReadout = {};
  1971. for (int i = 0; i < (int) pattern.notes.size() && ! eventLaneTarget() && mpeLanes.empty(); ++i)
  1972. {
  1973. const auto& n = pattern.notes[(std::size_t) i];
  1974. if (! edits (n) || ! rows.shown (n.key))
  1975. continue;
  1976. const auto x = (float) tickToX ((double) n.start);
  1977. // (round 190ge: outside the repainted area — the marker's ±6 pixels, the Velocity Range box over the note's
  1978. // length — nothing to draw; a probability group's line reaches another note, so those are always drawn)
  1979. if (! (laneIsChance() && n.chanceGroup != 0)
  1980. && outside (juce::Rectangle<float> (x - 6.0f, (float) lane.getY(), 12.0f + juce::jmax (3.0f, (float) (n.length * pixelsPerTick)), (float) lane.getHeight()), 1.0f))
  1981. continue;
  1982. const auto top = (float) lane.getBottom() - 2.0f - usable * laneValue (n);
  1983. auto colour = isSelected (i) ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  1984. if (n.muted)
  1985. colour = noteMuted;
  1986. const auto hovered = i == hover.note && drag == Drag::none;
  1987. if (liveVelocity && hovered)
  1988. colour = juce::Colour (91, 140, 255);
  1989. else if (liveVelocity && drag == Drag::velocity && isSelected (i))
  1990. colour = juce::Colour (176, 221, 235);
  1991. if (liveVelocity && ((hovered && lane.contains (lastMouse)) || (drag == Drag::velocity && isSelected (i) && liveVelocityReadout.note < 0)))
  1992. liveVelocityReadout = { i, top, juce::roundToInt (n.velocity * 127.0f) };
  1993. // the velocity lane shows a note's Velocity Range (round 187c) as a shaded box over the note's length, from
  1994. // its velocity to where the range reaches, as Live 12 draws it [LIVE 12.4 shot, live-02]
  1995. if (laneId() == laneVelocity && n.velocityRange != 0.0f)
  1996. {
  1997. const auto reach = juce::jlimit (1.0f / 127.0f, 1.0f, n.velocity + n.velocityRange);
  1998. const auto y2 = (float) lane.getBottom() - 2.0f - usable * reach;
  1999. const auto w = juce::jmax (3.0f, (float) (n.length * pixelsPerTick) - 1.0f);
  2000. g.setColour (colour.withAlpha (0.22f));
  2001. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, y2), w, std::abs (y2 - top)));
  2002. g.setColour (colour.withAlpha (0.5f));
  2003. g.drawHorizontalLine ((int) y2, x, x + w);
  2004. }
  2005. // a probability group (round 187c): its members' Chance markers joined by a line (the group has one Chance)
  2006. if (laneIsChance() && n.chanceGroup != 0)
  2007. for (int j = i + 1; j < (int) pattern.notes.size(); ++j)
  2008. if (const auto& m = pattern.notes[(std::size_t) j]; m.chanceGroup == n.chanceGroup && edits (m) && rows.shown (m.key))
  2009. {
  2010. g.setColour (colour.withAlpha (0.5f));
  2011. const auto dash = std::array<float, 2> { 3.0f, 3.0f };
  2012. g.drawDashedLine (juce::Line<float> (x, top, (float) tickToX ((double) m.start), top), dash.data(), 2, n.chanceOne ? 1.0f : 2.0f);
  2013. break;
  2014. }
  2015. g.setColour (hovered ? colour.brighter (0.3f) : colour.withAlpha (0.8f));
  2016. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, base), hovered ? 3.0f : 2.0f, std::abs (base - top)));
  2017. // round 190oj: FL's event mark in the Pattern layout — a line along the note's length at its value and a ring
  2018. // head (two fills: cheaper than a stroked ellipse); Live's look keeps its filled dot
  2019. if (! liveVelocity)
  2020. g.fillRect (juce::Rectangle<float> (x, std::round (top), juce::jmax (0.0f, (float) (n.length * pixelsPerTick) - 1.0f), 1.0f));
  2021. g.fillEllipse (x - 3.0f, top - 3.0f, 7.0f, 7.0f);
  2022. if (! liveVelocity)
  2023. {
  2024. g.setColour (colour.withMultipliedBrightness (0.45f));
  2025. g.fillEllipse (x - 1.5f, top - 1.5f, 4.0f, 4.0f);
  2026. g.setColour (colour.brighter (0.3f)); // (the hover ring below)
  2027. }
  2028. if (hovered)
  2029. g.drawEllipse (x - 5.0f, top - 5.0f, 11.0f, 11.0f, 1.0f);
  2030. // round 190pm: the Ratchets and Condition lanes name a note's value beside its mark ("4x", "2+4:4"), only on
  2031. // the notes that have one
  2032. if ((laneId() == laneRatchets && n.hasRatchets()) || (laneId() == laneCondition && n.hasCondition()))
  2033. {
  2034. const auto label = laneId() == laneRatchets ? juce::String (noterepeat::ratchetCount (n)) + "x" : conditionText (n);
  2035. g.setColour (textPrimary.withAlpha (0.85f));
  2036. g.setFont (theme::font (theme::type::caption));
  2037. const auto ty = juce::jlimit ((float) lane.getY() + 14.0f, (float) lane.getBottom() - 14.0f, top - 15.0f);
  2038. textcache::drawText (g, label, juce::Rectangle<float> (x + 5.0f, ty, 90.0f, 13.0f).toNearestInt(), juce::Justification::centredLeft, false);
  2039. }
  2040. }
  2041. if (drag == Drag::velocityLine && paintingLane == heldLane) // the line being drawn (in the lane it is drawn in)
  2042. {
  2043. g.setColour (textPrimary.withAlpha (0.8f));
  2044. g.drawLine (juce::Line<int> (knifeFrom, knifeTo).toFloat(), 1.5f);
  2045. }
  2046. }
  2047. }
  2048. // --- time ruler --------------------------------------------------------
  2049. {
  2050. const auto ruler = juce::Rectangle<int> (keyboardWidth, rulerTop, grid.getWidth(), timelineHeight);
  2051. g.setColour (bg2);
  2052. g.fillRect (ruler);
  2053. g.setColour (border);
  2054. g.fillRect (ruler.withTop (ruler.getBottom() - 1));
  2055. juce::Graphics::ScopedSaveState state (g);
  2056. g.reduceClipRegion (ruler);
  2057. g.setFont (theme::font (theme::type::caption));
  2058. const auto firstBar = (std::int64_t) std::floor (scrollTicks / (double) bar);
  2059. const auto lastBar = (std::int64_t) std::ceil (xToTick (grid.getRight()) / (double) bar);
  2060. if (timeFrom >= 0 && timeTo > timeFrom) // the time selection on the ruler
  2061. {
  2062. const auto x0 = (float) tickToX ((double) timeFrom), x1 = (float) tickToX ((double) timeTo);
  2063. g.setColour (accent.withAlpha (0.35f));
  2064. g.fillRect (juce::Rectangle<float> (x0, (float) rulerTop, x1 - x0, (float) timelineHeight - 1.0f));
  2065. g.setColour (accent);
  2066. g.fillRect (juce::Rectangle<float> (x0, (float) rulerTop, x1 - x0, 2.0f));
  2067. }
  2068. // View › "Ruler: song bars" (round 177d, LYNX's own; off = FL's pattern bars): the bar numbers the Playlist shows
  2069. // where the pattern's first clip plays
  2070. const auto songOrigin = songBarsRuler ? polish::patternSongOrigin (song, song.currentPattern) : std::nullopt;
  2071. for (auto b = firstBar; b <= lastBar; ++b)
  2072. {
  2073. const auto x = (int) tickToX ((double) (b * bar));
  2074. g.setColour (textSecondary);
  2075. g.drawVerticalLine (x, (float) rulerTop + 10.0f, (float) headerHeight);
  2076. const std::int64_t number = songOrigin.has_value() ? polish::songBarNumber (*songOrigin, b, bar) : (std::int64_t) b + 1;
  2077. if (number > 0) // (round 190oj: in the ruler's top row, as FL draws them: centred in the whole ruler, "1" sat under the 4/4 flag)
  2078. textcache::drawText (g, juce::String (number), x + 3, rulerTop, 40, 11, juce::Justification::centredLeft);
  2079. }
  2080. // the pattern's time markers (round 168g): a flag and the name in the ruler's lower half, like the Playlist's
  2081. for (const auto& m : currentPattern (song).markers)
  2082. {
  2083. const auto x = (float) tickToX ((double) m.tick);
  2084. if (x < (float) keyboardWidth - 120.0f || x > (float) ruler.getRight())
  2085. continue;
  2086. const auto colour = m.isSignature() ? textPrimary : accent;
  2087. g.setColour (colour);
  2088. g.fillRect (juce::Rectangle<float> (x, (float) rulerTop + 11.0f, 1.5f, (float) timelineHeight - 11.0f));
  2089. juce::Path flag;
  2090. flag.addTriangle (x, (float) rulerTop + 11.0f, x + 6.0f, (float) rulerTop + 14.0f, x, (float) rulerTop + 17.0f);
  2091. g.fillPath (flag);
  2092. auto label = juce::String::fromUTF8 (m.name.c_str());
  2093. if (label.isEmpty() && m.action != 0)
  2094. label = tr (markers::actionName (m.action));
  2095. auto textX = (int) x + 8;
  2096. if (keyregions::isKeyMarker (m)) // round 190nu: FL's key marker shows a note before its key ("♪ C Major (Ionian)")
  2097. {
  2098. const auto cy = (float) rulerTop + 10.0f + (float) (timelineHeight - 11) * 0.5f;
  2099. g.fillEllipse ((float) textX, cy + 1.0f, 4.5f, 3.5f);
  2100. g.fillRect ((float) textX + 3.5f, cy - 6.0f, 1.0f, 8.0f);
  2101. g.fillRect ((float) textX + 3.5f, cy - 6.0f, 3.0f, 1.0f);
  2102. textX += 9;
  2103. }
  2104. textcache::drawText (g, label, textX, rulerTop + 10, keyregions::isKeyMarker (m) ? 160 : 110, timelineHeight - 11, juce::Justification::centredLeft);
  2105. }
  2106. if (playheadTick >= 0.0 && ! gpuPlayhead.isShowing())
  2107. {
  2108. const auto x = (float) tickToX (playheadTick);
  2109. juce::Path tri;
  2110. tri.addTriangle (x - 5, (float) rulerTop, x + 5, (float) rulerTop, x, (float) rulerTop + 8);
  2111. g.setColour (playhead);
  2112. g.fillPath (tri);
  2113. }
  2114. }
  2115. // --- keyboard ------------------------------------------------------------
  2116. // flat keys; every C is labelled with its octave, the other white keys too when the rows are tall
  2117. // enough; the key under the mouse (and the one sounding) are lit
  2118. // (round 190ki, perf: all of it lies within `keys`; a playhead column elsewhere skips the 128 keys, their labels and
  2119. // the gradient)
  2120. if (const auto keys = juce::Rectangle<int> (0, headerHeight, keyboardWidth, grid.getHeight()); g.clipRegionIntersects (keys))
  2121. {
  2122. juce::Graphics::ScopedSaveState state (g);
  2123. g.reduceClipRegion (keys);
  2124. g.setColour (bg0);
  2125. g.fillRect (keys);
  2126. const auto fontHeight = gesture::labelHeight (rowHeight);
  2127. const auto blackWidth = blackKeyWidth;
  2128. // (round 190jo, perf: FL's white-key gradient is filled once over the column; the keys at rest draw nothing more)
  2129. if (! folded())
  2130. {
  2131. g.setGradientFill (juce::ColourGradient (keyWhite.withMultipliedBrightness (0.93f), 0.0f, 0.0f,
  2132. keyWhite.interpolatedWith (juce::Colours::white, 0.33f), (float) keyboardWidth, 0.0f, false));
  2133. g.fillRect (keys.withWidth (keyboardWidth - 1));
  2134. }
  2135. static const std::map<int, std::string> noLabels;
  2136. const auto selectedChannel = engine.getSelectedChannel();
  2137. const auto& ownLabels = selectedChannel >= 0 && selectedChannel < (int) song.channels.size()
  2138. ? song.channels[(std::size_t) selectedChannel].keyLabels : noLabels;
  2139. // a Drum Rack's pad names on its keys (round 190ec, Live's note editor); a key label of the user's wins
  2140. std::map<int, std::string> padLabels;
  2141. if (selectedChannel >= 0 && selectedChannel < (int) song.channels.size() && rack::isDrumRack (song.channels[(std::size_t) selectedChannel]))
  2142. {
  2143. padLabels = rack::padNames (*rack::rackOf (song.channels[(std::size_t) selectedChannel].patcher));
  2144. for (const auto& [key, label] : ownLabels)
  2145. padLabels[key] = label;
  2146. }
  2147. const auto& labels = padLabels.empty() ? ownLabels : padLabels;
  2148. // folded to the scale (round 166d) the keys no longer alternate like a piano: one full-width named row each
  2149. const auto list = folded();
  2150. const auto piano = pianokeys::whiteKeysMeet (keyStyle) && ! list;
  2151. const auto flKeys = keyStyle == pianokeys::Style::fl && ! list; // (round 190oo O-2: FL 2026's keyboard, the default)
  2152. // round 190jo (design190ia FM-17): FL's white keys shade from a light grey at the left to near-white at the right
  2153. // (the column's gradient above); its C keys are a step darker (FL: #B0B4BB against #D0D4DB-#E9EDF4)
  2154. const auto fillKey = [&] (int key, juce::Colour colour, juce::Rectangle<int> r) {
  2155. const auto isC = key % 12 == 0 && ! (isBlackKey (key) && ! list);
  2156. if (colour == keyWhite && ! list)
  2157. {
  2158. if (! isC)
  2159. return; // (the gradient is there)
  2160. g.setColour (juce::Colours::black.withAlpha (0.10f));
  2161. }
  2162. else
  2163. g.setColour (isC && colour != accent ? colour.withMultipliedBrightness (0.9f) : colour);
  2164. g.fillRect (r);
  2165. };
  2166. const auto fillBlack = [&] (juce::Colour colour, juce::Rectangle<int> r) {
  2167. g.setColour (colour);
  2168. g.fillRect (r);
  2169. };
  2170. const auto keyColour = [&] (int key) {
  2171. const auto black = isBlackKey (key) && ! list;
  2172. const auto pressed = key == previewKey || isLit (key);
  2173. auto colour = black ? keyBlack : keyWhite; // (no scale tint on the keys: FL draws the piano as it is, round 190kd)
  2174. if (key == hover.key && ! pressed)
  2175. colour = colour.interpolatedWith (accent, black ? 0.35f : 0.22f);
  2176. return pressed ? accent : colour;
  2177. };
  2178. const auto labelClass = scaleIndex() > 0 ? scaleRoot() : 0; // (once per paint)
  2179. // FL's black keys at rest (round 190oo O-2): dark at the left to lighter at the tip (FL 2026: #2a2b2d -> #4e4f51),
  2180. // six solid steps of the shade per key (a gradient fill, or one rectangle list per step, cost +1.7 % of the
  2181. // Piano roll's frame, --paintbench); a lit (hovered, pressed) black key is filled in its own colour
  2182. constexpr int shadeSteps = 6;
  2183. juce::Colour shade[shadeSteps];
  2184. for (int k = 0; k < shadeSteps; ++k)
  2185. shade[k] = keyBlack.interpolatedWith (keyWhite, 0.18f * ((float) k + 0.5f) / (float) shadeSteps);
  2186. for (int key = 0; key < 128; ++key)
  2187. {
  2188. const auto y = keyToY (key);
  2189. if (! rows.shown (key) || y > keys.getBottom() || y + rowHeight < keys.getY())
  2190. continue;
  2191. const auto black = isBlackKey (key) && ! list;
  2192. const auto pressed = key == previewKey || isLit (key);
  2193. const auto hovered = key == hover.key && ! pressed;
  2194. const auto colour = keyColour (key);
  2195. const auto width = black ? blackWidth : keyboardWidth - 1;
  2196. if (piano)
  2197. {
  2198. // "Piano keys" (round 190j, discussion #136): the white keys meet behind the black key, each in its own
  2199. // colour (hover, pressed, scale), with a dark line between every two white keys
  2200. // (FL's keys, round 190oo O-2: no line through the black keys' rows, and a faint one, FL's #c6cad0 on
  2201. // #e3e7ee, between B / C and E / F)
  2202. const auto line = flKeys ? juce::Colours::black.withAlpha (0.13f) : bg0.withAlpha (0.85f);
  2203. if (black)
  2204. {
  2205. const auto upper = pianokeys::upperPart (rowHeight);
  2206. // (FL's keys: the white keys only right of the black key, which the gradient above already filled)
  2207. const auto whiteX = flKeys ? blackWidth : 0;
  2208. fillKey (juce::jmin (127, key + 1), keyColour (juce::jmin (127, key + 1)), { whiteX, y, keyboardWidth - 1 - whiteX, upper });
  2209. fillKey (juce::jmax (0, key - 1), keyColour (juce::jmax (0, key - 1)), { whiteX, y + upper, keyboardWidth - 1 - whiteX, rowHeight - upper });
  2210. // the black key: a little shorter than its row when there is room, so the white shows around it
  2211. const auto inset = rowHeight >= 12 ? 1 : 0;
  2212. if (flKeys)
  2213. {
  2214. if (colour != keyBlack)
  2215. fillBlack (colour, { 0, y + inset, blackWidth, rowHeight - 2 * inset });
  2216. else
  2217. // round 190qu (Discord 11-24, sidthenugget): each step runs to the key's tip, over the one
  2218. // before it. Side by side, at a desktop scale of 125 % / 150 % a step's edge falls inside a
  2219. // pixel that both rectangles only partly covered: the white key showed through as a light
  2220. // line down every black key ("the black keys look broken")
  2221. for (int k = 0; k < shadeSteps; ++k)
  2222. {
  2223. const auto x0 = blackWidth * k / shadeSteps;
  2224. g.setColour (shade[k]);
  2225. g.fillRect (x0, y + inset, blackWidth - x0, rowHeight - 2 * inset);
  2226. }
  2227. }
  2228. else
  2229. {
  2230. g.setColour (line);
  2231. g.drawHorizontalLine (y + upper, (float) blackWidth, (float) (keyboardWidth - 1));
  2232. g.setColour (bg0);
  2233. g.fillRect (0, y + inset, blackWidth + 1, rowHeight - 2 * inset);
  2234. fillBlack (colour, { 0, y + inset, blackWidth, rowHeight - 2 * inset });
  2235. if (! pressed && rowHeight >= 12) // a light edge along the top, as on a real black key
  2236. {
  2237. g.setColour (keyWhite.withAlpha (0.14f));
  2238. g.drawHorizontalLine (y + inset, 0.0f, (float) blackWidth);
  2239. }
  2240. }
  2241. }
  2242. else
  2243. {
  2244. fillKey (key, colour, { 0, y, width, rowHeight });
  2245. if (pianokeys::lineBelow (key))
  2246. {
  2247. g.setColour (line);
  2248. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  2249. }
  2250. }
  2251. }
  2252. else
  2253. {
  2254. if (black)
  2255. {
  2256. g.setColour (bg0); // (the row right of the black key stays dark, over the column's white gradient)
  2257. g.fillRect (width, y, keyboardWidth - 1 - width, rowHeight);
  2258. fillBlack (colour, { 0, y, width, rowHeight });
  2259. }
  2260. else
  2261. fillKey (key, colour, { 0, y, width, rowHeight });
  2262. g.setColour (black ? bg0 : keyWhite.darker (0.3f));
  2263. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  2264. }
  2265. // the octave name on each C; with a chosen scale on each root, as FL labels it (round 190kd: "A3", "A4" in A minor)
  2266. const auto isC = key % 12 == labelClass;
  2267. // every key named (LYNX, on by default: notenames::everyKey) once the rows are tall enough to read
  2268. const auto everyKey = notenames::everyKey.load (std::memory_order_relaxed) && rowHeight >= 8;
  2269. // (round 190jo FM-17: as FL, only the Cs are named on the piano by default, larger and bold; "Note names on
  2270. // every key" names the others; a folded list names each row)
  2271. if (isC || hovered || pressed || everyKey || (list && rowHeight >= 8))
  2272. {
  2273. g.setFont (isC && ! list ? theme::font (juce::jmin (theme::type::body, fontHeight + 1.0f), true) : theme::font (fontHeight, isC));
  2274. // (round 190oo PAT-15: the hovered white key's name in the C keys' full ink, 11.9:1; it was at 55 %)
  2275. g.setColour (pressed ? onAccent : black ? textPrimary.withAlpha (hovered ? 1.0f : 0.85f) : isC || hovered ? bg0 : bg0.withAlpha (everyKey ? 0.72f : 0.55f));
  2276. const auto area = black ? juce::Rectangle<int> (2, y, blackWidth - 4, rowHeight)
  2277. : isC ? juce::Rectangle<int> (8, y, keyboardWidth - 13, rowHeight)
  2278. : juce::Rectangle<int> (blackWidth, y, keyboardWidth - blackWidth - 5, rowHeight);
  2279. textcache::drawText (g, keyName (key), area, black ? juce::Justification::centredLeft : juce::Justification::centredRight, false);
  2280. }
  2281. // a key label (FL 2026's custom key labels) replaces the name on the white part of the key
  2282. if (const auto label = labels.find (key); label != labels.end() && rowHeight >= 8)
  2283. {
  2284. const auto area = juce::Rectangle<int> (black ? blackWidth + 2 : 3, y, keyboardWidth - (black ? blackWidth + 2 : 3) - 4, rowHeight);
  2285. g.setColour (black ? keyWhite : colour);
  2286. g.fillRect (area);
  2287. g.setFont (theme::font (fontHeight, false));
  2288. g.setColour (pressed ? onAccent : bg0);
  2289. g.drawFittedText (juce::String::fromUTF8 (label->second.c_str()), area.reduced (1, 0), juce::Justification::centredLeft, 1, 0.8f);
  2290. }
  2291. if (! padRows.empty()) // (a Drum Rack's pad rows: a strip at the right in the key's piano colour, as Live's list)
  2292. {
  2293. g.setColour (isBlackKey (key) ? keyBlack : keyWhite.darker (0.25f));
  2294. g.fillRect (keyboardWidth - 12, y, 11, rowHeight - 1);
  2295. }
  2296. }
  2297. g.setColour (border);
  2298. g.fillRect (keyboardWidth - 1, keys.getY(), 1, keys.getHeight());
  2299. }
  2300. // velocity lane label
  2301. for (int laneIndex = 0; laneIndex <= (int) stacked.size(); ++laneIndex) // (round 190on: each stacked lane too)
  2302. {
  2303. const LaneScope laneScope (*this, laneIndex < (int) stacked.size() ? laneIndex : -1);
  2304. {
  2305. const auto lane = velocityArea();
  2306. g.setColour (bg2);
  2307. g.fillRect (0, lane.getY(), keyboardWidth, lane.getHeight());
  2308. // the property combo sits here; round 190mf (DL-80): Live's value at the hovered / dragged marker's height
  2309. if (liveVelocityReadout.note >= 0)
  2310. {
  2311. g.setColour (juce::Colour (181, 181, 181));
  2312. g.setFont (theme::font (theme::type::caption, true));
  2313. const auto low = (float) lane.getBottom() - 12.0f, high = juce::jmin (low, (float) lane.getY() + 24.0f); // (under the lane's combo)
  2314. const auto y = juce::jlimit (high, low, liveVelocityReadout.y - 6.0f);
  2315. textcache::drawText (g, juce::String (liveVelocityReadout.value), juce::Rectangle<float> (4.0f, y, (float) keyboardWidth - 10.0f, 12.0f),
  2316. juce::Justification::centredRight, false);
  2317. }
  2318. }
  2319. }
  2320. if (mpeStacked) // round 190jd: the MPE tab's left column (icons, scales), its footer and the hovered value
  2321. paintMpeTabFrame (g);
  2322. // the event editor's divider (round 190fz): FL's 10 px bar, a dark line at its top and bottom, lighter than the
  2323. // grid, with a grip of five 2 px dots 4 px apart in its middle (FL's SplitterPaint: darker than the bar at rest,
  2324. // lighter when a pane is folded away, the highlight colour while it is dragged; FL shot: triage190j/FL-pianoroll.png)
  2325. if (const auto divider = eventPaneBarArea(); ! divider.isEmpty() && g.clipRegionIntersects (divider))
  2326. {
  2327. g.setColour (bg3);
  2328. g.fillRect (divider);
  2329. g.setColour (bg0);
  2330. g.fillRect (divider.getX(), divider.getY(), divider.getWidth(), 1);
  2331. g.fillRect (divider.getX(), divider.getBottom() - 1, divider.getWidth(), 1);
  2332. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  2333. const auto atEnd = eventPaneBarTop <= top || eventPaneBarTop >= bottom;
  2334. g.setColour (drag == Drag::eventPaneBar && ! atEnd ? accent : atEnd ? textSecondary : bg1);
  2335. const auto centre = divider.getCentre();
  2336. for (int i = -2; i <= 2; ++i)
  2337. g.fillRect (centre.x + i * 4 - 1, centre.y - 1, 2, 2);
  2338. }
  2339. // the zoom wheel (round 190j): FL's small square with a mark in its middle, at the end of the time scroll bar
  2340. {
  2341. const auto wheel = zoomWheelArea().toFloat().reduced (1.0f);
  2342. const auto over = drag == Drag::keyZoom || zoomWheelHover;
  2343. g.setColour (bg2);
  2344. g.fillRect (zoomWheelArea());
  2345. g.setColour (over ? bg5 : bg4);
  2346. g.fillRoundedRectangle (wheel, 2.0f);
  2347. g.setColour (over ? textPrimary : textSecondary);
  2348. g.fillRect (juce::Rectangle<float> (4.0f, 5.0f).withCentre (wheel.getCentre()));
  2349. }
  2350. // top-left corner: channel name
  2351. g.setColour (bg3);
  2352. g.fillRect (0, 0, keyboardWidth, toolbarHeight);
  2353. g.setColour (bg2);
  2354. g.fillRect (0, toolbarHeight, keyboardWidth, headerHeight - toolbarHeight);
  2355. g.setColour (border);
  2356. g.fillRect (0, headerHeight - 1, keyboardWidth, 1);
  2357. g.fillRect (keyboardWidth - 1, 0, 1, headerHeight);
  2358. if (channel < (int) song.channels.size())
  2359. {
  2360. const auto& ch = song.channels[(std::size_t) channel];
  2361. g.setColour (ch.colour != 0 ? theme::tame (juce::Colour (ch.colour)) : accent);
  2362. g.fillRoundedRectangle (4.0f, (float) toolbarHeight + 6.0f, 3.0f, (float) (headerHeight - toolbarHeight) - 12.0f, 1.0f);
  2363. g.setColour (textPrimary);
  2364. g.setFont (theme::font (theme::type::caption, true));
  2365. textcache::drawFittedText (g, juce::String::fromUTF8 (ch.name.c_str()), 11, toolbarHeight, keyboardWidth - 14, headerHeight - toolbarHeight,
  2366. juce::Justification::centredLeft, 2, 0.8f);
  2367. // Freeze (round 190ay): the frozen mark over the notes' top right corner, with what to do
  2368. if (ch.freeze.on())
  2369. {
  2370. const auto text = tr ("Frozen: Unfreeze to edit");
  2371. g.setFont (theme::font (theme::type::caption, true));
  2372. const auto grid = gridArea();
  2373. const auto width = juce::jmin (grid.getWidth() - 8, 34 + juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), text));
  2374. if (width > 40)
  2375. {
  2376. const auto pill = juce::Rectangle<float> ((float) grid.getRight() - (float) width - 6.0f, (float) grid.getY() + 6.0f, (float) width, 20.0f);
  2377. theme::fillRoundRect (g, pill, theme::radius::md, bg1.withAlpha (0.88f));
  2378. theme::drawFrozenTag (g, juce::Rectangle<float> (pill.getX() + 4.0f, pill.getCentreY() - 6.5f, 14.0f, 13.0f), info.withAlpha (0.85f), bg1);
  2379. g.setColour (textSecondary);
  2380. g.drawText (text, pill.withTrimmedLeft (24.0f).withTrimmedRight (6.0f), juce::Justification::centredLeft, true);
  2381. }
  2382. }
  2383. }
  2384. // round gap190og (detail-047): Live's footer under the lanes (its Velocity Controls are child buttons): a 1 px #242424
  2385. // line, then #363636 [SHOT live-01-velocity-lane.png y 977…994]
  2386. if (const auto footer = liveFooterHeight(); footer > 0)
  2387. {
  2388. const auto top = getHeight() - footer;
  2389. g.setColour (juce::Colour (0xff242424));
  2390. g.fillRect (0, top, getWidth(), 1);
  2391. g.setColour (theme::livelook::surface);
  2392. g.fillRect (0, top + 1, getWidth(), footer - 1);
  2393. }
  2394. // round 190mr (DE-63, capture 190mr prhold): FL's hold ring, a thin light arc at the mouse growing clockwise from 12
  2395. // o'clock between 390 and 750 ms of a still press
  2396. if (holdRing && hold != Hold::none)
  2397. {
  2398. const auto elapsed = (int) (juce::Time::getMillisecondCounter() - holdSince);
  2399. const auto t = juce::jlimit (0.0f, 1.0f, (float) (elapsed - holdRingFromMs) / (float) (holdMs - holdRingFromMs));
  2400. if (t > 0.0f)
  2401. {
  2402. juce::Path arc;
  2403. const auto c = holdRingAt.toFloat();
  2404. arc.addCentredArc (c.x, c.y, 6.5f, 6.5f, 0.0f, 0.0f, juce::MathConstants<float>::twoPi * t, true);
  2405. g.setColour (juce::Colour (0xffdfe6e6));
  2406. g.strokePath (arc, juce::PathStrokeType (1.5f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  2407. }
  2408. }
  2409. }
  2410. // --- mouse -------------------------------------------------------------------
  2411. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge) const
  2412. {
  2413. bool left = false;
  2414. return noteAt (x, y, onRightEdge, left);
  2415. }
  2416. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge, bool& onLeftEdge) const
  2417. {
  2418. // the same hit test as the hover (cursor and highlight), so a click does what the cursor showed
  2419. const auto h = hoverAt ({ x, y });
  2420. onRightEdge = h.zone == gesture::Zone::rightEdge;
  2421. onLeftEdge = h.zone == gesture::Zone::leftEdge;
  2422. return gridArea().contains (x, y) ? h.note : -1;
  2423. }
  2424. int PianoRollComponent::ghostAt (int x, int y) const
  2425. {
  2426. if (! showGhosts)
  2427. return -1;
  2428. const auto& notes = currentPattern (engine.getSong()).notes;
  2429. const auto key = yToKey (y);
  2430. for (int i = (int) notes.size() - 1; i >= 0; --i)
  2431. {
  2432. const auto& n = notes[(std::size_t) i];
  2433. if (! edits (n) && n.key == key && ghostShown (n.channel) && x >= tickToX ((double) n.start) && x < tickToX ((double) (n.start + n.length)))
  2434. return i;
  2435. }
  2436. return -1;
  2437. }
  2438. float PianoRollComponent::keyVelocityAt (int x, int key) const
  2439. {
  2440. // FL: a click near the left of a key plays it softly, at its right end at full velocity (black keys are shorter)
  2441. return gesture::keyClickVelocity ((double) x, (double) (isBlackKey (key) ? keyboardWidth * 3 / 5 : keyboardWidth - 1));
  2442. }
  2443. void PianoRollComponent::previewOn (int key, float velocity)
  2444. {
  2445. // one preview note at a time; it remembers its channel, so a channel switch meanwhile can't strand it
  2446. previewNotes.releaseAll();
  2447. previewKey = key;
  2448. previewNotes.press (engine.getSelectedChannel(), key, velocity);
  2449. repaint (0, headerHeight, keyboardWidth, getHeight());
  2450. }
  2451. void PianoRollComponent::previewEdit (int key, float velocity)
  2452. {
  2453. if (gesture::previewsEditedNote (engine.getTransport().playing.load(), previewWhilePlaying))
  2454. previewOn (key, velocity);
  2455. }
  2456. void PianoRollComponent::previewOff()
  2457. {
  2458. previewNotes.releaseAll();
  2459. if (previewKey >= 0)
  2460. {
  2461. previewKey = -1;
  2462. repaint (0, headerHeight, keyboardWidth, getHeight());
  2463. }
  2464. }
  2465. void PianoRollComponent::visibilityChanged()
  2466. {
  2467. if (! isShowing()) // hidden mid-gesture (window closed, tab switched): nothing keeps sounding
  2468. {
  2469. previewOff();
  2470. stopListening();
  2471. }
  2472. }
  2473. // The note properties the bottom lane edits: FL's (velocity, pan, fine pitch, release, Mod X / Y: its "Control" list,
  2474. // FLEngine strings "Note release", "Note modulation X / Y"), then Live 12's Chance and Velocity Range (round 187c, LYNX
  2475. // additions marked "(LYNX)")
  2476. void PianoRollComponent::addNoteLanes()
  2477. {
  2478. laneBox.addItem (tr ("Velocity"), laneVelocity);
  2479. laneBox.addItem (tr ("Pan"), lanePan);
  2480. laneBox.addItem (tr ("Fine pitch"), laneFinePitch);
  2481. laneBox.addItem (tr ("Release"), laneRelease);
  2482. laneBox.addItem (tr ("Mod X"), laneModX);
  2483. laneBox.addItem (tr ("Mod Y"), laneModY);
  2484. laneBox.addItem (tr ("Chance"), laneChance);
  2485. laneBox.addItem (tr ("Velocity range (LYNX)"), laneVelocityRange);
  2486. // round 190pm (research190oe P19): the notes' ratchets, their velocity bend and their Condition (LYNX additions)
  2487. laneBox.addItem (tr ("Ratchets (LYNX)"), laneRatchets);
  2488. laneBox.addItem (tr ("Ratchet velocity (LYNX)"), laneRatchetVelocity);
  2489. laneBox.addItem (tr ("Condition (LYNX)"), laneCondition);
  2490. // MPE stage 2 (round 190hy, issue #108): each note's own pitch bend / slide (CC 74) / pressure curve, as Live 11+'s
  2491. // note expression lanes (LYNX additions: FL 2026 has no per-note curves)
  2492. laneBox.addItem (tr ("MPE pitch bend"), laneMpePitch);
  2493. laneBox.addItem (tr ("MPE slide"), laneMpeSlide);
  2494. laneBox.addItem (tr ("MPE pressure"), laneMpePressure);
  2495. }
  2496. float PianoRollComponent::laneValue (const Note& n) const
  2497. {
  2498. switch (laneId())
  2499. {
  2500. case lanePan: return (n.pan + 1.0f) * 0.5f;
  2501. case laneFinePitch: return (n.finePitch + 120.0f) / 240.0f;
  2502. case laneRelease: return n.release;
  2503. case laneModX: return n.modX;
  2504. case laneModY: return n.modY;
  2505. case laneChance: return n.chance;
  2506. case laneVelocityRange: return (n.velocityRange + 1.0f) * 0.5f;
  2507. case laneRatchets: return (float) (noterepeat::ratchetCount (n) - 1) / (float) (noterepeat::maxRatchets - 1);
  2508. case laneRatchetVelocity: return (n.ratchetVelocity + 1.0f) * 0.5f;
  2509. case laneCondition:
  2510. {
  2511. const auto preset = noteconditions::presetOf (n); // (a cycle of several passes: at the top)
  2512. return preset < 0 ? 1.0f : (float) preset / (float) (noteconditions::presetCount - 1);
  2513. }
  2514. case laneMpePitch: return 0.5f; // (the MPE lanes edit curves, not one value: round 190hy)
  2515. case laneMpeSlide: return n.modX;
  2516. case laneMpePressure: return mpe::pressureOfModY (n.modY);
  2517. default: return n.velocity;
  2518. }
  2519. }
  2520. void PianoRollComponent::setLaneValue (Note& n, float v) const
  2521. {
  2522. v = juce::jlimit (0.0f, 1.0f, v);
  2523. switch (laneId())
  2524. {
  2525. case lanePan: n.pan = std::abs (v - 0.5f) < 0.02f ? 0.0f : v * 2.0f - 1.0f; break; // snaps to center
  2526. case laneFinePitch: n.finePitch = std::round (v * 240.0f - 120.0f); break;
  2527. case laneRelease: n.release = v; break;
  2528. case laneModX: n.modX = v; break;
  2529. case laneModY: n.modY = v; break;
  2530. case laneChance: n.chance = std::round (v * 100.0f) / 100.0f; break; // whole percents, as Live shows them
  2531. case laneVelocityRange: // whole Live velocity steps (1/127); snaps to none
  2532. n.velocityRange = std::abs (v - 0.5f) < 0.02f ? 0.0f : std::round ((v * 2.0f - 1.0f) * 127.0f) / 127.0f;
  2533. break;
  2534. case laneRatchets: // 1 … 8 strikes, in steps (1 = none)
  2535. {
  2536. const auto strikes = 1 + juce::roundToInt (v * (float) (noterepeat::maxRatchets - 1));
  2537. n.ratchets = strikes > 1 ? strikes : 0;
  2538. break;
  2539. }
  2540. case laneRatchetVelocity: // whole percents; snaps to none
  2541. n.ratchetVelocity = std::abs (v - 0.5f) < 0.02f ? 0.0f : std::round ((v * 2.0f - 1.0f) * 100.0f) / 100.0f;
  2542. break;
  2543. case laneCondition: noteconditions::apply (n, noteconditions::preset (juce::roundToInt (v * (float) (noteconditions::presetCount - 1)))); break;
  2544. case laneMpePitch:
  2545. case laneMpeSlide:
  2546. case laneMpePressure: break; // (curves: the MPE lanes' own gestures edit them)
  2547. default: n.velocity = v; break;
  2548. }
  2549. }
  2550. // round 190pm: what a lane value reads as in the hint bar while it is set ("4 strikes", "+20%", "2:4"); "" = a percent
  2551. juce::String PianoRollComponent::laneValueText (float v) const
  2552. {
  2553. v = juce::jlimit (0.0f, 1.0f, v);
  2554. Note n;
  2555. switch (laneId())
  2556. {
  2557. case laneRatchets:
  2558. {
  2559. setLaneValue (n, v);
  2560. const auto strikes = noterepeat::ratchetCount (n);
  2561. return strikes <= 1 ? tr ("No ratchets") : tr ("{0} strikes", { juce::String (strikes) });
  2562. }
  2563. case laneRatchetVelocity:
  2564. setLaneValue (n, v);
  2565. return (n.ratchetVelocity > 0.0f ? "+" : "") + juce::String (juce::roundToInt (n.ratchetVelocity * 100.0f)) + "%";
  2566. case laneCondition:
  2567. setLaneValue (n, v);
  2568. return conditionText (n);
  2569. default: return {};
  2570. }
  2571. }
  2572. juce::String PianoRollComponent::conditionText (const Note& n)
  2573. {
  2574. if (! n.hasCondition())
  2575. return tr ("Always");
  2576. juce::StringArray parts;
  2577. if (n.condition != notecondition::always)
  2578. parts.add (tr (noteconditions::occurrenceName (n.condition)));
  2579. if (n.cycle > 1)
  2580. parts.add (noteconditions::cycleText (n.cycle, n.cycleMask));
  2581. return parts.joinIntoString (", ");
  2582. }
  2583. bool PianoRollComponent::laneIsBipolar() const
  2584. {
  2585. const auto id = laneId();
  2586. return id == lanePan || id == laneFinePitch || id == laneVelocityRange || id == laneRatchetVelocity || id == laneMpePitch || id >= eventLaneIdBase;
  2587. }
  2588. bool PianoRollComponent::laneIsChance() const { return laneId() == laneChance; }
  2589. void PianoRollComponent::applyVelocity (int fromX, int toX, int y)
  2590. {
  2591. const auto lane = velocityArea();
  2592. applyLaneValue (toX, juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8)), fromX);
  2593. }
  2594. void PianoRollComponent::applyLaneValue (int toX, float value, int fromX)
  2595. {
  2596. const auto lo = juce::jmin (fromX, toX) - 3, hi = juce::jmax (fromX, toX) + 3;
  2597. const auto& notes = currentPattern (engine.getSong()).notes;
  2598. std::vector<int> hits;
  2599. for (auto i : selectionOrAll())
  2600. {
  2601. const auto x = (int) tickToX ((double) notes[(std::size_t) i].start);
  2602. if (x >= lo && x <= hi)
  2603. hits.push_back (i);
  2604. }
  2605. if (! hits.empty())
  2606. editNotes ([this, &hits, value] (Pattern& p) {
  2607. for (auto i : hits)
  2608. setLaneValue (p.notes[(std::size_t) i], value);
  2609. if (laneIsChance())
  2610. notetools::spreadGroupChance (p, hits); // a probability group has one Chance
  2611. });
  2612. }
  2613. void PianoRollComponent::togglePorta()
  2614. {
  2615. const auto target = selectionOrAll();
  2616. if (target.empty())
  2617. return;
  2618. // like mute: if any note lacks porta, enable it on all; otherwise disable
  2619. const auto& notes = currentPattern (engine.getSong()).notes;
  2620. const auto porta = std::any_of (target.begin(), target.end(), [&notes] (int i) { return ! notes[(std::size_t) i].porta; });
  2621. editNotes ([&target, porta] (Pattern& p) {
  2622. for (auto i : target)
  2623. p.notes[(std::size_t) i].porta = porta;
  2624. });
  2625. }
  2626. void PianoRollComponent::setNotesMuted (bool mute)
  2627. {
  2628. const auto target = selectionOrAll();
  2629. if (target.empty())
  2630. return;
  2631. editNotes ([&target, mute] (Pattern& p) {
  2632. for (auto i : target)
  2633. p.notes[(std::size_t) i].muted = mute;
  2634. });
  2635. }
  2636. void PianoRollComponent::paintNoteAt (std::int64_t start, int key, bool monophonic)
  2637. {
  2638. // a brush stroke lays single notes (or the chosen chord) at the default length
  2639. Note n;
  2640. noteTemplate.applyTo (n);
  2641. n.start = juce::jmax<std::int64_t> (0, start);
  2642. n.length = paintLength;
  2643. n.key = key;
  2644. n.channel = engine.getSelectedChannel();
  2645. n.slide = slideButton.getToggleState();
  2646. n.colour = noteColour;
  2647. std::vector<Note> stamp;
  2648. for (const auto k : stampKeys (n.key, n.start)) // (the chord stamp; round 190nu: or the Scale degree chord)
  2649. {
  2650. auto chordNote = n;
  2651. chordNote.key = k;
  2652. stamp.push_back (chordNote);
  2653. }
  2654. editNotes ([&] (Pattern& p) {
  2655. if (monophonic) // Shift (or no Shift with "Monophonic painting"): the new note replaces what this channel plays then
  2656. {
  2657. std::vector<int> overlapping;
  2658. for (int i = 0; i < (int) p.notes.size(); ++i)
  2659. {
  2660. const auto& o = p.notes[(std::size_t) i];
  2661. if (o.channel == n.channel && o.start < n.start + n.length && o.start + o.length > n.start)
  2662. overlapping.push_back (i);
  2663. }
  2664. noteedit::remove (p, overlapping);
  2665. }
  2666. noteedit::paste (p, stamp, 0);
  2667. });
  2668. }
  2669. juce::Rectangle<int> PianoRollComponent::zoomWheelArea() const
  2670. {
  2671. // FL's VZoomSelect: the small square at the right end of the time scroll bar, over the vertical scroll bar
  2672. return { getWidth() - zoomWheelSize, toolbarHeight, zoomWheelSize, overviewHeight };
  2673. }
  2674. int PianoRollComponent::zoomAnchorKey() const
  2675. {
  2676. // FL (FUN_00e83850, REA round 167t): the middle of the notes in view, or the middle of the view
  2677. const auto grid = gridArea();
  2678. const auto top = yToKey (grid.getY()), bottom = yToKey (grid.getBottom() - 1);
  2679. const auto& notes = currentPattern (engine.getSong()).notes;
  2680. std::vector<int> keys;
  2681. for (auto i : channelNotes())
  2682. if (const auto key = notes[(std::size_t) i].key; key <= top && key >= bottom)
  2683. keys.push_back (key);
  2684. return gesture::zoomWheelAnchor (keys, top, bottom);
  2685. }
  2686. void PianoRollComponent::setRowHeightAround (int height, int key, int centreY)
  2687. {
  2688. rowHeight = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, height);
  2689. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), rowFor (key) * rowHeight + rowHeight / 2 - (centreY - headerHeight));
  2690. updateScrollBars();
  2691. repaint();
  2692. }
  2693. void PianoRollComponent::beginKeyZoom (const juce::MouseEvent& e)
  2694. {
  2695. drag = Drag::keyZoom;
  2696. keyZoomKey = zoomWheelArea().contains (e.getPosition()) ? zoomAnchorKey() : yToKey (e.y);
  2697. keyZoomStartRow = rowHeight;
  2698. keyZoomCentreY = keyToY (keyZoomKey) + rowHeight / 2;
  2699. keyZoomDrag.begin (e.y);
  2700. e.source.enableUnboundedMouseMovement (true); // FL hides the pointer while the zoom follows the travel
  2701. }
  2702. void PianoRollComponent::beginTimeZoom (const juce::MouseEvent& e)
  2703. {
  2704. drag = Drag::timeZoom;
  2705. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  2706. timeZoomDrag.begin (width / pixelsPerTick, scrollTicks + width * 0.5 / pixelsPerTick, e.x, e.y);
  2707. e.source.enableUnboundedMouseMovement (true);
  2708. }
  2709. void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
  2710. {
  2711. if (touchInput.mouseDown (e)) // round 190pm (P23): a finger in Touch mode is held back until it means something
  2712. return;
  2713. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::begin); // (round 190jv: one undo step per gesture)
  2714. followEditStamp = engine.getPublishCount(); // (round 190im, R15)
  2715. // round 190qe: a zoom glide lands; the press is kept in the song (a selection box's corner while the view runs); the
  2716. // selection before the press is what "Restore selection" brings back if this click replaces it
  2717. settleViewGlide();
  2718. edgeScroller.stop();
  2719. edgeDragEvent.reset();
  2720. dragDownTick = xToTick (e.x);
  2721. dragDownContentY = e.y + scrollY;
  2722. selectionAtPress = noteKeys (selection);
  2723. if (engine.getSong().channels.empty())
  2724. return;
  2725. // round 190on (P10): the line between two stacked lanes drags their heights; a press in a stacked lane works on that
  2726. // lane until the release (velocityArea() and the lane's id are that lane's meanwhile)
  2727. heldLane = boundaryDrag = -1;
  2728. enterLane (-1);
  2729. if (! stacked.empty())
  2730. {
  2731. if (const auto k = laneBoundaryAt (e.getPosition()); k >= 0 && e.mods.isLeftButtonDown())
  2732. {
  2733. boundaryDrag = k;
  2734. boundaryLastY = e.y;
  2735. return;
  2736. }
  2737. if (const auto i = stackedLaneAt (e.getPosition()); i >= 0)
  2738. {
  2739. heldLane = i;
  2740. enterLane (i);
  2741. }
  2742. }
  2743. downMods = e.mods;
  2744. startedOnEmpty = erasedSomething = holdExpired = false;
  2745. // FL's middle + right click (round 190mp, DE-62; capture 190mp A3.2): the second button's press opens the main menu at
  2746. // the mouse with the tools' "Mode" column on its left; whatever the first press began stops
  2747. if (e.mods.isMiddleButtonDown() && e.mods.isRightButtonDown())
  2748. {
  2749. showToolModeMenu();
  2750. return;
  2751. }
  2752. const auto onKeyboard = e.x < keyboardWidth && e.y >= headerHeight && e.y < gridArea().getBottom();
  2753. hover = {};
  2754. gliding = false;
  2755. // the zoom wheel (round 190j, discussion #10; FL's VZoomSelect): drag up = taller keys, one level (2 px) per 4 px of
  2756. // travel, per 16 px with Ctrl
  2757. if (zoomWheelArea().contains (e.getPosition()))
  2758. {
  2759. if (e.mods.isLeftButtonDown() || e.mods.isMiddleButtonDown())
  2760. beginKeyZoom (e);
  2761. return;
  2762. }
  2763. // the event editor's divider (round 190fz, FL's TQuickSplitter): left-drag moves it, a double-click or a right-click
  2764. // (swapped on release) gives the alternate size, a middle-click the default place
  2765. if (eventPaneBarArea().contains (e.getPosition()))
  2766. {
  2767. if (e.mods.isMiddleButtonDown())
  2768. resetEventPane();
  2769. else if (e.mods.isRightButtonDown())
  2770. drag = Drag::eventPaneAlternate;
  2771. else if (e.mods.isLeftButtonDown() && e.getNumberOfClicks() >= 2)
  2772. toggleEventPaneAlternate();
  2773. else if (e.mods.isLeftButtonDown())
  2774. {
  2775. drag = Drag::eventPaneBar;
  2776. eventPaneGrab = e.y - eventPaneBarTop;
  2777. repaint (eventPaneBarArea());
  2778. }
  2779. return;
  2780. }
  2781. // FL (TLEventPanelDblClick): a double-click on the event target panel, left of the event editor, swaps it too
  2782. if (! fitKeysToNotes && e.mods.isLeftButtonDown() && e.getNumberOfClicks() >= 2 && e.x < keyboardWidth && e.y >= velocityArea().getY())
  2783. {
  2784. toggleEventPaneAlternate();
  2785. return;
  2786. }
  2787. if (e.mods.isMiddleButtonDown())
  2788. {
  2789. // FL 2026 (round 167t, issue #26): middle-drag on the keyboard and Ctrl+middle-drag on the notes zoom
  2790. // vertically around the key under the mouse; middle-drag on the ruler and Alt+middle-drag on the notes
  2791. // zoom the time (drag up = zoom in, sideways = scroll)
  2792. const auto onNotes = gridArea().contains (e.getPosition());
  2793. const auto onRuler = e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth;
  2794. if (onKeyboard || (onNotes && flmods::ctrl (e.mods) && ! e.mods.isAltDown()))
  2795. {
  2796. beginKeyZoom (e);
  2797. return;
  2798. }
  2799. if (onRuler || (onNotes && e.mods.isAltDown()))
  2800. {
  2801. beginTimeZoom (e);
  2802. return;
  2803. }
  2804. drag = Drag::pan; // elsewhere it pans both ways, in every tool
  2805. panStartTicks = scrollTicks;
  2806. panStartY = scrollY;
  2807. setMouseCursor (editorCursor (gesture::Cursor::pan));
  2808. return;
  2809. }
  2810. if (onKeyboard)
  2811. {
  2812. if (flmods::ctrl (e.mods)) // Ctrl+click / drag: selects the notes of a key (range)
  2813. {
  2814. drag = Drag::keySelect;
  2815. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  2816. mouseDrag (e);
  2817. return;
  2818. }
  2819. if (e.mods.isRightButtonDown()) // key labels (FL 2026: right-click a key > Rename)
  2820. {
  2821. showKeyMenu (keyboardKeyAt (e.x, e.y));
  2822. return;
  2823. }
  2824. if (e.mods.isLeftButtonDown())
  2825. {
  2826. drag = Drag::keyboard;
  2827. previewOn (keyboardKeyAt (e.x, e.y), keyVelocityAt (e.x, keyboardKeyAt (e.x, e.y)));
  2828. }
  2829. return;
  2830. }
  2831. // ruler: a right press on a pattern marker opens its menu (FL's TimePanelMouseDown: the marker menu when the press
  2832. // is on the marker lane, REA_rodada168t.md table); the Time markers items are also in the More menu (round 168g)
  2833. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))
  2834. if (const auto mk = markerAtX (e.x); mk >= 0)
  2835. {
  2836. showPatternMarkerMenu (mk);
  2837. return;
  2838. }
  2839. // ruler: a time-range drag selects the notes in it. FL 2026 (one ruler handler for the Piano roll and the Playlist,
  2840. // TimePanelMouseDown 0xe56bf0, REA_rodada168t.md): Ctrl+drag, a double click held and dragged, the Select tool, or
  2841. // a right-drag (on a Mac Cmd or Control: core/ModifierMap.h)
  2842. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth
  2843. && ((e.mods.isLeftButtonDown() && (flmods::ctrl (e.mods) || e.getNumberOfClicks() >= 2 || (tools.getTool() == EditTool::lasso && ! ruler::seekWithAnyTool()))) // (#227: LYNX extra)
  2844. || (e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))))
  2845. {
  2846. drag = Drag::rulerSelect;
  2847. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  2848. return;
  2849. }
  2850. // ruler: click or drag = position (FL), Alt = off the grid
  2851. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isLeftButtonDown() && ! e.mods.isShiftDown())
  2852. {
  2853. drag = Drag::seek;
  2854. rulerMark = juce::jmax<std::int64_t> (0, e.mods.isAltDown() ? (std::int64_t) xToTick (e.x) : snap (xToTick (e.x), true)); // (FL's paste anchor, issue #211)
  2855. seekAt (e.x, ! e.mods.isAltDown());
  2856. return;
  2857. }
  2858. // round 190jd: the MPE tab's ▾ "Show Lane:" button and the focused lane's name, under the key column (Live 12.4)
  2859. if (mpeStacked && e.mods.isLeftButtonDown() && e.x < keyboardWidth && mpeFooterArea().contains (e.getPosition()))
  2860. {
  2861. mpeLaneMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this)
  2862. .withTargetScreenArea (localAreaToGlobal (mpeFooterArea().withWidth (keyboardWidth))));
  2863. return;
  2864. }
  2865. // Freeze (round 190ay): a frozen channel's notes and their lane are read-only (the keyboard, the ruler and the
  2866. // view gestures above still work)
  2867. if ((velocityArea().contains (e.getPosition()) || gridArea().contains (e.getPosition())) && refuseFrozenEdit())
  2868. return;
  2869. if (velocityArea().contains (e.getPosition()) && mpeMouseDown (e))
  2870. return;
  2871. if (velocityArea().contains (e.getPosition()) && eventLaneTarget())
  2872. {
  2873. // pattern events: drag draws one event per grid step, right-drag erases
  2874. lastVelocityX = e.x;
  2875. drag = e.mods.isRightButtonDown() ? Drag::eventErase : Drag::eventDraw;
  2876. drawEvents (e.x, e.x, e.y, drag == Drag::eventErase);
  2877. return;
  2878. }
  2879. if (velocityArea().contains (e.getPosition()))
  2880. {
  2881. const auto lane = velocityArea();
  2882. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  2883. lastVelocityX = e.x;
  2884. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click resets the notes under the mouse
  2885. {
  2886. drag = Drag::velocity;
  2887. applyLaneValue (e.x, laneValue (Note()), e.x); // (each property's default)
  2888. drag = Drag::none;
  2889. return;
  2890. }
  2891. laneOriginals = currentPattern (engine.getSong()).notes;
  2892. if (e.mods.isRightButtonDown()) // right-drag draws a straight line of values
  2893. {
  2894. drag = Drag::velocityLine;
  2895. laneSetValue = value;
  2896. return;
  2897. }
  2898. if (e.mods.isShiftDown()) // Shift+drag: every note crossed gets the value of the press
  2899. {
  2900. drag = Drag::velocitySet;
  2901. laneSetValue = value;
  2902. applyLaneValue (e.x, value, e.x);
  2903. return;
  2904. }
  2905. drag = Drag::velocity;
  2906. applyVelocity (e.x, e.x, e.y);
  2907. return;
  2908. }
  2909. if (! gridArea().contains (e.getPosition()))
  2910. return;
  2911. // the selection's stretch handle: drag scales the selected notes in time from the selection's start
  2912. if (e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods) && stretchHandle().expanded (2.0f).contains (e.position))
  2913. {
  2914. const auto& notes = currentPattern (engine.getSong()).notes;
  2915. dragIndices.clear();
  2916. dragOriginals.clear();
  2917. for (auto i : selection)
  2918. if (i >= 0 && i < (int) notes.size() && edits (notes[(std::size_t) i]))
  2919. {
  2920. dragIndices.push_back (i);
  2921. dragOriginals.push_back (notes[(std::size_t) i]);
  2922. }
  2923. noteedit::span (dragOriginals, stretchAnchor, stretchEnd);
  2924. dragNote = dragIndices.empty() ? -1 : dragIndices.front();
  2925. drag = Drag::stretch;
  2926. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  2927. return;
  2928. }
  2929. bool rightEdge = false, leftEdge = false;
  2930. const auto hit = noteAt (e.x, e.y, rightEdge, leftEdge);
  2931. const auto tool = tools.getTool();
  2932. // round 190jd: the MPE tab edits the pitch on the notes, as Live 12.4 (a selected note's pitch points, a click on it)
  2933. if (mpeStacked && e.mods.isLeftButtonDown() && mpePitchMouseDown (e, hit, rightEdge || leftEdge))
  2934. return;
  2935. // editable ghost notes (Ctrl+Alt+V): a left press on one switches to its channel and grabs the note there
  2936. if (hit < 0 && editGhosts && e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods))
  2937. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  2938. {
  2939. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  2940. if (noteAt (e.x, e.y, rightEdge, leftEdge) >= 0) // now it is one of this channel's notes
  2941. mouseDown (e);
  2942. return;
  2943. }
  2944. // Zoom tool: right-click zooms out around the point (a click zooms in, a drag zooms to the range)
  2945. if (tool == EditTool::zoom && e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))
  2946. {
  2947. zoomOut (e.x);
  2948. return;
  2949. }
  2950. // every tool: right click deletes (double right-click on a ghost note switches to its channel; with
  2951. // editable ghost notes a right-click deletes the ghost note itself)
  2952. if (e.mods.isRightButtonDown())
  2953. {
  2954. if (hit < 0 && editGhosts)
  2955. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  2956. {
  2957. setSelection ({});
  2958. editNotes ([ghost] (Pattern& p) { noteedit::remove (p, { ghost }); });
  2959. return;
  2960. }
  2961. if (hit < 0 && e.getNumberOfClicks() >= 2)
  2962. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  2963. {
  2964. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  2965. return;
  2966. }
  2967. drag = Drag::erase;
  2968. startedOnEmpty = hit < 0;
  2969. setSelection ({}); // indices change while deleting
  2970. if (hit >= 0)
  2971. {
  2972. erasedSomething = true;
  2973. fadeOut ({ hit }); // (issue #250)
  2974. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  2975. }
  2976. return;
  2977. }
  2978. // every tool: Ctrl+click on a note adds/removes it from the selection; Ctrl+drag selects (Shift adds)
  2979. if (hit >= 0 && flmods::ctrl (e.mods))
  2980. {
  2981. auto s = selection;
  2982. if (isSelected (hit))
  2983. s.erase (std::find (s.begin(), s.end(), hit));
  2984. else
  2985. s.push_back (hit);
  2986. setSelection (s);
  2987. return;
  2988. }
  2989. if ((hit < 0 && flmods::ctrl (e.mods)) || tool == EditTool::lasso
  2990. || (hit < 0 && e.mods.isShiftDown() && tool != EditTool::brush && tool != EditTool::drumPaint && tool != EditTool::pencil))
  2991. {
  2992. drag = Drag::select;
  2993. dragNote = hit; // a click without dragging selects this note (Lasso)
  2994. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  2995. rubberBand = {};
  2996. setSelection (selectionBefore);
  2997. return;
  2998. }
  2999. const auto snapOn = ! e.mods.isAltDown();
  3000. switch (tool)
  3001. {
  3002. case EditTool::eraser:
  3003. drag = Drag::erase;
  3004. setSelection ({});
  3005. if (hit >= 0)
  3006. {
  3007. fadeOut ({ hit }); // (issue #250)
  3008. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  3009. }
  3010. return;
  3011. case EditTool::mute:
  3012. drag = Drag::muting;
  3013. touchedNotes.clear();
  3014. if (hit >= 0)
  3015. {
  3016. muteTarget = ! currentPattern (engine.getSong()).notes[(std::size_t) hit].muted;
  3017. touchedNotes.push_back (hit);
  3018. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  3019. }
  3020. else
  3021. muteTarget = true;
  3022. return;
  3023. case EditTool::knife:
  3024. drag = Drag::knife;
  3025. knifeFrom = knifeTo = e.getPosition();
  3026. repaint();
  3027. return;
  3028. case EditTool::zoom:
  3029. drag = Drag::zoomRange;
  3030. rubberBand = {};
  3031. return;
  3032. case EditTool::listen:
  3033. drag = Drag::listen;
  3034. listenAt (e.x);
  3035. return;
  3036. case EditTool::pencil:
  3037. case EditTool::brush:
  3038. case EditTool::drumPaint:
  3039. case EditTool::lasso:
  3040. case EditTool::slip:
  3041. break;
  3042. }
  3043. // Pencil (and Brush on an existing note): Shift+drag on a note drags a copy
  3044. if (hit >= 0 && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  3045. {
  3046. const auto sources = isSelected (hit) ? selection : notetools::groupOf (currentPattern (engine.getSong()), hit);
  3047. const auto grabbedAt = (std::size_t) (std::find (sources.begin(), sources.end(), hit) - sources.begin());
  3048. std::vector<int> added;
  3049. // the copy comes out in the same order as the originals (copy sorts by start)
  3050. std::vector<Note> ordered;
  3051. for (auto i : sources)
  3052. ordered.push_back (currentPattern (engine.getSong()).notes[(std::size_t) i]);
  3053. editNotes ([&] (Pattern& p) {
  3054. added = noteedit::paste (p, ordered, 0);
  3055. notetools::regroup (p, added);
  3056. });
  3057. setSelection (added);
  3058. dragIndices = added;
  3059. dragOriginals = ordered;
  3060. lastScaleDragKeys = -1000;
  3061. dragNote = added[grabbedAt];
  3062. drag = Drag::move;
  3063. grabOffset = ordered[grabbedAt].start - snap (xToTick (e.x), snapOn);
  3064. previewEdit (ordered[grabbedAt].key, ordered[grabbedAt].velocity);
  3065. return;
  3066. }
  3067. if (hit >= 0)
  3068. {
  3069. const auto wasSelected = isSelected (hit);
  3070. if (! wasSelected) // a grouped note brings its group along (FL's note groups)
  3071. {
  3072. const auto members = notetools::groupOf (currentPattern (engine.getSong()), hit);
  3073. setSelection (members.size() > 1 ? members : std::vector<int> {});
  3074. }
  3075. const auto& notes = currentPattern (engine.getSong()).notes;
  3076. const auto& n = notes[(std::size_t) hit];
  3077. dragNote = hit;
  3078. dragIndices = selection.empty() ? std::vector<int> { hit } : selection;
  3079. dragOriginals.clear();
  3080. for (auto i : dragIndices)
  3081. dragOriginals.push_back (notes[(std::size_t) i]);
  3082. drag = rightEdge ? Drag::resize : leftEdge ? Drag::resizeLeft : Drag::move;
  3083. lastScaleDragKeys = 0; // (no scale step made yet)
  3084. // round 190mr (DE-63): FL's click-and-hold on a note (copy) or at the resize cursor between two touching notes (glue)
  3085. if (! e.mods.isShiftDown() && ! e.mods.isAltDown() && (tool == EditTool::pencil || tool == EditTool::brush))
  3086. {
  3087. if (drag == Drag::move && flsettings::options().clickHold.load())
  3088. armHold (Hold::copy, e.getScreenPosition());
  3089. else if (drag != Drag::move && flsettings::options().clickHold.load())
  3090. {
  3091. const auto& pat = currentPattern (engine.getSong());
  3092. const auto other = details190mr::touchingNeighbour (pat, hit, rightEdge);
  3093. if (other >= 0)
  3094. {
  3095. glueA = rightEdge ? hit : other;
  3096. glueB = rightEdge ? other : hit;
  3097. armHold (Hold::glue, e.getScreenPosition());
  3098. }
  3099. }
  3100. }
  3101. grabOffset = n.start - snap (xToTick (e.x), snapOn);
  3102. lastLength = n.length;
  3103. noteTemplate.takeFrom (n); // FL: new notes get the clicked note's properties (round 166e)
  3104. if (gesture::previewsGrabbedNote (rightEdge || leftEdge, wasSelected)) // FL: no sound on a resize or a selected grab
  3105. previewEdit (n.key, n.velocity);
  3106. return;
  3107. }
  3108. // new note (or the chosen chord, with the clicked note as the root)
  3109. setSelection ({});
  3110. createdAt = juce::Time::getMillisecondCounter();
  3111. if (tool == EditTool::drumPaint)
  3112. {
  3113. drag = Drag::drumPaint;
  3114. lastDrumCell = -1;
  3115. lastDrumKey = -1;
  3116. drumPaintAt (e.getPosition(), snapOn);
  3117. return;
  3118. }
  3119. if (tool == EditTool::brush)
  3120. {
  3121. drag = Drag::paint;
  3122. paintLength = juce::jmax<std::int64_t> (1, newNoteLength());
  3123. const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  3124. paintNoteAt (start, snapKey (yToKey (e.y)), noteedit::monophonicPaint (e.mods.isShiftDown(), monophonicPainting));
  3125. nextPaintTick = start + paintLength;
  3126. previewEdit (snapKey (yToKey (e.y)), noteTemplate.velocity);
  3127. return;
  3128. }
  3129. Note n;
  3130. noteTemplate.applyTo (n);
  3131. n.start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  3132. n.length = newNoteLength();
  3133. n.channel = engine.getSelectedChannel();
  3134. n.slide = slideButton.getToggleState();
  3135. n.colour = noteColour;
  3136. // the chord stamp's notes on the clicked key (round 190nu: or the Scale degree chord in the key of the click's region);
  3137. // the first one leads the drag
  3138. std::vector<Note> stamp;
  3139. for (const auto k : stampKeys (isDegreeStamp() ? yToKey (e.y) : snapKey (yToKey (e.y)), n.start))
  3140. {
  3141. auto chordNote = n;
  3142. chordNote.key = k;
  3143. stamp.push_back (chordNote);
  3144. }
  3145. n.key = stamp.empty() ? snapKey (yToKey (e.y)) : stamp.front().key;
  3146. clearDegreeGhost();
  3147. std::vector<int> added;
  3148. editNotes ([&] (Pattern& p) { added = noteedit::paste (p, stamp, 0); });
  3149. dragNote = added.front(); // the root leads the drag
  3150. dragIndices = added;
  3151. dragOriginals = stamp;
  3152. lastScaleDragKeys = -1000;
  3153. if (added.size() > 1)
  3154. setSelection (added);
  3155. drag = Drag::move;
  3156. // round 190mv (DE-69): FL's Draw tool "(Shift) add in stretch mode" (capture 190mv A3: Shift+press on the empty grid
  3157. // adds the note at the snapped spot and the drag stretches its end, the start stays; plain Draw moves it)
  3158. if (tool == EditTool::pencil && e.mods.isShiftDown())
  3159. drag = Drag::resize;
  3160. grabOffset = 0;
  3161. previewEdit (n.key, n.velocity);
  3162. holdStep = n.porta ? 2 : n.slide ? 1 : 0;
  3163. if (! e.mods.isShiftDown() && ! e.mods.isAltDown() && flsettings::options().clickHold.load())
  3164. armHold (Hold::cycle, e.getScreenPosition()); // round 190mr (DE-63): hold = slide, porta, plain…
  3165. }
  3166. void PianoRollComponent::pressForSnapshot (juce::Point<int> at, juce::ModifierKeys mods)
  3167. {
  3168. auto source = juce::Desktop::getInstance().getMainMouseSource();
  3169. const auto now = juce::Time::getCurrentTime();
  3170. mouseDown (juce::MouseEvent (source, at.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, this, this, now, at.toFloat(), now, 1, false));
  3171. holdRingAt = at; // (off screen, the screen point of the press is not this view's)
  3172. }
  3173. void PianoRollComponent::dragForSnapshot (juce::Point<int> at, juce::ModifierKeys mods)
  3174. {
  3175. auto source = juce::Desktop::getInstance().getMainMouseSource();
  3176. const auto now = juce::Time::getCurrentTime();
  3177. mouseDrag (juce::MouseEvent (source, at.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, this, this, now, at.toFloat(), now, 1, false));
  3178. }
  3179. void PianoRollComponent::releaseForSnapshot (juce::Point<int> at)
  3180. {
  3181. auto source = juce::Desktop::getInstance().getMainMouseSource();
  3182. const auto now = juce::Time::getCurrentTime();
  3183. mouseUp (juce::MouseEvent (source, at.toFloat(), {}, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, this, this, now, at.toFloat(), now, 1, false));
  3184. }
  3185. void PianoRollComponent::armHold (Hold kind, juce::Point<int> screenAt, bool ring)
  3186. {
  3187. hold = kind;
  3188. holdDownAt = screenAt;
  3189. holdSince = juce::Time::getMillisecondCounter();
  3190. holdRing = ring; // (the cycle's later steps run without it)
  3191. holdRingAt = getLocalPoint (nullptr, screenAt);
  3192. const auto serial = ++holdSerial;
  3193. juce::Timer::callAfterDelay (holdMs, [safe = juce::Component::SafePointer<PianoRollComponent> (this), serial] {
  3194. if (safe != nullptr)
  3195. safe->holdFired (serial);
  3196. });
  3197. }
  3198. void PianoRollComponent::holdFired (int serial)
  3199. {
  3200. if (serial != holdSerial || hold == Hold::none)
  3201. return;
  3202. const auto& mouse = juce::Desktop::getInstance().getMainMouseSource();
  3203. // (a hold is a press that stays where it was: a drag, a release or another button ends it)
  3204. if (holdReadsMouse && ! mouse.isDragging() && ! juce::ModifierKeys::currentModifiers.isLeftButtonDown())
  3205. return void (hold = Hold::none);
  3206. if (holdReadsMouse && (mouse.getScreenPosition().roundToInt().getDistanceFrom (holdDownAt) > 3 || juce::ModifierKeys::currentModifiers.isRightButtonDown()))
  3207. return void (hold = Hold::none);
  3208. const auto kind = std::exchange (hold, Hold::none);
  3209. if (std::exchange (holdRing, false))
  3210. repaint (holdRingArea());
  3211. const auto& notes = currentPattern (engine.getSong()).notes;
  3212. if (kind == Hold::copy && drag == Drag::move && ! dragIndices.empty())
  3213. {
  3214. // the copy is what the mouse drags from here on; the originals stay (as Shift+drag)
  3215. std::vector<Note> ordered;
  3216. for (auto i : dragIndices)
  3217. if (i >= 0 && i < (int) notes.size())
  3218. ordered.push_back (notes[(std::size_t) i]);
  3219. const auto grabbedAt = (std::size_t) juce::jmax<std::ptrdiff_t> (0, std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin());
  3220. // FL's "clone note": the clone lands one grid step later and is the one dragged from here on
  3221. const auto step = juce::jmax<std::int64_t> (1, gridTicks());
  3222. for (auto& n : ordered)
  3223. n.start += step;
  3224. std::vector<int> added;
  3225. editNotes ([&] (Pattern& p) {
  3226. added = noteedit::paste (p, ordered, 0);
  3227. notetools::regroup (p, added);
  3228. });
  3229. if (added.empty())
  3230. return;
  3231. setSelection (added);
  3232. dragIndices = added;
  3233. dragOriginals = ordered;
  3234. lastScaleDragKeys = -1000;
  3235. grabOffset += step;
  3236. dragNote = added[juce::jmin (grabbedAt, added.size() - 1)];
  3237. ui::postHint ({ tr ("Note cloned: drag it where it goes"), {}, false, false }, 1500);
  3238. repaint();
  3239. return;
  3240. }
  3241. if (kind == Hold::cycle && drag == Drag::move && ! dragIndices.empty())
  3242. {
  3243. holdStep = (holdStep + 1) % 3;
  3244. editNotes ([this] (Pattern& p) {
  3245. for (auto i : dragIndices)
  3246. if (i >= 0 && i < (int) p.notes.size())
  3247. details190mr::setHoldCycle (p.notes[(std::size_t) i], holdStep);
  3248. });
  3249. static const char* const names[] = { TR_NOOP ("Plain note"), TR_NOOP ("Slide note"), TR_NOOP ("Porta note") };
  3250. ui::postHint ({ tr (names[holdStep]) + " " + tr ("(keep holding to change it)"), {}, false, false }, holdMs + 400);
  3251. repaint();
  3252. armHold (Hold::cycle, holdDownAt, false); // (the next step, while the button stays down)
  3253. return;
  3254. }
  3255. if (kind == Hold::glue && (drag == Drag::resize || drag == Drag::resizeLeft) && glueA >= 0 && glueB >= 0)
  3256. {
  3257. const auto keep = juce::jmin (glueA, glueB);
  3258. editNotes ([a = glueA, b = glueB] (Pattern& p) { noteedit::join (p, { a, b }); });
  3259. drag = Drag::none;
  3260. dragIndices.clear();
  3261. dragOriginals.clear();
  3262. dragNote = -1;
  3263. setSelection ({ keep }); // (FL: the glued note is selected; join keeps the earlier index)
  3264. ui::postHint ({ tr ("Notes glued"), {}, false, false }, 1500);
  3265. repaint();
  3266. }
  3267. }
  3268. void PianoRollComponent::mouseDrag (const juce::MouseEvent& e)
  3269. {
  3270. if (touchInput.mouseDrag (e)) // round 190pm (P23)
  3271. return;
  3272. if (boundaryDrag >= 0) // round 190on (P10): two stacked lanes' heights
  3273. {
  3274. std::vector<float> weights;
  3275. for (const auto& l : stacked)
  3276. weights.push_back (l->spec.weight);
  3277. weights.push_back (bottomWeight);
  3278. stackedlanes::dragBoundary (weights, eventPaneArea().getHeight(), boundaryDrag, e.y - boundaryLastY);
  3279. boundaryLastY = e.y;
  3280. for (std::size_t i = 0; i < stacked.size(); ++i)
  3281. stacked[i]->spec.weight = weights[i];
  3282. bottomWeight = weights.back();
  3283. resized();
  3284. repaint (eventPaneArea().withX (0).withWidth (getWidth()));
  3285. return;
  3286. }
  3287. // round 190qe (D2-PL1): past the editor's edge the view runs (feelFrame); the dragged notes, the brush and the lane
  3288. // stroke stay at the edge meanwhile, as FL keeps them (round 190qc)
  3289. if (! edgeLayout && (edgeScrollsX() || edgeScrollsY()))
  3290. {
  3291. edgeDragEvent.emplace (e); // (the real pointer: the speed comes from how far past the edge it is)
  3292. frames.wake();
  3293. if (drag != Drag::select)
  3294. {
  3295. const auto grid = gridArea();
  3296. const auto lane = edgeOnLane() ? velocityArea() : grid;
  3297. const auto x = edgeScrollsX() ? (float) edgescroll::clampInto (e.position.x, grid.getX(), grid.getRight()) : e.position.x;
  3298. const auto y = edgeScrollsY() ? (float) edgescroll::clampInto (e.position.y, lane.getY(), lane.getBottom()) : e.position.y;
  3299. if (x != e.position.x || y != e.position.y)
  3300. {
  3301. const juce::ScopedValueSetter<bool> layout (edgeLayout, true);
  3302. mouseDrag (e.withNewPosition (juce::Point<float> (x, y)));
  3303. return;
  3304. }
  3305. }
  3306. }
  3307. const auto snapOn = ! e.mods.isAltDown();
  3308. // after the step below, the hint bar says what the gesture is doing
  3309. const struct PostAfter
  3310. {
  3311. PianoRollComponent& roll;
  3312. const juce::MouseEvent& event;
  3313. ~PostAfter() { roll.postDragHint (event); }
  3314. } postAfter { *this, e };
  3315. switch (drag)
  3316. {
  3317. case Drag::none:
  3318. return;
  3319. case Drag::mpePoint: // round 190hy: the notes' MPE curves
  3320. case Drag::mpeDraw:
  3321. case Drag::mpeErase:
  3322. case Drag::mpeBend: // round 190jd: a pitch point on a note, a Velocity / Release Velocity lane
  3323. case Drag::mpeValue:
  3324. mpeMouseDrag (e);
  3325. return;
  3326. case Drag::eventPaneBar: // round 190fz: the divider follows the mouse (FL's SplitterChanging rule)
  3327. moveEventPaneBar (e.y - eventPaneGrab);
  3328. return;
  3329. case Drag::eventPaneAlternate: // (swapped when the right button is released)
  3330. return;
  3331. case Drag::pan:
  3332. scrollTicks = juce::jmax (0.0, panStartTicks - e.getDistanceFromDragStartX() / pixelsPerTick);
  3333. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), panStartY - e.getDistanceFromDragStartY());
  3334. updateScrollBars();
  3335. repaint();
  3336. return;
  3337. case Drag::keyboard:
  3338. {
  3339. const auto key = keyboardKeyAt (e.x, e.y);
  3340. if (key != previewKey)
  3341. previewOn (key, keyVelocityAt (e.x, key));
  3342. return;
  3343. }
  3344. case Drag::keyZoom:
  3345. {
  3346. // up = taller keys (Ctrl: fine); the centre of the clicked key stays where it was
  3347. keyZoomDrag.move (e.y, flmods::ctrl (e.mods));
  3348. rowHeight = keyZoomDrag.height (keyZoomStartRow);
  3349. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()),
  3350. rowFor (keyZoomKey) * rowHeight + rowHeight / 2 - (keyZoomCentreY - headerHeight));
  3351. updateScrollBars();
  3352. repaint();
  3353. return;
  3354. }
  3355. case Drag::timeZoom:
  3356. {
  3357. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  3358. timeZoomDrag.move (e.x, e.y, flmods::ctrl (e.mods));
  3359. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, width / timeZoomDrag.span);
  3360. scrollTicks = juce::jmax (0.0, timeZoomDrag.centre - width * 0.5 / pixelsPerTick);
  3361. updateScrollBars();
  3362. repaint();
  3363. return;
  3364. }
  3365. case Drag::keySelect:
  3366. {
  3367. const auto k0 = yToKey (e.getMouseDownY()), k1 = yToKey (e.y);
  3368. const auto& notes = currentPattern (engine.getSong()).notes;
  3369. auto s = selectionBefore;
  3370. for (auto i : channelNotes())
  3371. if (const auto k = notes[(std::size_t) i].key; k >= juce::jmin (k0, k1) && k <= juce::jmax (k0, k1))
  3372. s.push_back (i);
  3373. setSelection (s);
  3374. return;
  3375. }
  3376. case Drag::rulerSelect:
  3377. {
  3378. const auto t0 = (double) snap (xToTick (juce::jmin (e.getMouseDownX(), e.x)), snapOn);
  3379. const auto t1 = (double) snap (xToTick (juce::jmax (e.getMouseDownX(), e.x)) + (snapOn ? (double) gridTicks() : 0.0), snapOn);
  3380. const auto& notes = currentPattern (engine.getSong()).notes;
  3381. auto s = selectionBefore;
  3382. for (auto i : channelNotes())
  3383. if (const auto& n = notes[(std::size_t) i]; (double) n.start >= t0 && (double) n.start < t1)
  3384. s.push_back (i);
  3385. rubberBand = juce::Rectangle<int>::leftTopRightBottom ((int) tickToX (t0), gridArea().getY(), (int) tickToX (t1), gridArea().getBottom());
  3386. timeFrom = (std::int64_t) t0; // (round 168g: the range stays as the time selection)
  3387. timeTo = (std::int64_t) t1;
  3388. setSelection (s);
  3389. return;
  3390. }
  3391. case Drag::velocity:
  3392. applyVelocity (lastVelocityX, e.x, e.y);
  3393. lastVelocityX = e.x;
  3394. if (liveNotes()) // (round 190mf, DL-80: Live's value in the lane header follows the drag)
  3395. repaint (0, velocityArea().getY(), keyboardWidth, velocityArea().getHeight());
  3396. return;
  3397. case Drag::eventDraw:
  3398. case Drag::eventErase:
  3399. drawEvents (lastVelocityX, e.x, e.y, drag == Drag::eventErase);
  3400. lastVelocityX = e.x;
  3401. return;
  3402. case Drag::velocitySet:
  3403. applyLaneValue (e.x, laneSetValue, lastVelocityX);
  3404. lastVelocityX = e.x;
  3405. return;
  3406. case Drag::velocityLine:
  3407. {
  3408. // from the press to the mouse: notes in between follow the line, the others keep their value
  3409. const auto lane = velocityArea();
  3410. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  3411. const auto x0 = e.getMouseDownX(), x1 = e.x;
  3412. const auto lo = juce::jmin (x0, x1) - 3, hi = juce::jmax (x0, x1) + 3;
  3413. const auto targets = selectionOrAll();
  3414. knifeFrom = { x0, juce::roundToInt ((float) lane.getBottom() - 2.0f - laneSetValue * (float) (lane.getHeight() - 8)) };
  3415. knifeTo = e.getPosition();
  3416. editNotes ([&] (Pattern& p) {
  3417. for (auto i : targets)
  3418. {
  3419. if ((std::size_t) i >= laneOriginals.size() || (std::size_t) i >= p.notes.size())
  3420. continue;
  3421. auto& n = p.notes[(std::size_t) i];
  3422. n = laneOriginals[(std::size_t) i];
  3423. const auto x = (int) tickToX ((double) n.start);
  3424. if (x >= lo && x <= hi)
  3425. setLaneValue (n, (float) gesture::lineValue (x0, laneSetValue, x1, value, x));
  3426. }
  3427. if (laneIsChance())
  3428. notetools::spreadGroupChance (p, targets);
  3429. });
  3430. repaint();
  3431. return;
  3432. }
  3433. case Drag::select:
  3434. case Drag::zoomRange:
  3435. {
  3436. if (e.getDistanceFromDragStart() < 3 && rubberBand.isEmpty())
  3437. return;
  3438. const auto area = gridArea();
  3439. rubberBand = juce::Rectangle<int> (e.getMouseDownPosition(), e.getPosition()).getIntersection (area);
  3440. if (drag == Drag::zoomRange)
  3441. {
  3442. rubberBand = rubberBand.withY (area.getY()).withHeight (area.getHeight());
  3443. repaint();
  3444. return;
  3445. }
  3446. // (round 190qe: the box's corner stays where it was pressed in the song while the view runs at an edge; the
  3447. // notes between it and the pointer are selected, also the ones scrolled out of view)
  3448. const juce::Point<int> corner ((int) juce::jlimit (-1.0e6, 1.0e6, std::round (tickToX (dragDownTick))), dragDownContentY - scrollY);
  3449. const auto box = juce::Rectangle<int> (corner, e.getPosition());
  3450. rubberBand = box.getIntersection (area);
  3451. const auto t0 = juce::jmin (dragDownTick, xToTick (e.x)), t1 = juce::jmax (dragDownTick, xToTick (e.x));
  3452. const auto kTop = yToKey (box.getY()), kBottom = yToKey (box.getBottom());
  3453. const auto& notes = currentPattern (engine.getSong()).notes;
  3454. auto s = selectionBefore;
  3455. for (auto i : channelNotes())
  3456. {
  3457. const auto& n = notes[(std::size_t) i];
  3458. if ((double) (n.start + n.length) > t0 && (double) n.start < t1 && n.key <= kTop && n.key >= kBottom)
  3459. s.push_back (i);
  3460. }
  3461. setSelection (s);
  3462. return;
  3463. }
  3464. case Drag::erase:
  3465. {
  3466. // right press-and-hold on empty grid, then drag: a temporary Knife
  3467. if (e.mods.isRightButtonDown() && startedOnEmpty && ! erasedSomething && ! holdExpired)
  3468. {
  3469. if (e.getLengthOfMousePress() >= 350)
  3470. {
  3471. drag = Drag::knife;
  3472. knifeFrom = e.getMouseDownPosition();
  3473. knifeTo = e.getPosition();
  3474. repaint();
  3475. return;
  3476. }
  3477. if (e.getDistanceFromDragStart() > 3)
  3478. holdExpired = true; // moved right away: it is an erase stroke
  3479. }
  3480. bool edge = false;
  3481. const auto hit = noteAt (e.x, e.y, edge);
  3482. if (hit >= 0)
  3483. {
  3484. erasedSomething = true;
  3485. fadeOut ({ hit }); // (issue #250)
  3486. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  3487. }
  3488. return;
  3489. }
  3490. case Drag::muting:
  3491. {
  3492. bool edge = false;
  3493. const auto hit = noteAt (e.x, e.y, edge);
  3494. if (hit >= 0 && std::find (touchedNotes.begin(), touchedNotes.end(), hit) == touchedNotes.end())
  3495. {
  3496. touchedNotes.push_back (hit);
  3497. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  3498. }
  3499. return;
  3500. }
  3501. case Drag::knife:
  3502. knifeTo = e.getPosition();
  3503. repaint();
  3504. return;
  3505. case Drag::listen:
  3506. listenAt (e.x);
  3507. return;
  3508. case Drag::seek:
  3509. seekAt (e.x, snapOn);
  3510. rulerMark = juce::jmax<std::int64_t> (0, snapOn ? snap (xToTick (e.x), true) : (std::int64_t) xToTick (e.x));
  3511. return;
  3512. case Drag::drumPaint:
  3513. drumPaintAt (e.getPosition(), snapOn);
  3514. return;
  3515. case Drag::stretch:
  3516. {
  3517. if (dragOriginals.empty() || stretchEnd <= stretchAnchor)
  3518. return;
  3519. // the new end of the selection: on the grid (the nearest line), or free with Alt
  3520. const auto minimum = snapOn ? juce::jmax<std::int64_t> (1, gridTicks()) : (std::int64_t) 10;
  3521. auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  3522. end = juce::jmax (stretchAnchor + minimum, end);
  3523. const auto stretched = polish::stretchNotes (dragOriginals, stretchAnchor, stretchEnd, end);
  3524. editNotes ([this, &stretched] (Pattern& p) {
  3525. for (std::size_t j = 0; j < dragIndices.size() && j < stretched.size(); ++j)
  3526. if ((std::size_t) dragIndices[j] < p.notes.size())
  3527. p.notes[(std::size_t) dragIndices[j]] = stretched[j];
  3528. });
  3529. repaint();
  3530. return;
  3531. }
  3532. case Drag::paint:
  3533. {
  3534. // lays notes to the right, one per default length, at the pitch under the mouse
  3535. const auto tick = snap (xToTick (e.x), snapOn);
  3536. for (int guard = 0; tick >= nextPaintTick && guard < 64; ++guard)
  3537. {
  3538. paintNoteAt (nextPaintTick, snapKey (yToKey (e.y)), noteedit::monophonicPaint (e.mods.isShiftDown(), monophonicPainting));
  3539. nextPaintTick += paintLength;
  3540. }
  3541. if (snapKey (yToKey (e.y)) != previewKey)
  3542. previewEdit (snapKey (yToKey (e.y)), noteTemplate.velocity);
  3543. return;
  3544. }
  3545. case Drag::move:
  3546. {
  3547. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  3548. auto deltaTicks = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset) - grabbed.start;
  3549. auto deltaKeys = snapKey (yToKey (e.y)) - grabbed.key;
  3550. auto rawKeys = yToKey (e.y) - grabbed.key; // (the mouse's own row, before any snap)
  3551. // locks: Shift pressed after the click keeps the pitch, Ctrl keeps the time
  3552. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  3553. deltaKeys = rawKeys = 0;
  3554. if (flmods::ctrl (e.mods) && ! flmods::ctrl (downMods))
  3555. deltaTicks = 0;
  3556. const auto& current = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  3557. // snap to scale (core/ScaleSnap.h, round 190an): the grabbed note follows the mouse onto the scale and the
  3558. // whole group moves that many scale steps; on the note's own row the pitch is left alone, also off the scale
  3559. const auto scale = snapScale();
  3560. const auto onScale = scale.active() && ! folded();
  3561. const auto scaleSteps = onScale ? scalesnap::dragSteps (scale, grabbed.key, grabbed.key + rawKeys) : 0;
  3562. if (current.start == grabbed.start + deltaTicks
  3563. && (onScale ? scaleSteps == lastScaleDragKeys : current.key == grabbed.key + deltaKeys))
  3564. return;
  3565. lastScaleDragKeys = scaleSteps;
  3566. const auto oldKey = current.key;
  3567. // from the original positions: the group keeps its shape even when hitting the limits
  3568. // folded to the scale (round 166d): the notes move by rows (scale degrees), so they stay on shown keys
  3569. const auto deltaRows = folded() ? rowFor (grabbed.key) - rowFor (grabbed.key + deltaKeys) : 0;
  3570. editNotes ([this, &deltaTicks, &deltaKeys, scale, scaleSteps, onScale, deltaRows] (Pattern& p) {
  3571. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3572. p.notes[(std::size_t) dragIndices[j]] = dragOriginals[j];
  3573. if (folded())
  3574. {
  3575. auto noKeys = 0;
  3576. noteedit::move (p, dragIndices, deltaTicks, noKeys);
  3577. if (deltaRows != 0)
  3578. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3579. p.notes[(std::size_t) dragIndices[j]].key = rows.step (dragOriginals[j].key, deltaRows);
  3580. return;
  3581. }
  3582. if (! onScale)
  3583. {
  3584. noteedit::move (p, dragIndices, deltaTicks, deltaKeys);
  3585. return;
  3586. }
  3587. // snap to scale: the time moves as a group, the pitch by scale steps (a chord stays a chord of the scale)
  3588. auto noKeys = 0;
  3589. noteedit::move (p, dragIndices, deltaTicks, noKeys);
  3590. scalesnap::moveBySteps (p, dragIndices, scaleSteps, scale);
  3591. });
  3592. const auto& moved = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  3593. if (moved.key != oldKey)
  3594. previewEdit (moved.key, moved.velocity);
  3595. return;
  3596. }
  3597. case Drag::resize:
  3598. {
  3599. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  3600. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  3601. const auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  3602. const auto delta = juce::jmax (minimum, end - grabbed.start) - grabbed.length;
  3603. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].length == grabbed.length + delta)
  3604. return;
  3605. lastLength = grabbed.length + delta;
  3606. editNotes ([this, delta, minimum] (Pattern& p) {
  3607. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3608. p.notes[(std::size_t) dragIndices[j]].length = juce::jmax (minimum, dragOriginals[j].length + delta);
  3609. });
  3610. return;
  3611. }
  3612. case Drag::resizeLeft:
  3613. {
  3614. // the start moves, the end stays (selected notes together)
  3615. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  3616. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  3617. auto delta = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn)) - grabbed.start;
  3618. for (const auto& o : dragOriginals)
  3619. delta = juce::jlimit (-o.start, o.length - juce::jmin (minimum, o.length), delta);
  3620. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].start == grabbed.start + delta)
  3621. return;
  3622. editNotes ([this, delta] (Pattern& p) {
  3623. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3624. {
  3625. auto& n = p.notes[(std::size_t) dragIndices[j]];
  3626. n.start = dragOriginals[j].start + delta;
  3627. n.length = dragOriginals[j].length - delta;
  3628. }
  3629. });
  3630. lastLength = grabbed.length - delta;
  3631. return;
  3632. }
  3633. }
  3634. }
  3635. void PianoRollComponent::postDragHint (const juce::MouseEvent& e)
  3636. {
  3637. const auto& notes = currentPattern (engine.getSong()).notes;
  3638. const auto count = juce::String ((int) std::max<std::size_t> (1, dragIndices.size()));
  3639. auto steps = [] (std::int64_t ticks) {
  3640. const auto value = (double) ticks / ticksPerStep;
  3641. return (value > 0 ? "+" : "") + juce::String (value, std::abs (value - std::round (value)) < 1e-9 ? 0 : 2);
  3642. };
  3643. ui::Hint hint;
  3644. switch (drag)
  3645. {
  3646. case Drag::move:
  3647. {
  3648. const auto at = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin());
  3649. if (dragNote < 0 || dragNote >= (int) notes.size() || at >= dragOriginals.size())
  3650. return;
  3651. const auto& now = notes[(std::size_t) dragNote];
  3652. const auto& was = dragOriginals[at];
  3653. hint.text = tr ("Moving {0} note(s): then [Shift] keeps the pitch [Ctrl] keeps the time [Alt] no snap", { count });
  3654. hint.value = keyName (now.key) + " " + juce::String (now.key - was.key >= 0 ? "+" : "") + juce::String (now.key - was.key) + " st "
  3655. + steps (now.start - was.start) + " " + tr ("steps");
  3656. break;
  3657. }
  3658. case Drag::resize:
  3659. case Drag::resizeLeft:
  3660. if (dragNote < 0 || dragNote >= (int) notes.size())
  3661. return;
  3662. hint.text = tr ("Resizing {0} note(s) [Alt] no snap", { count });
  3663. hint.value = juce::String ((double) notes[(std::size_t) dragNote].length / ticksPerStep, 2) + " " + tr ("steps");
  3664. break;
  3665. case Drag::eventDraw:
  3666. case Drag::eventErase:
  3667. {
  3668. const auto lane = velocityArea();
  3669. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  3670. hint.text = drag == Drag::eventErase ? tr ("Deleting events") : tr ("Drawing events: {0}", { laneName() });
  3671. const auto target = eventLaneTarget();
  3672. hint.value = target && target->kind == AutomationTargetKind::tempo ? juce::String (tempoFromValue (value), 3) + " BPM" // (issue #86: as FL's hint)
  3673. : juce::String (juce::roundToInt (value * 100.0f)) + "%";
  3674. break;
  3675. }
  3676. case Drag::mpePoint:
  3677. case Drag::mpeDraw:
  3678. case Drag::mpeErase:
  3679. {
  3680. juce::Rectangle<int> area;
  3681. const auto id = mpeDragLane;
  3682. mpeLaneAt ({ lastMpeX, lastMpeY }, &area);
  3683. hint.text = drag == Drag::mpeErase ? tr ("Erasing the curve's points") : drag == Drag::mpePoint ? tr ("Moving the curve's point")
  3684. : tr ("Drawing the note's curve");
  3685. if (drag != Drag::mpeErase && ! area.isEmpty())
  3686. {
  3687. const auto norm = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - 2 - lastMpeY) / (float) juce::jmax (1, area.getHeight() - 8));
  3688. const auto v = mpeValue (id, norm, mpeDragRange);
  3689. hint.value = id == laneMpePitch ? tr ("{0} st", { juce::String (v / 100.0f, 2) })
  3690. : juce::String (juce::roundToInt (id == laneMpeSlide ? (float) mpe::timbreOfModX (v) : v * 127.0f));
  3691. }
  3692. break;
  3693. }
  3694. case Drag::mpeBend: // round 190jd: Live's tooltip on a pitch point ("0 st")
  3695. {
  3696. const auto& notes = currentPattern (engine.getSong()).notes;
  3697. hint.text = tr ("Bending the note's pitch [Shift] fine");
  3698. if (mpeDragNote >= 0 && mpeDragNote < (int) notes.size() && notes[(std::size_t) mpeDragNote].curves.has())
  3699. {
  3700. const auto& points = notes[(std::size_t) mpeDragNote].curves->lane (NoteCurveLane::pitch);
  3701. if (mpeDragPoint >= 0 && mpeDragPoint < (int) points.size())
  3702. {
  3703. const auto st = points[(std::size_t) mpeDragPoint].value / 100.0f;
  3704. hint.value = tr ("{0} st", { std::abs (st - std::round (st)) < 0.001f ? juce::String (juce::roundToInt (st)) : juce::String (st, 2) });
  3705. }
  3706. }
  3707. break;
  3708. }
  3709. case Drag::mpeValue:
  3710. {
  3711. const auto& notes = currentPattern (engine.getSong()).notes;
  3712. hint.text = tr ("Setting {0}", { mpeDragLane == laneRelease ? tr ("Release Velocity") : tr ("Velocity") });
  3713. if (mpeDragNote >= 0 && mpeDragNote < (int) notes.size())
  3714. hint.value = juce::String (juce::roundToInt (mpeValueLaneValue (mpeDragLane, notes[(std::size_t) mpeDragNote]) * 127.0f));
  3715. break;
  3716. }
  3717. case Drag::velocity:
  3718. case Drag::velocitySet:
  3719. case Drag::velocityLine:
  3720. {
  3721. const auto lane = velocityArea();
  3722. const auto value = drag == Drag::velocitySet ? laneSetValue
  3723. : juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  3724. hint.text = tr ("Setting {0}", { laneName() });
  3725. hint.value = laneValueText (value);
  3726. if (hint.value.isEmpty())
  3727. hint.value = juce::String (juce::roundToInt (value * 100.0f)) + "%";
  3728. break;
  3729. }
  3730. case Drag::select:
  3731. case Drag::keySelect:
  3732. case Drag::rulerSelect:
  3733. hint.text = tr ("Selecting [Shift] adds to the selection");
  3734. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  3735. break;
  3736. case Drag::erase: hint.text = tr ("Deleting what the mouse crosses"); break;
  3737. case Drag::muting: hint.text = tr ("Muting / unmuting what the mouse crosses"); break;
  3738. case Drag::knife: hint.text = tr ("Cutting along the line [Alt] no snap"); break;
  3739. case Drag::paint: hint.text = tr ("Painting notes [Alt] no snap"); break;
  3740. case Drag::drumPaint: hint.text = tr ("Drum brush: one hit per grid cell, on the key under the mouse [Alt] no snap"); break;
  3741. case Drag::stretch:
  3742. {
  3743. std::int64_t from = 0, to = 0;
  3744. std::vector<Note> now;
  3745. for (auto i : dragIndices)
  3746. if (i >= 0 && i < (int) notes.size())
  3747. now.push_back (notes[(std::size_t) i]);
  3748. noteedit::span (now, from, to);
  3749. hint.text = tr ("Stretching {0} note(s) in time [Alt] no snap", { count });
  3750. hint.value = "x" + juce::String ((double) (to - stretchAnchor) / (double) juce::jmax<std::int64_t> (1, stretchEnd - stretchAnchor), 2);
  3751. break;
  3752. }
  3753. case Drag::keyZoom: hint.text = tr ("Key height"); hint.value = tr ("Zoom level {0}", { juce::String (gesture::zoomLevel (rowHeight)) }) + " " + juce::String (rowHeight) + " px"; break;
  3754. case Drag::timeZoom: hint.text = tr ("Zooming: drag up = closer, sideways = scroll [Ctrl] zoom only"); break;
  3755. case Drag::keyboard:
  3756. hint.text = tr ("Hearing the key: further right on a key = louder");
  3757. hint.value = keyName (previewKey) + " " + tr ("vel {0}", { juce::String (juce::roundToInt (keyVelocityAt (e.x, previewKey) * 127.0f)) });
  3758. break;
  3759. case Drag::pan:
  3760. case Drag::seek: hint.text = tr ("Position [Alt] no snap"); break;
  3761. case Drag::listen:
  3762. case Drag::zoomRange:
  3763. case Drag::eventPaneBar: // (eventPaneChanged posts the percentage)
  3764. case Drag::eventPaneAlternate:
  3765. case Drag::none: return;
  3766. }
  3767. ui::postHint (hint);
  3768. }
  3769. void PianoRollComponent::mouseUp (const juce::MouseEvent& e)
  3770. {
  3771. if (touchInput.mouseUp (e)) // round 190pm (P23)
  3772. return;
  3773. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::end); // (closes when mouseUp returns)
  3774. // round 190qe: the release ends the edge scroll; a click that replaced or cleared the selection leaves the old one
  3775. // for "Restore selection" (D2-PL9)
  3776. edgeScroller.stop();
  3777. edgeDragEvent.reset();
  3778. struct RememberSelection
  3779. {
  3780. PianoRollComponent& p;
  3781. ~RememberSelection()
  3782. {
  3783. if (p.engine.getPublishCount() == p.followEditStamp) // (a click that only selected: an edit keeps its selection)
  3784. p.selectionHistory.changed (p.selectionAtPress, p.noteKeys (p.selection));
  3785. }
  3786. } const rememberSelection { *this };
  3787. if (boundaryDrag >= 0) // round 190on (P10): the heights are kept
  3788. {
  3789. boundaryDrag = -1;
  3790. saveStackedLanes();
  3791. return;
  3792. }
  3793. hold = Hold::none; // (round 190mr: a pending click-and-hold ends with the press)
  3794. ++holdSerial;
  3795. if (std::exchange (holdRing, false))
  3796. repaint (holdRingArea());
  3797. EditorGlobals::get().pauseFollowIfEdited (EditorGlobals::FollowView::pianoRoll, followEditStamp, engine.getPublishCount()); // (round 190im, R15)
  3798. ui::clearPostedHint();
  3799. if (drag == Drag::eventPaneBar) // round 190fz: remembered once the drag ends
  3800. saveEventPaneState();
  3801. if (drag == Drag::eventPaneAlternate)
  3802. {
  3803. drag = Drag::none;
  3804. toggleEventPaneAlternate();
  3805. }
  3806. if (drag == Drag::knife)
  3807. cutWithKnife (knifeFrom, knifeTo, ! e.mods.isAltDown());
  3808. if (drag == Drag::zoomRange)
  3809. {
  3810. if (rubberBand.getWidth() > 4)
  3811. zoomToTicks (xToTick (rubberBand.getX()), xToTick (rubberBand.getRight()));
  3812. else
  3813. zoomIn (e.x); // a click zooms in around the point (right-click zooms out)
  3814. }
  3815. if (drag == Drag::select && rubberBand.isEmpty() && dragNote >= 0)
  3816. {
  3817. // Lasso click on a note: selects it (Shift: adds / removes)
  3818. auto s = selectionBefore;
  3819. if (auto it = std::find (s.begin(), s.end(), dragNote); it != s.end())
  3820. s.erase (it);
  3821. else
  3822. s.push_back (dragNote);
  3823. setSelection (s);
  3824. }
  3825. // issue #213 (round 190mq): a double click (or a Ctrl+click) on the ruler released in place clears the time
  3826. // selection, as the Playlist's ruler does; FL 2026 also deselects the notes (capture f30 / f31) and drops the paste
  3827. // anchor (issue #211)
  3828. if (drag == Drag::rulerSelect && downMods.isLeftButtonDown() && e.getDistanceFromDragStart() < 3)
  3829. {
  3830. setTimeSelection (-1, -1);
  3831. rulerMark = -1;
  3832. if (! downMods.isShiftDown())
  3833. setSelection ({});
  3834. }
  3835. if (drag == Drag::listen)
  3836. stopListening();
  3837. if (drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft || drag == Drag::paint || drag == Drag::drumPaint
  3838. || drag == Drag::stretch)
  3839. sortNotes();
  3840. previewOff();
  3841. drag = Drag::none;
  3842. dragNote = -1;
  3843. dragIndices.clear();
  3844. dragOriginals.clear();
  3845. touchedNotes.clear();
  3846. laneOriginals.clear();
  3847. rubberBand = {};
  3848. hover = {};
  3849. heldLane = -1; // (round 190on: the gesture's stacked lane ends with it)
  3850. enterLane (-1);
  3851. updateHover (e.getPosition(), e.mods); // the cursor of what is under the mouse now
  3852. repaint();
  3853. }
  3854. void PianoRollComponent::mouseMove (const juce::MouseEvent& e)
  3855. {
  3856. if (const auto over = zoomWheelArea().contains (e.getPosition()); over != zoomWheelHover)
  3857. {
  3858. zoomWheelHover = over;
  3859. repaint (zoomWheelArea());
  3860. }
  3861. if (mpeStacked) // round 190jd: the value ghost point on a lane's line
  3862. updateMpeGhost (e.getPosition());
  3863. updateHover (e.getPosition(), e.mods);
  3864. updateDegreeGhost (e.getPosition()); // (round 190nu: nothing unless the Scale degree chord is the stamp)
  3865. feedMagicLasso (e.getPosition(), false); // (round 190mp, DE-71: nothing while the option is off)
  3866. if (const auto inLane = velocityArea().contains (e.getPosition()); liveNotes() && inLane != liveLaneHover) // (round 190mf, DL-80)
  3867. {
  3868. liveLaneHover = inLane;
  3869. repaint (0, velocityArea().getY(), getWidth(), velocityArea().getHeight());
  3870. }
  3871. if (laneBoundaryAt (e.getPosition()) >= 0) // round 190on (P10): the line between two stacked lanes
  3872. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  3873. }
  3874. void PianoRollComponent::mouseExit (const juce::MouseEvent&)
  3875. {
  3876. lastMouse = { -1, -1 };
  3877. if (std::exchange (zoomWheelHover, false))
  3878. repaint (zoomWheelArea());
  3879. if (mpeGhost.x >= 0.0f)
  3880. updateMpeGhost ({ -1, -1 });
  3881. clearDegreeGhost();
  3882. if (! (hover == Hover {}))
  3883. {
  3884. hover = {};
  3885. repaint();
  3886. }
  3887. }
  3888. void PianoRollComponent::modifierKeysChanged (const juce::ModifierKeys& mods)
  3889. {
  3890. // Ctrl / Shift / Alt change what a click would do: the cursor follows without moving the mouse
  3891. if (drag == Drag::none && lastMouse.x >= 0)
  3892. updateCursor (mods);
  3893. }
  3894. PianoRollComponent::Hover PianoRollComponent::hoverAt (juce::Point<int> p) const
  3895. {
  3896. Hover h;
  3897. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  3898. {
  3899. h.key = keyboardKeyAt (p.x, p.y);
  3900. return h;
  3901. }
  3902. if (velocityArea().contains (p))
  3903. {
  3904. // the stem nearest to the mouse (within a few pixels)
  3905. const auto& notes = currentPattern (engine.getSong()).notes;
  3906. auto best = 5.0;
  3907. for (auto i : channelNotes())
  3908. if (const auto d = std::abs (tickToX ((double) notes[(std::size_t) i].start) - p.x); d < best)
  3909. {
  3910. best = d;
  3911. h.note = i;
  3912. }
  3913. return h;
  3914. }
  3915. if (! gridArea().contains (p))
  3916. return h;
  3917. h.key = yToKey (p.y);
  3918. if (stretchHandle().expanded (2.0f).contains (p.toFloat()))
  3919. {
  3920. h.stretch = true;
  3921. return h;
  3922. }
  3923. const auto& notes = currentPattern (engine.getSong()).notes;
  3924. gesture::EdgeRules rules;
  3925. rules.allowLeft = resizeFromLeft;
  3926. // back to front: the note drawn on top wins
  3927. for (int i = (int) notes.size() - 1; i >= 0; --i)
  3928. {
  3929. const auto& n = notes[(std::size_t) i];
  3930. if (! edits (n) || n.key != h.key)
  3931. continue;
  3932. if (const auto zone = gesture::zoneAt (p.x, tickToX ((double) n.start), tickToX ((double) (n.start + n.length)), rules);
  3933. zone != gesture::Zone::outside)
  3934. {
  3935. h.note = i;
  3936. h.zone = zone;
  3937. return h;
  3938. }
  3939. }
  3940. h.ghost = ghostAt (p.x, p.y);
  3941. return h;
  3942. }
  3943. gesture::Target PianoRollComponent::targetAt (const Hover& h) const
  3944. {
  3945. return h.note >= 0 ? gesture::targetFor (h.zone) : gesture::Target::empty;
  3946. }
  3947. void PianoRollComponent::updateHover (juce::Point<int> p, juce::ModifierKeys mods)
  3948. {
  3949. const LaneScope laneScope (*this, heldLane >= 0 ? heldLane : stackedLaneAt (p)); // (round 190on: the stacked lane under the mouse)
  3950. lastMouse = p;
  3951. const auto h = hoverAt (p);
  3952. if (! (h == hover))
  3953. {
  3954. // repaint only what changed: the old and new note rows, the keyboard, the lane
  3955. auto dirty = [this] (const Hover& o) {
  3956. if (o.key >= 0)
  3957. repaint (0, keyToY (o.key) - 1, getWidth(), rowHeight + 2);
  3958. const auto& notes = currentPattern (engine.getSong()).notes;
  3959. for (auto i : { o.note, o.ghost })
  3960. if (i >= 0 && i < (int) notes.size())
  3961. {
  3962. repaint (0, keyToY (notes[(std::size_t) i].key) - 1, getWidth(), rowHeight + 2);
  3963. repaint (velocityArea());
  3964. }
  3965. };
  3966. dirty (hover);
  3967. hover = h;
  3968. dirty (hover);
  3969. }
  3970. if (drag == Drag::none)
  3971. updateCursor (mods);
  3972. }
  3973. void PianoRollComponent::updateCursor (juce::ModifierKeys mods)
  3974. {
  3975. const auto p = lastMouse;
  3976. auto cursor = gesture::Cursor::normal;
  3977. if (eventPaneBarArea().contains (p)) // the event editor's divider (FL: crVSplit)
  3978. {
  3979. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  3980. return;
  3981. }
  3982. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  3983. cursor = flmods::ctrl (mods) ? gesture::Cursor::select : gesture::Cursor::point;
  3984. else if (velocityArea().contains (p))
  3985. cursor = mpeStacked && ! drawmode::isOn() ? gesture::Cursor::point : gesture::Cursor::draw; // (round 190jd: Live's pointer)
  3986. else if (gridArea().contains (p) && hover.stretch && ! flmods::ctrl (mods))
  3987. cursor = gesture::Cursor::resizeH;
  3988. else if (gridArea().contains (p) && editGhosts && hover.note < 0 && hover.ghost >= 0 && ! flmods::ctrl (mods))
  3989. cursor = gesture::Cursor::move;
  3990. else if (gridArea().contains (p))
  3991. {
  3992. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  3993. const auto tool = tools.getTool();
  3994. cursor = gesture::cursorFor (gesture::leftAction (tool, targetAt (hover), m, false), tool);
  3995. }
  3996. else if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth && flmods::ctrl (mods))
  3997. cursor = gesture::Cursor::select;
  3998. else if (zoomWheelArea().contains (p))
  3999. cursor = gesture::Cursor::resizeV; // (FL: crSizeNS)
  4000. setMouseCursor (editorCursor (cursor));
  4001. }
  4002. ui::Hint PianoRollComponent::hintAt (juce::Point<int> p)
  4003. {
  4004. ui::Hint hint;
  4005. const auto mods = juce::ModifierKeys::currentModifiers;
  4006. const auto& song = engine.getSong();
  4007. const auto& notes = currentPattern (song).notes;
  4008. if (zoomWheelArea().contains (p))
  4009. {
  4010. hint.text = tr ("Key height: drag up / down or turn the wheel [Ctrl] fine");
  4011. hint.value = tr ("Zoom level {0}", { juce::String (gesture::zoomLevel (rowHeight)) });
  4012. return hint;
  4013. }
  4014. if (eventPaneBarArea().contains (p)) // round 190fz: FL's hint is "Right-click / shift+enter for alternate size"
  4015. {
  4016. hint.text = tr ("Event editor size: drag [RMB] or [Shift][Enter] alternate size [MMB] default size");
  4017. hint.value = juce::String (evpane::percentOf (eventPaneState().aspect)) + "%";
  4018. return hint;
  4019. }
  4020. const auto h = hoverAt (p);
  4021. auto noteValue = [&] (int i) {
  4022. const auto& n = notes[(std::size_t) i];
  4023. return keyName (n.key) + " " + juce::String (juce::roundToInt (n.velocity * 100.0f)) + "%";
  4024. };
  4025. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  4026. {
  4027. hint.text = tr ("Keyboard: [LMB] hear the key (further right = louder) [Ctrl][LMB] select its notes [MMB] drag: taller / shorter keys");
  4028. hint.value = keyName (h.key) + " " + tr ("vel {0}", { juce::String (juce::roundToInt (keyVelocityAt (p.x, h.key) * 127.0f)) });
  4029. return hint;
  4030. }
  4031. if (mpeStacked && p.x < keyboardWidth && mpeFooterArea().contains (p))
  4032. {
  4033. hint.text = tr ("Show Lane:") + " " + tr ("Slide") + ", " + tr ("Pressure") + ", " + tr ("Velocity") + ", " + tr ("Release Velocity");
  4034. return hint;
  4035. }
  4036. if (mpeStacked && velocityArea().contains (p) && ! isMpeLane (mpeLaneAt (p)))
  4037. {
  4038. hint.text = tr ("{0} lane: [LMB] drag sets the note under the mouse", { mpeLaneAt (p) == laneRelease ? tr ("Release Velocity") : tr ("Velocity") });
  4039. if (const auto note = mpeNoteAt (p.x); note >= 0)
  4040. hint.value = noteValue (note);
  4041. return hint;
  4042. }
  4043. if (mpeStacked && velocityArea().contains (p) && mpeLaneAt (p) != 0) // round 190jd: Live 12.4's MPE tab gestures
  4044. {
  4045. hint.text = drawmode::isOn() ? tr ("MPE curve of the note, Draw Mode: [LMB] drag draws [B] Draw Mode off [RMB] drag erases [Alt][LMB] clear")
  4046. : tr ("MPE curve of the note: click the line: add a point drag a point: move it double-click a point: delete it [B] Draw Mode [RMB] drag erases");
  4047. if (mpeGhost.x >= 0.0f)
  4048. hint.value = mpeGhostText;
  4049. else if (const auto note = mpeNoteAt (p.x); note >= 0)
  4050. hint.value = noteValue (note);
  4051. return hint;
  4052. }
  4053. if (velocityArea().contains (p) && mpeLaneAt (p) != 0)
  4054. {
  4055. hint.text = tr ("MPE curve of the note: [LMB] drag draws drag a point: move it double-click a point: delete it [RMB] drag erases [Alt][LMB] clear");
  4056. if (const auto note = mpeNoteAt (p.x); note >= 0)
  4057. hint.value = noteValue (note);
  4058. return hint;
  4059. }
  4060. if (velocityArea().contains (p))
  4061. {
  4062. 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",
  4063. { laneName() });
  4064. if (h.note >= 0)
  4065. hint.value = noteValue (h.note);
  4066. return hint;
  4067. }
  4068. if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth)
  4069. {
  4070. hint.text = tr ("Ruler: [LMB] position [Alt] no snap [Ctrl][LMB], [RMB] or [2xLMB] drag selects the notes in a time range [Ctrl][Wheel] or a pinch: zoom [Shift][Wheel] scroll");
  4071. return hint;
  4072. }
  4073. if (! gridArea().contains (p))
  4074. return hint;
  4075. if (h.stretch)
  4076. {
  4077. hint.text = tr ("Stretch handle: [LMB] drag stretches or squeezes the selected notes in time (from the selection's start) [Alt] no snap");
  4078. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  4079. return hint;
  4080. }
  4081. if (h.note < 0 && h.ghost >= 0)
  4082. {
  4083. const auto ghostChannel = notes[(std::size_t) h.ghost].channel;
  4084. const auto name = ghostChannel >= 0 && ghostChannel < (int) song.channels.size()
  4085. ? juce::String::fromUTF8 (song.channels[(std::size_t) ghostChannel].name.c_str())
  4086. : juce::String();
  4087. hint.text = editGhosts ? tr ("Ghost note of {0} (editable): [LMB] edit it (switches to {0}) [RMB] deletes it [Ctrl][Alt][V] read-only ghosts",
  4088. { name })
  4089. : tr ("Ghost note of {0}: double [RMB] edits that channel [Alt][V] hides ghost notes [Ctrl][Alt][V] makes them editable",
  4090. { name });
  4091. hint.value = keyName (notes[(std::size_t) h.ghost].key);
  4092. return hint;
  4093. }
  4094. if (mpeStacked && (mpePitchPointAt (p).first >= 0 || (h.note >= 0 && isSelected (h.note)))) // round 190jd: Live's pitch on the notes
  4095. {
  4096. hint.text = tr ("Pitch on the note: [LMB] click adds a pitch point drag a point: bend in semitones [Shift] fine double-click a point: delete it");
  4097. hint.value = h.note >= 0 ? noteValue (h.note) : keyName (h.key);
  4098. return hint;
  4099. }
  4100. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  4101. hint.text = actionHint (gesture::leftAction (tools.getTool(), targetAt (h), m, false), false);
  4102. hint.value = h.note >= 0 ? noteValue (h.note) : keyName (h.key);
  4103. return hint;
  4104. }
  4105. void PianoRollComponent::mouseDoubleClick (const juce::MouseEvent& e)
  4106. {
  4107. const LaneScope laneScope (*this, stackedLaneAt (e.getPosition())); // (round 190on)
  4108. if (velocityArea().contains (e.getPosition()) && mpeDoubleClick (e))
  4109. return;
  4110. if (mpeStacked && gridArea().contains (e.getPosition()) && mpePitchDoubleClick (e)) // round 190jd
  4111. return;
  4112. if (! gridArea().contains (e.getPosition()) || e.mods.isRightButtonDown() || flmods::ctrl (e.mods))
  4113. return;
  4114. // the first click of this double click created the note: that was drawing, not opening it
  4115. if (juce::Time::getMillisecondCounter() - createdAt < 800)
  4116. return;
  4117. bool edge = false;
  4118. const auto hit = noteAt (e.x, e.y, edge);
  4119. if (hit < 0)
  4120. return;
  4121. const auto indices = isSelected (hit) ? selection : std::vector<int> { hit };
  4122. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) hit];
  4123. const auto area = juce::Rectangle<int> ((int) tickToX ((double) n.start), keyToY (n.key), juce::jmax (8, (int) (n.length * pixelsPerTick)), rowHeight);
  4124. showNoteInspector (engine, indices, hit, localAreaToGlobal (area));
  4125. }
  4126. std::unique_ptr<juce::Component> PianoRollComponent::makeNoteInspectorForSnapshot (bool singleNote)
  4127. {
  4128. if (selection.empty())
  4129. selectAll();
  4130. if (selection.empty())
  4131. return nullptr;
  4132. return makeNoteInspector (engine, singleNote ? std::vector<int> { selection.front() } : selection, selection.front());
  4133. }
  4134. int PianoRollComponent::liveVelocityHoverForSnapshot (bool dragging)
  4135. {
  4136. setDocked (true);
  4137. velocityHeight = defaultVelocityHeight; // (the lane enlarged by its divider, as in capture 190mf B2)
  4138. liveNoteColour = juce::Colour (0xff3fb7c9);
  4139. rowHeight = 18;
  4140. pixelsPerTick = 64.0 / ticksPerStep;
  4141. resized();
  4142. scrollToNotes (false);
  4143. const auto notes = channelNotes();
  4144. if (notes.empty())
  4145. return -1;
  4146. const auto pick = notes[juce::jmin ((std::size_t) 1, notes.size() - 1)]; // (the second note: clear of the lane's left edge)
  4147. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) pick];
  4148. const auto lane = velocityArea();
  4149. const auto at = juce::Point<int> ((int) tickToX ((double) n.start), lane.getBottom() - 2 - juce::roundToInt ((float) (lane.getHeight() - 8) * n.velocity));
  4150. lastMouse = at;
  4151. updateHover (at, {});
  4152. if (dragging)
  4153. {
  4154. selection = { pick };
  4155. drag = Drag::velocity;
  4156. }
  4157. repaint();
  4158. return juce::roundToInt (n.velocity * 127.0f);
  4159. }
  4160. ui::Hint PianoRollComponent::hoverForSnapshot()
  4161. {
  4162. rowHeight = 18;
  4163. pixelsPerTick = 64.0 / ticksPerStep;
  4164. scrollToNotes (false);
  4165. const auto notes = channelNotes();
  4166. if (notes.empty())
  4167. return {};
  4168. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) notes.front()];
  4169. const auto at = juce::Point<int> ((int) tickToX ((double) (n.start + n.length)) - 2, keyToY (n.key) + rowHeight / 2);
  4170. updateHover (at, {});
  4171. return hintAt (at);
  4172. }
  4173. // --- tools ---------------------------------------------------------------------------
  4174. void PianoRollComponent::cutWithKnife (juce::Point<int> from, juce::Point<int> to, bool snapOn)
  4175. {
  4176. const auto& notes = currentPattern (engine.getSong()).notes;
  4177. std::vector<std::pair<int, std::int64_t>> cuts;
  4178. if (from.getDistanceFrom (to) < 3)
  4179. {
  4180. // a click: cuts the note under the cursor
  4181. bool edge = false;
  4182. if (const auto hit = noteAt (from.x, from.y, edge); hit >= 0)
  4183. cuts.push_back ({ hit, snap (xToTick (from.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn) });
  4184. }
  4185. else
  4186. {
  4187. // a line: every note row it crosses is cut where the line passes
  4188. const auto top = juce::jmin (from.y, to.y), bottom = juce::jmax (from.y, to.y);
  4189. for (int i = 0; i < (int) notes.size(); ++i)
  4190. {
  4191. const auto& n = notes[(std::size_t) i];
  4192. if (! edits (n))
  4193. continue;
  4194. const auto rowY = keyToY (n.key) + rowHeight / 2;
  4195. if (rowY < top - rowHeight / 2 || rowY > bottom + rowHeight / 2)
  4196. continue;
  4197. const auto y = juce::jlimit (top, bottom, rowY);
  4198. 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);
  4199. const auto tick = snap (xToTick ((int) std::round (x)) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn);
  4200. if (tick > n.start && tick < n.start + n.length)
  4201. cuts.push_back ({ i, tick });
  4202. }
  4203. }
  4204. if (cuts.empty())
  4205. return;
  4206. setSelection ({});
  4207. editNotes ([&cuts] (Pattern& p) {
  4208. for (auto [index, tick] : cuts)
  4209. noteedit::split (p, index, tick);
  4210. });
  4211. sortNotes();
  4212. }
  4213. void PianoRollComponent::zoomToTicks (double from, double to)
  4214. {
  4215. if (to - from < 1.0)
  4216. return;
  4217. // (round 190qe, UX-A3: glides with Animations on)
  4218. settleViewGlide();
  4219. auto target = currentView();
  4220. target.pixelsPerUnit = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, gridArea().getWidth() / (to - from));
  4221. target.scroll = juce::jmax (0.0, from);
  4222. showView (clampedView (target));
  4223. }
  4224. void PianoRollComponent::zoomIn (int anchorX)
  4225. {
  4226. const auto anchor = xToTick (anchorX);
  4227. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, pixelsPerTick * 2.0);
  4228. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  4229. updateScrollBars();
  4230. repaint();
  4231. }
  4232. void PianoRollComponent::zoomOut (int anchorX)
  4233. {
  4234. const auto anchor = xToTick (anchorX);
  4235. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, pixelsPerTick / 2.0);
  4236. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  4237. updateScrollBars();
  4238. repaint();
  4239. }
  4240. void PianoRollComponent::seekAt (int x, bool snapOn)
  4241. {
  4242. const auto& song = engine.getSong();
  4243. const auto tick = snapOn ? (double) snap (xToTick (x), true) : xToTick (x);
  4244. const auto target = transportedit::patternSeekTarget (song, song.currentPattern, tick, engine.getTransport().positionTicks.load());
  4245. if (target < 0.0)
  4246. {
  4247. // Song mode and no clip of this pattern: play the pattern on its own from there
  4248. engine.editSong ([] (Song& s) { s.mode = PlayMode::pattern; }, false);
  4249. engine.seek (juce::jmax (0.0, tick));
  4250. EditorGlobals::get().markSeek ((std::int64_t) juce::jmax (0.0, tick), false); // FL: Stop goes back here (issue #169)
  4251. return;
  4252. }
  4253. engine.seek (target);
  4254. EditorGlobals::get().markSeek ((std::int64_t) target, song.mode == PlayMode::song);
  4255. }
  4256. void PianoRollComponent::listenAt (int x)
  4257. {
  4258. // plays the channel's notes that sound at the tick under the mouse
  4259. const auto tick = (std::int64_t) xToTick (x);
  4260. const auto& notes = currentPattern (engine.getSong()).notes;
  4261. const auto channel = engine.getSelectedChannel();
  4262. std::vector<int> keys;
  4263. std::vector<float> velocities;
  4264. for (const auto& n : notes)
  4265. if (n.channel == channel && ! n.muted && n.start <= tick && n.start + n.length > tick
  4266. && std::find (keys.begin(), keys.end(), n.key) == keys.end())
  4267. {
  4268. keys.push_back (n.key);
  4269. velocities.push_back (n.velocity);
  4270. }
  4271. for (auto k : listenKeys)
  4272. if (std::find (keys.begin(), keys.end(), k) == keys.end())
  4273. listenNotes.release (listenChannel, k);
  4274. if (channel != listenChannel)
  4275. listenNotes.releaseAll();
  4276. for (std::size_t i = 0; i < keys.size(); ++i)
  4277. if (! listenNotes.isHeld (channel, keys[i]))
  4278. listenNotes.press (channel, keys[i], velocities[i]);
  4279. listenKeys = keys;
  4280. listenChannel = channel;
  4281. }
  4282. void PianoRollComponent::stopListening()
  4283. {
  4284. listenNotes.releaseAll();
  4285. listenKeys.clear();
  4286. }
  4287. void PianoRollComponent::refreshChannelBox()
  4288. {
  4289. const auto& song = engine.getSong();
  4290. std::vector<bool> hasNotes (song.channels.size(), false);
  4291. for (const auto& n : currentPattern (song).notes)
  4292. if (n.channel >= 0 && n.channel < (int) hasNotes.size())
  4293. hasNotes[(std::size_t) n.channel] = true;
  4294. juce::StringArray names;
  4295. names.add (tr ("All")); // (issue #12: every channel's notes; drawn bold)
  4296. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4297. names.add ((hasNotes[c] ? juce::String::fromUTF8 ("\xe2\x97\x8f ") : juce::String (" ")) + juce::String::fromUTF8 (song.channels[c].name.c_str()));
  4298. // only rebuilds when something changed (rebuilding closes an open menu)
  4299. bool same = channelBox.getNumItems() == names.size();
  4300. for (int i = 0; same && i < names.size(); ++i)
  4301. same = channelBox.getItemText (i) == names[i];
  4302. if (! same)
  4303. {
  4304. // the bold "All" at the top, as a custom item (a ComboBox item has no font of its own)
  4305. struct BoldItem final : juce::PopupMenu::CustomComponent
  4306. {
  4307. explicit BoldItem (juce::String t) : text (std::move (t)) {}
  4308. void getIdealSize (int& w, int& h) override
  4309. {
  4310. w = 160;
  4311. h = 24;
  4312. }
  4313. void paint (juce::Graphics& g) override
  4314. {
  4315. if (isItemHighlighted())
  4316. {
  4317. g.setColour (theme::colour::accent.withAlpha (0.35f));
  4318. g.fillRect (getLocalBounds());
  4319. }
  4320. g.setColour (theme::colour::textPrimary);
  4321. g.setFont (theme::font (theme::type::body, true));
  4322. g.drawText (text, getLocalBounds().withTrimmedLeft (12), juce::Justification::centredLeft, true);
  4323. }
  4324. juce::String text;
  4325. };
  4326. channelBox.clear (juce::dontSendNotification);
  4327. juce::PopupMenu::Item all (names[0]);
  4328. all.itemID = allChannelsId;
  4329. all.customComponent = new BoldItem (names[0]);
  4330. channelBox.getRootMenu()->addItem (std::move (all));
  4331. channelBox.getRootMenu()->addSeparator();
  4332. for (int i = 1; i < names.size(); ++i)
  4333. channelBox.addItem (names[i], i);
  4334. }
  4335. channelBox.setSelectedId (allChannels ? allChannelsId : engine.getSelectedChannel() + 1, juce::dontSendNotification);
  4336. }
  4337. void PianoRollComponent::setAllChannels (bool on)
  4338. {
  4339. if (allChannels == on)
  4340. return;
  4341. allChannels = on;
  4342. selection.clear();
  4343. stopListening();
  4344. refreshChannelBox();
  4345. repaint();
  4346. }
  4347. void PianoRollComponent::stepChannel (int direction, bool withNotesOnly)
  4348. {
  4349. const auto& song = engine.getSong();
  4350. const auto count = (int) song.channels.size();
  4351. if (count == 0)
  4352. return;
  4353. std::vector<bool> hasNotes ((std::size_t) count, false);
  4354. for (const auto& n : currentPattern (song).notes)
  4355. if (n.channel >= 0 && n.channel < count)
  4356. hasNotes[(std::size_t) n.channel] = true;
  4357. auto channel = engine.getSelectedChannel();
  4358. for (int step = 0; step < count; ++step)
  4359. {
  4360. channel += direction;
  4361. if (channel < 0 || channel >= count)
  4362. return; // stops at the ends
  4363. if (! withNotesOnly || hasNotes[(std::size_t) channel])
  4364. {
  4365. engine.setSelectedChannel (channel);
  4366. return;
  4367. }
  4368. }
  4369. }
  4370. void PianoRollComponent::runOperation (const std::function<std::vector<int> (Pattern&, const std::vector<int>&)>& op)
  4371. {
  4372. const auto target = selectionOrAll();
  4373. if (target.empty())
  4374. return;
  4375. const auto hadSelection = ! selection.empty();
  4376. std::vector<int> result;
  4377. editNotes ([&] (Pattern& p) { result = op (p, target); });
  4378. setSelection (hadSelection ? result : std::vector<int> {});
  4379. sortNotes();
  4380. }
  4381. // Round 190pm (research190oe P19): ratchets and Conditions for the selected notes (all when none is selected), the Fill
  4382. // switch and the lanes; LYNX additions next to Chance
  4383. juce::PopupMenu PianoRollComponent::repeatsMenu()
  4384. {
  4385. juce::PopupMenu menu;
  4386. const auto& notes = currentPattern (engine.getSong()).notes;
  4387. const auto target = selectionOrAll();
  4388. const auto all = [&] (const std::function<bool (const Note&)>& test) {
  4389. return ! target.empty() && std::all_of (target.begin(), target.end(), [&] (int i) { return i >= 0 && i < (int) notes.size() && test (notes[(std::size_t) i]); });
  4390. };
  4391. const auto setAll = [this] (std::function<void (Note&)> change) {
  4392. runOperation ([change] (Pattern& p, const std::vector<int>& t) {
  4393. for (auto i : t)
  4394. if (i >= 0 && i < (int) p.notes.size())
  4395. change (p.notes[(std::size_t) i]);
  4396. return t;
  4397. });
  4398. };
  4399. juce::PopupMenu ratchets;
  4400. ratchets.addItem (tr ("No ratchets"), true, all ([] (const Note& n) { return ! n.hasRatchets(); }), [setAll] { setAll ([] (Note& n) { n.ratchets = 0; }); });
  4401. for (int count = 2; count <= noterepeat::maxRatchets; ++count)
  4402. ratchets.addItem (tr ("{0} strikes", { juce::String (count) }), true, all ([count] (const Note& n) { return n.ratchets == count; }),
  4403. [setAll, count] { setAll ([count] (Note& n) { n.ratchets = count; }); });
  4404. ratchets.addSeparator();
  4405. for (const auto& [name, bend] : { std::pair { TR_NOOP ("Even velocity"), 0.0f }, { TR_NOOP ("Fade out (to 30%)"), -0.7f },
  4406. { TR_NOOP ("Fade in (from 50%)"), 1.0f } })
  4407. {
  4408. const auto b = bend;
  4409. ratchets.addItem (tr (name), true, all ([b] (const Note& n) { return n.ratchetVelocity == b; }), [setAll, b] { setAll ([b] (Note& n) { n.ratchetVelocity = b; }); });
  4410. }
  4411. menu.addSubMenu (tr ("Ratchets"), ratchets);
  4412. juce::PopupMenu condition;
  4413. for (int c = notecondition::always; c < notecondition::count; ++c)
  4414. condition.addItem (tr (noteconditions::occurrenceName (c)), true,
  4415. all ([c] (const Note& n) { return n.condition == c && n.cycle <= 1; }),
  4416. [setAll, c] { setAll ([c] (Note& n) { n.condition = (std::uint8_t) c; n.cycle = 0; n.cycleMask = 0; }); });
  4417. condition.addSeparator();
  4418. for (int length = 2; length <= noteconditions::maxPresetCycle; ++length)
  4419. {
  4420. juce::PopupMenu cycle;
  4421. for (int pass = 1; pass <= length; ++pass)
  4422. {
  4423. const auto mask = (std::uint16_t) (1u << (pass - 1));
  4424. cycle.addItem (juce::String (noteconditions::cycleText (length, mask)), true,
  4425. all ([length, mask] (const Note& n) { return n.cycle == length && n.cycleMask == mask; }),
  4426. [setAll, length, mask] { setAll ([length, mask] (Note& n) { n.cycle = (std::uint8_t) length; n.cycleMask = mask; }); });
  4427. }
  4428. if (length == 4) // (two of four: Bitwig's Recurrence with two passes lit)
  4429. {
  4430. cycle.addSeparator();
  4431. for (const std::uint16_t mask : { (std::uint16_t) 0b0101, (std::uint16_t) 0b1010 })
  4432. cycle.addItem (juce::String (noteconditions::cycleText (4, mask)), true,
  4433. all ([mask] (const Note& n) { return n.cycle == 4 && n.cycleMask == mask; }),
  4434. [setAll, mask] { setAll ([mask] (Note& n) { n.cycle = 4; n.cycleMask = mask; }); });
  4435. }
  4436. condition.addSubMenu (tr ("Cycle of {0} passes", { juce::String (length) }), cycle);
  4437. }
  4438. condition.addItem (tr ("No cycle"), true, all ([] (const Note& n) { return n.cycle <= 1; }), [setAll] { setAll ([] (Note& n) { n.cycle = 0; n.cycleMask = 0; }); });
  4439. menu.addSubMenu (tr ("Condition"), condition);
  4440. menu.addSeparator();
  4441. menu.addItem (tr ("Fill (the notes with a Fill condition play)"), true, chance::fillSwitch().load(), [this] {
  4442. chance::fillSwitch().store (! chance::fillSwitch().load());
  4443. repaint();
  4444. });
  4445. menu.addItem (tr ("Reset ratchets and conditions"), [setAll] {
  4446. setAll ([] (Note& n) {
  4447. n.ratchets = 0;
  4448. n.ratchetVelocity = 0.0f;
  4449. n.condition = notecondition::always;
  4450. n.cycle = 0;
  4451. n.cycleMask = 0;
  4452. });
  4453. });
  4454. menu.addSeparator();
  4455. menu.addItem (tr ("Show the ratchets lane"), true, laneId() == laneRatchets, [this] { laneBox.setSelectedId (laneRatchets); });
  4456. menu.addItem (tr ("Show the condition lane"), true, laneId() == laneCondition, [this] { laneBox.setSelectedId (laneCondition); });
  4457. return menu;
  4458. }
  4459. void PianoRollComponent::showMoreMenu()
  4460. {
  4461. moreMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&moreButton));
  4462. }
  4463. juce::PopupMenu PianoRollComponent::moreMenu()
  4464. {
  4465. const auto grid = gridTicks();
  4466. const auto bar = engine.getSong().barTicks();
  4467. juce::PopupMenu menu;
  4468. menu.addSubMenu (theme::mnemonic (tr ("File"), 'F'), fileMenu());
  4469. menu.addSubMenu (theme::mnemonic (tr ("Edit"), 'E'), editMenu());
  4470. menu.addSubMenu (theme::mnemonic (tr ("View"), 'V'), viewMenu());
  4471. menu.addSubMenu (tr ("Time markers"), markersMenu());
  4472. menu.addSeparator();
  4473. menu.addSectionHeader (tr ("Note operations (selection, or all notes)"));
  4474. 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); }); });
  4475. 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> {}; }); });
  4476. menu.addItem (tr ("Make legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  4477. 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; }); });
  4478. menu.addItem (tr ("Quantise starts") + keyText ("pianoRoll.quantizeStarts"), [this] { quantizeOperation (0); });
  4479. menu.addItem (tr ("Quantise starts 50% (halfway to the grid)") + keyText ("pianoRoll.quantizeHalf"), [this] { quantizeOperation (2); });
  4480. menu.addItem (tr ("Quantise starts and lengths") + keyText ("pianoRoll.quickQuantize"), [this] { quantizeOperation (1); });
  4481. 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; }); });
  4482. 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; }); });
  4483. menu.addSeparator();
  4484. menu.addSubMenu (theme::mnemonic (tr ("Tools"), 'T'), toolsMenu());
  4485. menu.addSubMenu (theme::mnemonic (tr ("Select"), 'S'), selectMenu());
  4486. {
  4487. juce::PopupMenu zoom;
  4488. zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("pianoRoll.zoomIn"); });
  4489. zoom.addItem (tr ("Zoom out") + "\tPageDown", [this] { runAction ("pianoRoll.zoomOut"); });
  4490. zoom.addItem (tr ("Zoom: one bar") + "\tShift+1", [this] { runAction ("pianoRoll.zoom1"); });
  4491. zoom.addItem (tr ("Zoom: four bars") + "\tShift+2", [this] { runAction ("pianoRoll.zoom2"); });
  4492. zoom.addItem (tr ("Zoom: sixteen bars") + "\tShift+3", [this] { runAction ("pianoRoll.zoom3"); });
  4493. zoom.addItem (tr ("Zoom to show everything") + "\tShift+4", [this] { runAction ("pianoRoll.zoomAll"); });
  4494. zoom.addItem (tr ("Zoom to the selection") + "\tShift+5", [this] { runAction ("pianoRoll.zoomSelection"); });
  4495. zoom.addItem (tr ("Previous view"), viewStack.depth() > 0, false, [this] { runAction ("pianoRoll.previousView"); }); // round 190qe
  4496. zoom.addItem (tr ("Centre the view on the playhead") + "\tShift+0", [this] { runAction ("pianoRoll.centrePlayhead"); });
  4497. zoom.addSeparator();
  4498. zoom.addItem (tr ("Taller keys") + "\tCtrl+Alt+Wheel", [this] { rowHeight = juce::jmin (gesture::maxKeyHeight, rowHeight + 2); updateScrollBars(); repaint(); });
  4499. zoom.addItem (tr ("Shorter keys"), [this] { rowHeight = juce::jmax (gesture::minKeyHeight, rowHeight - 2); updateScrollBars(); repaint(); });
  4500. menu.addSubMenu (tr ("Zoom"), zoom);
  4501. }
  4502. menu.addSeparator();
  4503. menu.addItem (tr ("Snap notes to the scale") + keyText ("pianoRoll.scaleSnap"), scaleIndex() > 0, scaleSnap, [this] { setScaleSnap (! scaleSnap); });
  4504. menu.addItem (tr ("Fold to the scale (hide the other keys and their notes)"), scaleIndex() > 0, foldToScale,
  4505. [this] { setFoldToScale (! foldToScale); });
  4506. menu.addItem (tr ("Chord stamp: the clicked key is the top note"), true, chordTopDown, [this] { chordTopDown = ! chordTopDown; });
  4507. // the chord stamp's list (round 190j, discussion #10): the toolbar's chord box is hidden in a narrow window, so
  4508. // the stamp is always in this menu too
  4509. menu.addSubMenu (tr ("Chord stamp"), stampMenu(), true, juce::Image(), chordBox.getSelectedId() > 1);
  4510. menu.addItem (tr ("Stamp: none (single notes)") + keyText ("pianoRoll.stampNone"), chordBox.getSelectedId() != 1, false,
  4511. [this] { runAction ("pianoRoll.stampNone"); });
  4512. menu.addItem (tr ("Move the notes onto the scale"), scaleIndex() > 0, false, [this] {
  4513. const auto root = scaleRoot(), scale = scaleIndex();
  4514. runOperation ([root, scale] (Pattern& p, const std::vector<int>& t) { notetools::snapNotesToScale (p, t, root, scale); return t; });
  4515. });
  4516. menu.addSeparator();
  4517. menu.addItem (tr ("Note names on every key"), true, notenames::everyKey.load(), [this] {
  4518. notenames::everyKey.store (! notenames::everyKey.load());
  4519. if (onNoteNamesChanged != nullptr)
  4520. onNoteNamesChanged(); // (saved with the settings)
  4521. repaint();
  4522. });
  4523. menu.addItem (tr ("Resize notes from the left edge too") + "\tCtrl+Alt+Home", true, resizeFromLeft, [this] { resizeFromLeft = ! resizeFromLeft; });
  4524. // issue #183: FL keeps placed and dragged notes silent while the song / pattern plays; this hears them anyway
  4525. menu.addItem (tr ("Preview notes while playing"), true, previewWhilePlaying, [] {
  4526. previewWhilePlaying = ! previewWhilePlaying;
  4527. if (EditorGlobals::get().onOptionsChanged)
  4528. EditorGlobals::get().onOptionsChanged(); // (saved with the UI settings)
  4529. });
  4530. menu.addItem (tr ("Show ghost notes") + "\tAlt+V", true, showGhosts,
  4531. [this] { ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync); });
  4532. menu.addItem (tr ("Ghost notes are editable") + "\tCtrl+Alt+V", true, editGhosts, [this] {
  4533. editGhosts = ! editGhosts;
  4534. if (editGhosts && ! showGhosts)
  4535. ghostButton.setToggleState (true, juce::sendNotificationSync);
  4536. repaint();
  4537. });
  4538. menu.addSubMenu (tr ("Ghost channels"), ghostChannelsMenu());
  4539. menu.addSeparator();
  4540. menu.addSubMenu ("MIDI", midiMenu());
  4541. return menu;
  4542. }
  4543. bool PianoRollComponent::ghostShown (int channel) const noexcept
  4544. {
  4545. const auto& channels = engine.getSong().channels;
  4546. return channel < 0 || channel >= (int) channels.size() || ! channels[(std::size_t) channel].ghostHidden;
  4547. }
  4548. void PianoRollComponent::setGhostChannels (const std::function<bool (int channel, bool shown)>& show)
  4549. {
  4550. engine.editSong ([&show] (Song& s) {
  4551. for (int c = 0; c < (int) s.channels.size(); ++c)
  4552. s.channels[(std::size_t) c].ghostHidden = ! show (c, ! s.channels[(std::size_t) c].ghostHidden);
  4553. }, false);
  4554. engine.markModified();
  4555. if (! showGhosts) // choosing what to ghost shows the ghosts
  4556. ghostButton.setToggleState (true, juce::sendNotificationSync);
  4557. repaint();
  4558. }
  4559. juce::PopupMenu PianoRollComponent::ghostChannelsMenu()
  4560. {
  4561. // FL 2026's ghost notes button menu (round 166d [SHOT], right-click on it): "Ghost channels", All, None, then every
  4562. // channel with a check mark (the edited one in bold); a click toggles that channel's ghost notes
  4563. struct ChannelItem final : juce::PopupMenu::CustomComponent
  4564. {
  4565. ChannelItem (juce::String t, bool tick, bool bold) : text (std::move (t)), ticked (tick), strong (bold) {}
  4566. void getIdealSize (int& w, int& h) override
  4567. {
  4568. w = juce::jlimit (140, 420, 40 + juce::GlyphArrangement::getStringWidthInt (theme::font (theme::type::body, true), text));
  4569. h = 22;
  4570. }
  4571. void paint (juce::Graphics& g) override
  4572. {
  4573. if (isItemHighlighted())
  4574. {
  4575. g.setColour (theme::colour::accent.withAlpha (0.35f));
  4576. g.fillRect (getLocalBounds());
  4577. }
  4578. auto area = getLocalBounds();
  4579. const auto tickArea = area.removeFromLeft (24).toFloat();
  4580. if (ticked)
  4581. icons::draw (g, Icon::check, tickArea.withSizeKeepingCentre (12.0f, 12.0f), theme::colour::textPrimary);
  4582. g.setColour (ticked ? theme::colour::textPrimary : theme::colour::textSecondary);
  4583. g.setFont (theme::font (theme::type::body, strong));
  4584. g.drawText (text, area.withTrimmedRight (8), juce::Justification::centredLeft, true);
  4585. }
  4586. juce::String text;
  4587. bool ticked, strong;
  4588. };
  4589. juce::PopupMenu menu;
  4590. menu.addSectionHeader (tr ("Ghost channels"));
  4591. menu.addItem (tr ("All"), [this] { setGhostChannels ([] (int, bool) { return true; }); });
  4592. menu.addItem (tr ("None"), [this] { setGhostChannels ([] (int, bool) { return false; }); });
  4593. menu.addSeparator();
  4594. const auto& song = engine.getSong();
  4595. const auto current = engine.getSelectedChannel();
  4596. for (int c = 0; c < (int) song.channels.size(); ++c)
  4597. {
  4598. const auto name = juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str());
  4599. juce::PopupMenu::Item item (name);
  4600. item.customComponent = new ChannelItem (name, ghostShown (c), c == current);
  4601. item.action = [this, c] { setGhostChannels ([c] (int k, bool shown) { return k == c ? ! shown : shown; }); };
  4602. menu.addItem (std::move (item));
  4603. }
  4604. return menu;
  4605. }
  4606. void PianoRollComponent::openMidiTools()
  4607. {
  4608. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  4609. auto panel = std::make_unique<MidiToolsPanel> (
  4610. engine,
  4611. [safe] {
  4612. MidiToolsPanel::Target t;
  4613. if (safe != nullptr)
  4614. {
  4615. t.pattern = safe->engine.getSong().currentPattern;
  4616. t.indices = safe->midiToolNotes (t.selected);
  4617. t.grid = safe->midiToolGrid();
  4618. t.from = safe->timeSelectionFrom(); // round 190fm: Generate writes into the time selection
  4619. t.to = safe->timeSelectionTo();
  4620. t.channel = safe->engine.getSelectedChannel();
  4621. }
  4622. return t;
  4623. },
  4624. [safe] (const std::vector<int>& indices) {
  4625. if (safe != nullptr)
  4626. safe->selectMidiToolResult (indices);
  4627. });
  4628. struct Padded final : juce::Component // (the panel with a margin, on the window's background)
  4629. {
  4630. explicit Padded (std::unique_ptr<MidiToolsPanel> p) : panel (std::move (p))
  4631. {
  4632. addAndMakeVisible (*panel);
  4633. setSize (MidiToolsPanel::panelWidth + 16, MidiToolsPanel::panelHeight + 12);
  4634. }
  4635. void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
  4636. void resized() override { panel->setBounds (getLocalBounds().reduced (8, 6)); }
  4637. std::unique_ptr<MidiToolsPanel> panel;
  4638. };
  4639. openToolWindow (std::make_unique<Padded> (std::move (panel)), tr ("MIDI Tools"), "midiTools");
  4640. }
  4641. void PianoRollComponent::openChordHelper()
  4642. {
  4643. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  4644. const auto look = ChordHelperPanel::lookNow();
  4645. auto panel = std::make_unique<ChordHelperPanel> (
  4646. engine,
  4647. [safe] {
  4648. ChordHelperPanel::Target t;
  4649. if (safe != nullptr)
  4650. {
  4651. t.pattern = safe->engine.getSong().currentPattern;
  4652. t.channel = safe->engine.getSelectedChannel();
  4653. t.selected = safe->selection;
  4654. }
  4655. return t;
  4656. },
  4657. [safe] (const std::vector<int>& indices) {
  4658. if (safe != nullptr)
  4659. safe->selectOwnNewNotes (indices);
  4660. },
  4661. look);
  4662. auto* raw = panel.get();
  4663. openToolWindow (std::move (panel), tr ("Chord helper"), "chordHelper");
  4664. chordHelper = raw;
  4665. }
  4666. void PianoRollComponent::selectOwnNewNotes (std::vector<int> indices)
  4667. {
  4668. const auto& song = engine.getSong();
  4669. if (song.currentPattern == knownPattern && engine.getSelectedChannel() == knownChannel)
  4670. knownNoteCount = currentPattern (song).notes.size();
  4671. setSelection (std::move (indices));
  4672. chordPanelSelection = selection; // (the helper already read it)
  4673. }
  4674. ChordHelperPanel* PianoRollComponent::chordHelperForTests() const noexcept { return dynamic_cast<ChordHelperPanel*> (chordHelper.getComponent()); }
  4675. juce::PopupMenu PianoRollComponent::toolsMenu()
  4676. {
  4677. // FL's piano roll Tools menu (REA round 143, EXEC capture): its groups and keys, in its order
  4678. juce::PopupMenu menu;
  4679. const auto grid = gridTicks();
  4680. auto tool = [this, &menu] (NoteTool t, const char* key) {
  4681. menu.addItem (tr (noteToolTitle (t)) + "..." + (key != nullptr ? juce::String ("\t") + key : juce::String()), [this, t] { openNoteTool (t); });
  4682. };
  4683. menu.addSectionHeader (tr ("Built-in"));
  4684. tool (NoteTool::riffMachine, "Alt+E");
  4685. menu.addItem (tr ("Generate chord progression...") + "\tAlt+P", [this] { openNoteTool (NoteTool::chordProgression); });
  4686. menu.addSeparator();
  4687. menu.addItem (tr ("Quick legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  4688. tool (NoteTool::articulate, "Alt+L");
  4689. menu.addSeparator();
  4690. menu.addItem (tr ("Quick quantize") + keyText ("pianoRoll.quickQuantize"), [this] { quantizeOperation (1); });
  4691. menu.addItem (tr ("Quick quantize start times") + keyText ("pianoRoll.quantizeStarts"), [this] { quantizeOperation (0); });
  4692. menu.addItem (tr ("Quick quantize 50% (halfway to the grid)") + keyText ("pianoRoll.quantizeHalf"), [this] { quantizeOperation (2); });
  4693. tool (NoteTool::quantize, "Alt+Q");
  4694. menu.addSeparator();
  4695. menu.addItem (tr ("Quick chop") + "\tCtrl+U", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); }); });
  4696. tool (NoteTool::chop, "Alt+U");
  4697. menu.addSeparator();
  4698. menu.addItem (tr ("Glue notes") + "\tCtrl+G", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; }); });
  4699. menu.addSeparator();
  4700. tool (NoteTool::arpeggiate, "Alt+A");
  4701. tool (NoteTool::strum, "Alt+S");
  4702. tool (NoteTool::flam, "Alt+F");
  4703. tool (NoteTool::claw, "Alt+W");
  4704. tool (NoteTool::limit, "Alt+K");
  4705. tool (NoteTool::flip, "Alt+Y");
  4706. tool (NoteTool::randomise, "Alt+R");
  4707. menu.addSeparator();
  4708. tool (NoteTool::scaleLevels, "Alt+X");
  4709. tool (NoteTool::lfo, "Alt+O");
  4710. // FL's second column ("Scripts": Python tools shipped with FL); LYNX has its own built-in versions
  4711. menu.addSectionHeader (tr ("More tools"));
  4712. tool (NoteTool::euclidean, nullptr);
  4713. tool (NoteTool::humanize, nullptr);
  4714. tool (NoteTool::noteRepeat, nullptr);
  4715. // Live 12's MIDI Transformations as a docked-style panel (round 190s; LYNX addition beside FL's tools above)
  4716. menu.addItem (tr ("MIDI Tools") + "...", [this] { openMidiTools(); });
  4717. // LYNX's Chord helper (round 190mc, discussion #105): modal interchange from the selected chord
  4718. menu.addItem (tr ("Chord helper") + "..." + keyText ("pianoRoll.chordHelper"), [this] { openChordHelper(); });
  4719. {
  4720. juce::PopupMenu velocity;
  4721. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  4722. const auto& song = engine.getSong();
  4723. setSelection (pick (song.activePattern(), channelNotes()));
  4724. };
  4725. velocity.addItem (tr ("Loudest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, true); }); });
  4726. velocity.addItem (tr ("Quietest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, false); }); });
  4727. velocity.addSeparator();
  4728. 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 } })
  4729. velocity.addItem (tr ("Velocity {0}", { juce::String (label) }), [choose, lo = lo, hi = hi] {
  4730. choose ([lo, hi] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, lo, hi); });
  4731. });
  4732. if (! selection.empty())
  4733. {
  4734. const auto& notes = engine.getSong().activePattern().notes;
  4735. const auto v = selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].velocity : 0.0f;
  4736. velocity.addSeparator();
  4737. velocity.addItem (tr ("Same velocity as the selected note ({0}%)", { juce::String (juce::roundToInt (v * 100.0f)) }), [choose, v] {
  4738. choose ([v] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, v - 0.005f, v + 0.005f); });
  4739. });
  4740. }
  4741. menu.addSubMenu (tr ("Select by velocity"), velocity);
  4742. }
  4743. {
  4744. // Live 12's note Chance (round 187c, LYNX additions): probability groups, a reset and a new draw for the project
  4745. juce::PopupMenu chance;
  4746. const auto several = selection.size() > 1;
  4747. chance.addItem (tr ("Group the selected notes: play all"), several, false, [this] {
  4748. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::groupChance (p, t, false); return t; });
  4749. });
  4750. chance.addItem (tr ("Group the selected notes: play one"), several, false, [this] {
  4751. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::groupChance (p, t, true); return t; });
  4752. });
  4753. chance.addItem (tr ("Ungroup the chance of the selected notes"), [this] {
  4754. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::ungroupChance (p, t); return t; });
  4755. });
  4756. chance.addSeparator();
  4757. chance.addItem (tr ("Reset chance and velocity range"), [this] {
  4758. runOperation ([] (Pattern& p, const std::vector<int>& t) {
  4759. notetools::ungroupChance (p, t);
  4760. for (auto i : t)
  4761. if (i >= 0 && i < (int) p.notes.size())
  4762. p.notes[(std::size_t) i].chance = 1.0f, p.notes[(std::size_t) i].velocityRange = 0.0f;
  4763. return t;
  4764. });
  4765. });
  4766. chance.addItem (tr ("New chance seed (draws again for the whole project)"), [this] {
  4767. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt64();
  4768. engine.editSong ([seed] (Song& s) { s.chanceSeed = seed == 0 ? 1u : seed; });
  4769. repaint();
  4770. });
  4771. chance.addSeparator();
  4772. chance.addItem (tr ("Show the chance lane"), true, laneIsChance(), [this] {
  4773. laneBox.setSelectedId (laneChance);
  4774. });
  4775. menu.addSubMenu (tr ("Chance (LYNX)"), chance);
  4776. menu.addSubMenu (tr ("Repeats and conditions (LYNX)"), repeatsMenu()); // (round 190pm)
  4777. }
  4778. menu.addSeparator();
  4779. menu.addItem (tr ("Edit events..."), [this] {
  4780. openEventEditor (engine, { AutomationTargetKind::channelVolume, engine.getSelectedChannel() });
  4781. });
  4782. // FL's second column: "Scripts", the Piano roll's Python scripts (round 190as)
  4783. menu.addColumnBreak();
  4784. menu.addSectionHeader (tr ("Scripts"));
  4785. addScriptItems (menu);
  4786. return menu;
  4787. }
  4788. void PianoRollComponent::openNoteTool (NoteTool tool)
  4789. {
  4790. const auto target = selectionOrAll();
  4791. if (target.empty() && ! noteToolGenerates (tool))
  4792. return;
  4793. showNoteTool (engine, tool, target, gridTicks(), [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  4794. if (safe != nullptr)
  4795. safe->setSelection ({});
  4796. });
  4797. }
  4798. void PianoRollComponent::zoomAroundCentre (double factor)
  4799. {
  4800. // round 190qe (UX-A2): the keys zoom around the playhead while it plays on screen, else the selection's centre on
  4801. // screen, else the view's centre (as before); the step glides with Animations on (UX-A3). Issue #276 (round 190qr,
  4802. // the LYNX extra "Zoom around the song position"): the song position when it is in view, before all of those
  4803. settleViewGlide();
  4804. const auto grid = gridArea();
  4805. const auto anchor = zoomanchor::anchorX (zoomanchor::atSongPosition() && playheadTick >= 0.0, keyZoomAnchorPx() + grid.getX(), tickToX (playheadTick),
  4806. (double) grid.getX(), (double) grid.getRight())
  4807. - grid.getX();
  4808. auto target = currentView();
  4809. target.pixelsPerUnit = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, pixelsPerTick * factor);
  4810. target.scroll = zoomanchor::scrollFor (scrollTicks, pixelsPerTick, target.pixelsPerUnit, anchor);
  4811. showView (clampedView (target));
  4812. }
  4813. void PianoRollComponent::zoomToBars (int bars)
  4814. {
  4815. const auto bar = (double) engine.getSong().barTicks();
  4816. const auto from = std::floor (scrollTicks / bar) * bar;
  4817. zoomToTicks (from, from + bars * bar);
  4818. }
  4819. void PianoRollComponent::zoomAll()
  4820. {
  4821. const auto& song = engine.getSong();
  4822. zoomToTicks (0.0, (double) currentPattern (song).effectiveLength (song.meter()));
  4823. }
  4824. void PianoRollComponent::zoomToSelection()
  4825. {
  4826. const auto target = selectionOrAll();
  4827. if (target.empty())
  4828. return zoomAll();
  4829. const auto& notes = currentPattern (engine.getSong()).notes;
  4830. std::int64_t from = INT64_MAX, to = 0;
  4831. int low = 127, high = 0;
  4832. for (auto i : target)
  4833. {
  4834. const auto& n = notes[(std::size_t) i];
  4835. from = juce::jmin (from, n.start);
  4836. to = juce::jmax (to, n.start + n.length);
  4837. low = juce::jmin (low, n.key);
  4838. high = juce::jmax (high, n.key);
  4839. }
  4840. // round 190qe (D2-PL8): the view it leaves goes on the view stack; the same key again (the view still the one it
  4841. // zoomed to) goes back to it
  4842. settleViewGlide();
  4843. const auto margin = (double) ticksPerStep;
  4844. const auto before = currentView();
  4845. auto view = before;
  4846. const auto t0 = juce::jmax (0.0, (double) from - margin), t1 = (double) to + margin;
  4847. if (t1 - t0 >= 1.0)
  4848. {
  4849. view.pixelsPerUnit = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, gridArea().getWidth() / (t1 - t0));
  4850. view.scroll = t0;
  4851. }
  4852. view.scrollY = juce::jmax (0, rowFor ((low + high) / 2) * rowHeight - gridArea().getHeight() / 2);
  4853. showView (viewStack.toggle (before, clampedView (view)));
  4854. }
  4855. // --- round 190qe (TOP-NEXT R1): edge scroll, view stack, zoom glide, selection history ---------------------------------
  4856. // A lane stroke (velocity, Release velocity..., the event lanes): the view runs sideways only, with the lane's x range
  4857. bool PianoRollComponent::edgeOnLane() const
  4858. {
  4859. return drag == Drag::velocity || drag == Drag::velocitySet || drag == Drag::eventDraw || drag == Drag::eventErase;
  4860. }
  4861. // FL scrolls for notes moved and resized, the selection box, the brushes, and the lane strokes (round 190qc)
  4862. bool PianoRollComponent::edgeScrollsX() const
  4863. {
  4864. return drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft || drag == Drag::select || drag == Drag::paint
  4865. || drag == Drag::drumPaint || edgeOnLane();
  4866. }
  4867. bool PianoRollComponent::edgeScrollsY() const
  4868. {
  4869. return drag == Drag::move || drag == Drag::select || drag == Drag::paint || drag == Drag::drumPaint;
  4870. }
  4871. bool PianoRollComponent::edgeScrollFrame (double nowMs)
  4872. {
  4873. if (! edgeDragEvent.has_value() || ! (edgeScrollsX() || edgeScrollsY()) || ! (isMouseButtonDown() || edgescroll::buttonHeldForTests))
  4874. {
  4875. edgeScroller.stop();
  4876. return false;
  4877. }
  4878. if (juce::KeyPress::isKeyCurrentlyDown (juce::KeyPress::escapeKey))
  4879. edgeScroller.hold();
  4880. const auto grid = gridArea();
  4881. const auto lane = edgeOnLane() ? velocityArea() : grid;
  4882. const auto law = layoutstyle::current() == layoutstyle::Style::pattern ? edgescroll::Law::fl : edgescroll::Law::smooth;
  4883. const auto quantum = (double) edgescroll::wholeQuantum (juce::Component::getApproximateScaleFactorForComponent (this));
  4884. const auto at = edgeDragEvent->position;
  4885. const auto step = edgeScroller.update (nowMs, at.x, at.y, grid.getX(), lane.getY(), grid.getRight(), lane.getBottom(), edgeScrollsX(),
  4886. edgeScrollsY(), law, quantum);
  4887. if (step.dx == 0.0 && step.dy == 0.0)
  4888. return step.running;
  4889. const auto oldTicks = scrollTicks;
  4890. const auto oldY = scrollY;
  4891. if (step.dx != 0.0)
  4892. scrollTicks = juce::jmax (0.0, scrollTicks + step.dx / pixelsPerTick);
  4893. if (step.dy != 0.0)
  4894. scrollY = juce::jmax (0, scrollY + (int) step.dy);
  4895. updateScrollBars();
  4896. if (scrollTicks != oldTicks || scrollY != oldY)
  4897. {
  4898. // (a lane stroke goes on from where it was in the song: its last point moved with the view)
  4899. lastVelocityX -= (int) std::lround ((scrollTicks - oldTicks) * pixelsPerTick);
  4900. repaint();
  4901. const auto event = *edgeDragEvent;
  4902. mouseDrag (event);
  4903. }
  4904. return step.running;
  4905. }
  4906. bool PianoRollComponent::feelFrame (double nowMs)
  4907. {
  4908. auto active = edgeScrollFrame (nowMs);
  4909. if (viewGlide.running)
  4910. {
  4911. if (viewGlide.done (nowMs))
  4912. {
  4913. viewGlide.running = false;
  4914. applyView (viewGlide.to);
  4915. }
  4916. else
  4917. applyView (viewGlide.at (nowMs));
  4918. active = true;
  4919. }
  4920. return active;
  4921. }
  4922. viewstack::View PianoRollComponent::currentView() const
  4923. {
  4924. return { scrollTicks, pixelsPerTick, (double) scrollY };
  4925. }
  4926. void PianoRollComponent::applyView (const viewstack::View& v)
  4927. {
  4928. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, v.pixelsPerUnit);
  4929. scrollTicks = juce::jmax (0.0, v.scroll);
  4930. scrollY = juce::jmax (0, (int) std::lround (v.scrollY));
  4931. updateScrollBars();
  4932. repaint();
  4933. }
  4934. viewstack::View PianoRollComponent::clampedView (const viewstack::View& v)
  4935. {
  4936. const auto saved = currentView();
  4937. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, v.pixelsPerUnit);
  4938. scrollTicks = juce::jmax (0.0, v.scroll);
  4939. scrollY = juce::jmax (0, (int) std::lround (v.scrollY));
  4940. updateScrollBars();
  4941. const auto clamped = currentView();
  4942. pixelsPerTick = saved.pixelsPerUnit;
  4943. scrollTicks = saved.scroll;
  4944. scrollY = (int) saved.scrollY;
  4945. updateScrollBars();
  4946. return clamped;
  4947. }
  4948. // UX-A3: the zoom keys, fit and zoom-to-selection glide over 150 ms (ease-out) while Animations are on; off: at once
  4949. void PianoRollComponent::showView (const viewstack::View& target)
  4950. {
  4951. if (ui::motion::enabled() && (! platform::testMode() || glide::inTests) && ui::showingOrShot (*this))
  4952. {
  4953. viewGlide.start (currentView(), target, juce::Time::getMillisecondCounterHiRes(), (double) gridArea().getWidth());
  4954. if (viewGlide.running)
  4955. {
  4956. frames.wake();
  4957. return;
  4958. }
  4959. }
  4960. viewGlide.running = false;
  4961. applyView (target);
  4962. }
  4963. void PianoRollComponent::settleViewGlide()
  4964. {
  4965. if (! viewGlide.running)
  4966. return;
  4967. viewGlide.running = false;
  4968. applyView (viewGlide.to);
  4969. }
  4970. // UX-A2: the zoom keys' anchor (px from the grid's left): the playhead while the pattern plays and it is on screen, else
  4971. // the centre of the selected notes when on screen, else the view's centre
  4972. double PianoRollComponent::keyZoomAnchorPx() const
  4973. {
  4974. const auto grid = gridArea();
  4975. const auto& song = engine.getSong();
  4976. const auto playing = engine.getTransport().playing.load();
  4977. std::optional<double> playhead, selected;
  4978. if (playing)
  4979. if (const auto tick = transportedit::patternPlayhead (song, song.currentPattern, engine.getTransport().positionTicks.load()); tick >= 0.0)
  4980. playhead = tickToX (tick) - grid.getX();
  4981. if (! selection.empty())
  4982. {
  4983. const auto& notes = currentPattern (song).notes;
  4984. std::int64_t from = INT64_MAX, to = 0;
  4985. for (auto i : selection)
  4986. if (i >= 0 && i < (int) notes.size())
  4987. {
  4988. from = juce::jmin (from, notes[(std::size_t) i].start);
  4989. to = juce::jmax (to, notes[(std::size_t) i].start + notes[(std::size_t) i].length);
  4990. }
  4991. if (to > from)
  4992. selected = tickToX (0.5 * (double) (from + to)) - grid.getX();
  4993. }
  4994. return zoomanchor::anchorPx (zoomanchor::Source::keys, 0.0, grid.getWidth(), playing, playhead, selected);
  4995. }
  4996. std::vector<PianoRollComponent::NoteKey> PianoRollComponent::noteKeys (const std::vector<int>& indices) const
  4997. {
  4998. const auto& notes = currentPattern (engine.getSong()).notes;
  4999. std::vector<NoteKey> keys;
  5000. for (auto i : indices)
  5001. if (i >= 0 && i < (int) notes.size())
  5002. {
  5003. const auto& n = notes[(std::size_t) i];
  5004. keys.push_back ({ n.channel, n.key, n.start, n.length });
  5005. }
  5006. std::sort (keys.begin(), keys.end());
  5007. return keys;
  5008. }
  5009. // D2-PL9: "Restore selection" — the notes a click deselected (the last 8 selections, newest first), found again by their
  5010. // channel, key, start and length
  5011. void PianoRollComponent::restoreSelection()
  5012. {
  5013. const auto restored = selectionHistory.restore (noteKeys (selection));
  5014. if (! restored.has_value())
  5015. {
  5016. ui::postHint ({ tr ("No earlier selection to restore"), {}, false, false }, 2000);
  5017. return;
  5018. }
  5019. const auto& notes = currentPattern (engine.getSong()).notes;
  5020. std::vector<int> indices;
  5021. for (int i = 0; i < (int) notes.size(); ++i)
  5022. if (const auto key = noteKeys ({ i }); ! key.empty() && std::binary_search (restored->begin(), restored->end(), key.front()))
  5023. indices.push_back (i);
  5024. const juce::ScopedValueSetter<bool> restoring (selectionHistory.restoring, true);
  5025. setSelection (indices);
  5026. repaint();
  5027. }
  5028. // D2-PL8: "Previous view" — back to the view the last "Zoom to the selection" left
  5029. void PianoRollComponent::previousView()
  5030. {
  5031. if (const auto before = viewStack.back())
  5032. showView (*before);
  5033. }
  5034. void PianoRollComponent::centreOnPlayhead()
  5035. {
  5036. const auto& song = engine.getSong();
  5037. const auto length = (double) juce::jmax<std::int64_t> (1, currentPattern (song).effectiveLength (song.meter()));
  5038. auto tick = transportedit::patternPlayhead (song, song.currentPattern, engine.getTransport().positionTicks.load());
  5039. if (tick < 0.0)
  5040. tick = std::fmod (engine.getTransport().positionTicks.load(), length);
  5041. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick / 2.0);
  5042. updateScrollBars();
  5043. repaint();
  5044. }
  5045. void PianoRollComponent::centreOnTick (double tick, double at)
  5046. {
  5047. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick * at);
  5048. updateScrollBars();
  5049. repaint();
  5050. }
  5051. void PianoRollComponent::ColourSwatch::paintButton (juce::Graphics& g, bool over, bool down)
  5052. {
  5053. auto r = getLocalBounds().toFloat().reduced (3.0f);
  5054. g.setColour (theme::noteGroupColour (colourIndex, 0.85f));
  5055. g.fillRoundedRectangle (r, 3.0f);
  5056. g.setColour (over || down ? theme::colour::textPrimary : theme::colour::bg0.withAlpha (0.7f));
  5057. g.drawRoundedRectangle (r, 3.0f, 1.0f);
  5058. g.setColour (theme::colour::bg0.withAlpha (0.85f));
  5059. g.setFont (theme::font (theme::type::caption, true));
  5060. g.drawText (juce::String (colourIndex + 1), r, juce::Justification::centred, false);
  5061. }
  5062. void PianoRollComponent::colourSelection (int colour)
  5063. {
  5064. const auto target = selection;
  5065. if (target.empty())
  5066. return;
  5067. editNotes ([&] (Pattern& p) { notetools::setColour (p, target, colour); });
  5068. repaint();
  5069. }
  5070. void PianoRollComponent::selectByColour (int colour)
  5071. {
  5072. setSelection (notetools::selectByColour (currentPattern (engine.getSong()), channelNotes(), colour));
  5073. }
  5074. void PianoRollComponent::showColourMenu()
  5075. {
  5076. juce::PopupMenu menu;
  5077. menu.addSectionHeader (tr ("Colour for new notes"));
  5078. for (int c = 0; c < noteColourCount; ++c)
  5079. menu.addColouredItem (c + 1, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, c == noteColour);
  5080. menu.addSeparator();
  5081. menu.addItem (1000, tr ("Colour the selected notes with it") + "\tAlt+C", ! selection.empty());
  5082. {
  5083. juce::PopupMenu colourAs;
  5084. for (int c = 0; c < noteColourCount; ++c)
  5085. colourAs.addColouredItem (2001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, false);
  5086. menu.addSubMenu (tr ("Colour the selected notes"), colourAs, ! selection.empty());
  5087. }
  5088. {
  5089. juce::PopupMenu select;
  5090. const auto& pattern = currentPattern (engine.getSong());
  5091. for (int c = 0; c < noteColourCount; ++c)
  5092. select.addColouredItem (3001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f),
  5093. ! notetools::selectByColour (pattern, channelNotes(), c).empty(), false);
  5094. menu.addSubMenu (tr ("Select by colour") + "\tShift+C", select);
  5095. }
  5096. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&colourButton), [safe = juce::Component::SafePointer (this)] (int id) {
  5097. if (safe == nullptr || id <= 0)
  5098. return;
  5099. if (id <= noteColourCount)
  5100. {
  5101. safe->noteColour = id - 1;
  5102. safe->colourButton.colourIndex = id - 1;
  5103. safe->colourButton.repaint();
  5104. }
  5105. else if (id == 1000)
  5106. safe->colourSelection (safe->noteColour);
  5107. else if (id > 2000 && id <= 2000 + noteColourCount)
  5108. safe->colourSelection (id - 2001);
  5109. else if (id > 3000 && id <= 3000 + noteColourCount)
  5110. safe->selectByColour (id - 3001);
  5111. });
  5112. }
  5113. juce::PopupMenu PianoRollComponent::selectMenu()
  5114. {
  5115. // FL's piano roll Select submenu (its manual): all, invert, odd, random, muted, overlapping, stacked, by colour
  5116. juce::PopupMenu menu;
  5117. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  5118. setSelection (pick (currentPattern (engine.getSong()), channelNotes()));
  5119. };
  5120. menu.addItem (theme::mnemonic (tr ("All"), 'a') + "\tCtrl+A", [this] { selectAll(); });
  5121. menu.addItem (theme::mnemonic (tr ("Invert selection"), 'I') + "\tShift+I", [this] { runAction ("pianoRoll.invertSelection"); });
  5122. menu.addItem (theme::mnemonic (tr ("Deselect"), 'D') + "\tEsc", ! selection.empty(), false, [this] { setSelection ({}); });
  5123. menu.addSeparator();
  5124. // FL's Select items with their keys (round 168g): they add to the selection
  5125. menu.addItem (theme::mnemonic (tr ("Select one at random"), 'r') + keyText ("pianoRoll.selectRandomOne"), [this] { runAction ("pianoRoll.selectRandomOne"); });
  5126. menu.addItem (theme::mnemonic (tr ("Select more at random"), 'r') + keyText ("pianoRoll.selectRandomMore"), [this] { runAction ("pianoRoll.selectRandomMore"); });
  5127. menu.addItem (theme::mnemonic (tr ("Select odd (swung) notes"), 'o') + keyText ("pianoRoll.selectOddSteps"), [this] { runAction ("pianoRoll.selectOddSteps"); });
  5128. menu.addSeparator();
  5129. menu.addItem (tr ("Odd notes (every other one)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOdd (p, t); }); });
  5130. menu.addItem (tr ("Even notes"), [choose] {
  5131. choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::invertSelection (t, notetools::selectOdd (p, t)); });
  5132. });
  5133. menu.addItem (tr ("Random (half of the notes)"), [choose] {
  5134. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
  5135. choose ([seed] (const Pattern& p, const std::vector<int>& t) { return notetools::selectRandom (p, t, 0.5f, seed); });
  5136. });
  5137. menu.addItem (theme::mnemonic (tr ("Muted notes"), 'm'), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectMuted (p, t); }); });
  5138. menu.addItem (tr ("Overlapping notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOverlapping (p, t); }); });
  5139. menu.addItem (tr ("Stacked notes (hidden duplicates)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectStacked (p, t); }); });
  5140. menu.addItem (theme::mnemonic (tr ("Same colour as the selection"), 'c') + "\tShift+C", [this] { runAction ("pianoRoll.selectByColour"); });
  5141. menu.addSeparator();
  5142. menu.addItem (tr ("Group the selected notes") + "\tShift+G", selection.size() > 1, false, [this] { runAction ("pianoRoll.groupNotes"); });
  5143. menu.addItem (tr ("Ungroup the selected notes") + "\tAlt+G", ! selection.empty(), false, [this] { runAction ("pianoRoll.ungroupNotes"); });
  5144. // FL's last Select item, alone after a line (round 190mp, DE-71; capture 190mp A3.4): Magic lasso, no key, off
  5145. menu.addSeparator();
  5146. menu.addItem (tr ("Magic lasso"), true, EditorGlobals::get().pianoRollMagicLasso, [] {
  5147. auto& g = EditorGlobals::get();
  5148. g.pianoRollMagicLasso = ! g.pianoRollMagicLasso;
  5149. if (g.onOptionsChanged != nullptr)
  5150. g.onOptionsChanged();
  5151. });
  5152. // round 190qe (D2-PL9, LYNX's own): the selection a click replaced or cleared
  5153. menu.addItem (tr ("Restore selection") + " (LYNX)" + keyText ("pianoRoll.restoreSelection"), selectionHistory.size() > 0, false,
  5154. [this] { runAction ("pianoRoll.restoreSelection"); });
  5155. return menu;
  5156. }
  5157. // FL's Magic lasso over the notes (round 190mp, DE-71; core/MagicLasso.h, FL's Playlist rules of round 189g): with the
  5158. // option on, a loop drawn with the mouse (no button) around notes selects them (Shift / a second loop: as FL's decide)
  5159. void PianoRollComponent::feedMagicLasso (juce::Point<int> p, bool buttonDown)
  5160. {
  5161. if (! EditorGlobals::get().pianoRollMagicLasso)
  5162. {
  5163. lassoPath.clear();
  5164. return;
  5165. }
  5166. const auto grid = gridArea();
  5167. const auto at = grid.getConstrainedPoint (p);
  5168. const auto loop = lassoPath.move ({ (double) at.x, (double) at.y }, juce::Time::getMillisecondCounter(), buttonDown || ! grid.contains (p));
  5169. if (loop.empty())
  5170. return;
  5171. const auto& notes = currentPattern (engine.getSong()).notes;
  5172. std::vector<int> enclosed;
  5173. std::vector<bool> enclosedSelected;
  5174. for (const auto i : channelNotes())
  5175. {
  5176. const auto& n = notes[(std::size_t) i];
  5177. const auto r = noteRect (n.start, n.length, n.key);
  5178. if (! r.toNearestInt().intersects (grid))
  5179. continue;
  5180. if (magiclasso::rectInsidePolygon (loop, magiclasso::innerRect ({ (double) r.getX(), (double) r.getY(), (double) r.getRight(), (double) r.getBottom() })))
  5181. {
  5182. enclosed.push_back (i);
  5183. enclosedSelected.push_back (isSelected (i));
  5184. }
  5185. }
  5186. switch (magiclasso::decide (enclosed, juce::ModifierKeys::currentModifiers.isShiftDown(), (int) selection.size(), enclosedSelected))
  5187. {
  5188. case magiclasso::Result::select:
  5189. {
  5190. auto chosen = selection;
  5191. for (const auto i : enclosed)
  5192. if (std::find (chosen.begin(), chosen.end(), i) == chosen.end())
  5193. chosen.push_back (i);
  5194. setSelection (chosen);
  5195. lassoPath.clear();
  5196. break;
  5197. }
  5198. case magiclasso::Result::zoomToSelection:
  5199. {
  5200. std::int64_t from = std::numeric_limits<std::int64_t>::max(), to = 0;
  5201. for (const auto i : selection)
  5202. if (i >= 0 && i < (int) notes.size())
  5203. {
  5204. from = std::min (from, notes[(std::size_t) i].start);
  5205. to = std::max (to, notes[(std::size_t) i].start + notes[(std::size_t) i].length);
  5206. }
  5207. if (to > from)
  5208. zoomToTicks ((double) from, (double) to);
  5209. lassoPath.clear();
  5210. break;
  5211. }
  5212. case magiclasso::Result::nothing:
  5213. break;
  5214. }
  5215. }
  5216. void PianoRollComponent::showKeyMenu (int key)
  5217. {
  5218. const auto channel = engine.getSelectedChannel();
  5219. if (channel < 0 || channel >= (int) engine.getSong().channels.size() || key < 0 || key > 127)
  5220. return;
  5221. const auto& labels = engine.getSong().channels[(std::size_t) channel].keyLabels;
  5222. const auto current = labels.find (key);
  5223. auto setLabels = [this, channel] (std::function<void (std::map<int, std::string>&)> edit) {
  5224. engine.editSong ([channel, edit] (Song& s) {
  5225. if (channel < (int) s.channels.size())
  5226. edit (s.channels[(std::size_t) channel].keyLabels);
  5227. });
  5228. repaint();
  5229. };
  5230. juce::PopupMenu menu;
  5231. menu.addSectionHeader (keyName (key));
  5232. menu.addItem (tr ("Rename this key..."), [key, setLabels, text = current != labels.end() ? current->second : std::string()] {
  5233. auto* window = new juce::AlertWindow (tr ("Key label"), tr ("The name shown on {0} for this channel", { keyName (key) }), juce::MessageBoxIconType::NoIcon);
  5234. window->addTextEditor ("label", juce::String::fromUTF8 (text.c_str()));
  5235. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5236. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5237. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, key, setLabels] (int result) {
  5238. if (result != 1)
  5239. return;
  5240. const auto label = window->getTextEditorContents ("label").trim().toStdString();
  5241. setLabels ([key, label] (std::map<int, std::string>& l) {
  5242. if (label.empty())
  5243. l.erase (key);
  5244. else
  5245. l[key] = label;
  5246. });
  5247. }),
  5248. true);
  5249. });
  5250. menu.addItem (tr ("Remove this key's label"), current != labels.end(), false,
  5251. [setLabels, key] { setLabels ([key] (std::map<int, std::string>& l) { l.erase (key); }); });
  5252. menu.addSeparator();
  5253. menu.addItem (tr ("Label the keys with the General MIDI drum map"), [setLabels] {
  5254. setLabels ([] (std::map<int, std::string>& l) {
  5255. for (int k = 35; k <= 81; ++k)
  5256. if (const auto* name = notetools::generalMidiDrumName (k))
  5257. l[k] = name;
  5258. });
  5259. });
  5260. menu.addItem (tr ("Remove all key labels of this channel"), ! labels.empty(), false,
  5261. [setLabels] { setLabels ([] (std::map<int, std::string>& l) { l.clear(); }); });
  5262. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  5263. }
  5264. void PianoRollComponent::updateChordReadout()
  5265. {
  5266. auto keys = engine.heldInputKeys();
  5267. if (keys.size() < 2)
  5268. {
  5269. keys.clear();
  5270. const auto& notes = currentPattern (engine.getSong()).notes;
  5271. for (auto i : selection)
  5272. if (i >= 0 && i < (int) notes.size())
  5273. keys.push_back (notes[(std::size_t) i].key);
  5274. }
  5275. const auto text = chordName (keys);
  5276. if (chordLabel.getText() != text)
  5277. chordLabel.setText (text, juce::dontSendNotification);
  5278. updateChordBubble();
  5279. }
  5280. void PianoRollComponent::updateChordBubble()
  5281. {
  5282. const auto now = juce::Time::getMillisecondCounter();
  5283. if (selection != chordPanelSelection)
  5284. {
  5285. // the toolbar's chord panel follows the selection whether this bubble is on or not (FL: FUN_00d32da0)
  5286. chordPanelSelection = selection;
  5287. if (auto* helper = dynamic_cast<ChordHelperPanel*> (chordHelper.getComponent())) // (round 190mc: only while it is open)
  5288. helper->refresh();
  5289. if (onSelectedKeys)
  5290. {
  5291. const auto& notes = currentPattern (engine.getSong()).notes;
  5292. std::vector<int> keys;
  5293. for (auto i : selection)
  5294. if (i >= 0 && i < (int) notes.size() && ! notes[(std::size_t) i].muted)
  5295. keys.push_back (notes[(std::size_t) i].key);
  5296. onSelectedKeys (keys);
  5297. }
  5298. }
  5299. if (! showChordName)
  5300. {
  5301. chordBubble.setVisible (false);
  5302. chordBubbleSelection = selection;
  5303. return;
  5304. }
  5305. if (selection != chordBubbleSelection)
  5306. {
  5307. // FL (FUN_00e5a850 → FUN_00d32da0, on every selection change): the different keys of the selected notes, muted
  5308. // ones left out; 2 to 10 of them name a chord
  5309. chordBubbleSelection = selection;
  5310. const auto& notes = currentPattern (engine.getSong()).notes;
  5311. std::vector<int> keys;
  5312. for (auto i : selection)
  5313. if (i >= 0 && i < (int) notes.size() && ! notes[(std::size_t) i].muted)
  5314. keys.push_back (notes[(std::size_t) i].key);
  5315. std::sort (keys.begin(), keys.end());
  5316. keys.erase (std::unique (keys.begin(), keys.end()), keys.end());
  5317. const auto text = keys.size() >= 2 && keys.size() <= 10 ? chordName (keys) : juce::String();
  5318. if (text.isNotEmpty())
  5319. {
  5320. chordBubble.setText (text, juce::dontSendNotification);
  5321. const auto font = chordBubble.getFont();
  5322. const auto width = juce::roundToInt (juce::GlyphArrangement::getStringWidth (font, text)) + 20;
  5323. const auto grid = gridArea();
  5324. chordBubble.setBounds (grid.getX() + 16, grid.getY() + 16, width, juce::roundToInt (font.getHeight()) + 10);
  5325. chordBubble.setVisible (true);
  5326. chordBubble.toFront (false);
  5327. chordBubbleUntil = now + 2000; // (FL keeps its chord readout at least 2 s: FUN_00d32da0 +0xac)
  5328. }
  5329. else
  5330. chordBubble.setVisible (false);
  5331. }
  5332. else if (chordBubble.isVisible() && now > chordBubbleUntil)
  5333. chordBubble.setVisible (false);
  5334. }
  5335. // Round 190hr: the reference's grid menu [STR AGridContextMenu: Widest … Narrowest (adaptive), Fixed with its values,
  5336. // Triplet; DOC: Snap to Grid Ctrl+4, Fixed / Adaptive Ctrl+5]. Each pick changes this editor's grid at once.
  5337. juce::PopupMenu PianoRollComponent::liveGridMenu()
  5338. {
  5339. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  5340. const auto change = [safe] (std::function<void (livegrid::Grid&)> fn) {
  5341. return [safe, fn] {
  5342. if (safe == nullptr)
  5343. return;
  5344. fn (safe->liveGrid);
  5345. safe->resized();
  5346. safe->repaint();
  5347. };
  5348. };
  5349. juce::PopupMenu menu;
  5350. menu.addSectionHeader (tr ("Adaptive Grid"));
  5351. for (int d = 0; d < livegrid::densityCount; ++d)
  5352. menu.addItem (tr (livegrid::densityName (d)), true, ! liveGrid.fixed && liveGrid.density == d, change ([d] (livegrid::Grid& g) {
  5353. g.fixed = false;
  5354. g.density = d;
  5355. g.snap = true;
  5356. }));
  5357. menu.addSectionHeader (tr ("Fixed Grid"));
  5358. for (int i = 0; i < livegrid::fixedCount; ++i)
  5359. {
  5360. const auto f = livegrid::fixedValues[i];
  5361. const auto text = f.den == 1 ? (f.num == 1 ? tr ("1 Bar") : tr ("{0} Bars", { juce::String (f.num) })) : juce::String (f.num) + "/" + juce::String (f.den);
  5362. menu.addItem (text, true, liveGrid.fixed && liveGrid.fixedIndex == i, change ([i] (livegrid::Grid& g) {
  5363. g.fixed = true;
  5364. g.fixedIndex = i;
  5365. g.snap = true;
  5366. }));
  5367. }
  5368. menu.addSeparator();
  5369. menu.addItem (tr ("Triplet Grid") + "\tCtrl+3", true, liveGrid.triplet, change ([] (livegrid::Grid& g) { g.triplet = ! g.triplet; }));
  5370. menu.addItem (tr ("Snap to Grid") + "\tCtrl+4", true, liveGrid.snap, change ([] (livegrid::Grid& g) { g.snap = ! g.snap; }));
  5371. menu.addSeparator();
  5372. menu.addItem (tr ("Narrow Grid") + "\tCtrl+1", true, false, change ([] (livegrid::Grid& g) { livegrid::narrower (g); }));
  5373. menu.addItem (tr ("Widen Grid") + "\tCtrl+2", true, false, change ([] (livegrid::Grid& g) { livegrid::wider (g); }));
  5374. menu.addSeparator();
  5375. menu.addItem (tr ("Quantize") + "\tCtrl+U", onLiveQuantize != nullptr, false, [safe] { if (safe != nullptr && safe->onLiveQuantize != nullptr) safe->onLiveQuantize(); });
  5376. menu.addItem (tr ("Quantize Settings...") + "\tCtrl+Shift+U", onLiveQuantizeSettings != nullptr, false, [safe] {
  5377. if (safe != nullptr && safe->onLiveQuantizeSettings != nullptr)
  5378. safe->onLiveQuantizeSettings();
  5379. });
  5380. return menu;
  5381. }
  5382. bool PianoRollComponent::runAction (const std::string& id)
  5383. {
  5384. auto is = [&id] (const char* name) { return id == name; };
  5385. // round 190hr: the reference's grid and quantize keys, only while docked in the Clip-launch detail view
  5386. if (id.rfind ("pianoRoll.live", 0) == 0)
  5387. {
  5388. if (! liveGridOn())
  5389. return false;
  5390. if (is ("pianoRoll.liveGridNarrower")) livegrid::narrower (liveGrid);
  5391. else if (is ("pianoRoll.liveGridWider")) livegrid::wider (liveGrid);
  5392. else if (is ("pianoRoll.liveGridTriplet")) liveGrid.triplet = ! liveGrid.triplet;
  5393. else if (is ("pianoRoll.liveGridSnap")) liveGrid.snap = ! liveGrid.snap;
  5394. else if (is ("pianoRoll.liveGridFixed")) liveGrid.fixed = ! liveGrid.fixed;
  5395. else if (is ("pianoRoll.liveQuantize") && onLiveQuantize != nullptr) onLiveQuantize();
  5396. else if (is ("pianoRoll.liveQuantizeSettings") && onLiveQuantizeSettings != nullptr) onLiveQuantizeSettings();
  5397. else
  5398. return false;
  5399. resized();
  5400. repaint();
  5401. return true;
  5402. }
  5403. if (is ("pianoRoll.arpeggiate")) openNoteTool (NoteTool::arpeggiate);
  5404. else if (is ("pianoRoll.strum")) openNoteTool (NoteTool::strum);
  5405. else if (is ("pianoRoll.flip")) openNoteTool (NoteTool::flip);
  5406. else if (is ("pianoRoll.randomise")) openNoteTool (NoteTool::randomise);
  5407. else if (is ("pianoRoll.scaleLevels")) openNoteTool (NoteTool::scaleLevels);
  5408. else if (is ("pianoRoll.limit")) openNoteTool (NoteTool::limit);
  5409. else if (is ("pianoRoll.quantize")) openNoteTool (NoteTool::quantize);
  5410. else if (is ("pianoRoll.chop")) openNoteTool (NoteTool::chop);
  5411. else if (is ("pianoRoll.flam")) openNoteTool (NoteTool::flam);
  5412. else if (is ("pianoRoll.claw")) openNoteTool (NoteTool::claw);
  5413. else if (is ("pianoRoll.lfo")) openNoteTool (NoteTool::lfo);
  5414. else if (is ("pianoRoll.articulate")) openNoteTool (NoteTool::articulate);
  5415. else if (is ("pianoRoll.riffMachine")) openNoteTool (NoteTool::riffMachine);
  5416. else if (is ("pianoRoll.chordProgression")) openNoteTool (NoteTool::chordProgression);
  5417. else if (is ("pianoRoll.chordHelper")) openChordHelper();
  5418. else if (is ("pianoRoll.runLastScript")) runLastScript();
  5419. else if (is ("pianoRoll.zoomIn")) zoomAroundCentre (1.25);
  5420. else if (is ("pianoRoll.zoomOut")) zoomAroundCentre (1.0 / 1.25);
  5421. else if (is ("pianoRoll.zoom1")) zoomToBars (1);
  5422. else if (is ("pianoRoll.zoom2")) zoomToBars (4);
  5423. else if (is ("pianoRoll.zoom3")) zoomToBars (16);
  5424. else if (is ("pianoRoll.zoomAll")) zoomAll();
  5425. else if (is ("pianoRoll.zoomSelection")) zoomToSelection();
  5426. else if (is ("pianoRoll.previousView")) previousView(); // round 190qe (D2-PL8)
  5427. else if (is ("pianoRoll.restoreSelection")) restoreSelection(); // round 190qe (D2-PL9)
  5428. else if (is ("pianoRoll.centrePlayhead")) centreOnPlayhead();
  5429. else if (is ("pianoRoll.follow")) EditorGlobals::get().setFollowing (true, ! EditorGlobals::get().isFollowing (true));
  5430. else if (is ("pianoRoll.eventPaneAlternate")) toggleEventPaneAlternate(); // FL's Shift+Enter (round 190fz)
  5431. else if (is ("pianoRoll.quantizeStarts")) quantizeOperation (0);
  5432. else if (is ("pianoRoll.quickQuantize")) quantizeOperation (1);
  5433. else if (is ("pianoRoll.quantizeHalf")) quantizeOperation (2);
  5434. else if (is ("pianoRoll.colourSelected")) colourSelection (noteColour);
  5435. else if (is ("pianoRoll.selectByColour"))
  5436. {
  5437. // the colour of the selected note (FL: the selection's colour), else the current note colour
  5438. const auto& notes = currentPattern (engine.getSong()).notes;
  5439. selectByColour (! selection.empty() && selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].colour : noteColour);
  5440. }
  5441. else if (is ("pianoRoll.invertSelection")) setSelection (notetools::invertSelection (channelNotes(), selection));
  5442. // round 168g: FL's View / Select / Stamp / Edit / File items
  5443. else if (is ("pianoRoll.gridHighlights"))
  5444. {
  5445. gridHighlights = ! gridHighlights;
  5446. if (EditorGlobals::get().onOptionsChanged)
  5447. EditorGlobals::get().onOptionsChanged();
  5448. repaint();
  5449. }
  5450. else if (is ("pianoRoll.backgroundWave")) setBackgroundWaveShown (! isBackgroundWaveShown());
  5451. else if (is ("pianoRoll.songBarsRuler"))
  5452. {
  5453. songBarsRuler = ! songBarsRuler;
  5454. if (EditorGlobals::get().onOptionsChanged)
  5455. EditorGlobals::get().onOptionsChanged();
  5456. repaint();
  5457. }
  5458. else if (is ("pianoRoll.stackedLanes")) // round 190on (P10): Settings › LYNX extras, the View menu
  5459. {
  5460. stackedLanesExtra = ! stackedLanesExtra;
  5461. if (EditorGlobals::get().onOptionsChanged)
  5462. EditorGlobals::get().onOptionsChanged();
  5463. stackedLanesChanged();
  5464. }
  5465. else if (is ("pianoRoll.showChordName"))
  5466. {
  5467. showChordName = ! showChordName;
  5468. chordBubbleSelection.clear(); // shows the current selection's chord at once
  5469. if (EditorGlobals::get().onOptionsChanged)
  5470. EditorGlobals::get().onOptionsChanged();
  5471. updateChordBubble();
  5472. }
  5473. else if (is ("pianoRoll.selectRandomOne") || is ("pianoRoll.selectRandomMore"))
  5474. setSelection (noteedit::selectRandomMore (currentPattern (engine.getSong()), channelNotes(), selection, is ("pianoRoll.selectRandomMore"),
  5475. (std::uint32_t) juce::Random::getSystemRandom().nextInt()));
  5476. else if (is ("pianoRoll.selectOddSteps"))
  5477. setSelection (noteedit::selectOddSteps (currentPattern (engine.getSong()), channelNotes(), selection, ticksPerStep));
  5478. else if (is ("pianoRoll.stampNone")) chordBox.setSelectedId (1, juce::sendNotificationSync);
  5479. else if (is ("pianoRoll.scaleSnap"))
  5480. {
  5481. if (scaleIndex() > 0) // (like its menu item and button: only with a scale chosen)
  5482. setScaleSnap (! scaleSnap);
  5483. }
  5484. else if (is ("pianoRoll.insertSpace")) spaceOperation (0);
  5485. else if (is ("pianoRoll.sliceInsertSpace")) spaceOperation (1);
  5486. else if (is ("pianoRoll.deleteSpace")) spaceOperation (2);
  5487. else if (is ("pianoRoll.trimSpace")) spaceOperation (3);
  5488. else if (is ("pianoRoll.deleteAll")) deleteAllNotes();
  5489. else if (is ("pianoRoll.insertControllerValue")) insertControllerValue();
  5490. else if (is ("pianoRoll.importMidi") || is ("pianoRoll.openScore"))
  5491. {
  5492. // FL: Import MIDI and Open score share one file window (FUN_0120b340): .fsc, .mid or both
  5493. const auto score = is ("pianoRoll.openScore");
  5494. chooser = lynx::ui::makeFileChooser (score ? tr ("Open score") : tr ("Import MIDI"), juce::File(),
  5495. score ? "*.fsc;*.mid;*.midi" : "*.mid;*.midi");
  5496. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  5497. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  5498. if (safe != nullptr && fc.getResult().existsAsFile())
  5499. safe->loadFile (fc.getResult());
  5500. });
  5501. }
  5502. else if (is ("pianoRoll.exportMidi"))
  5503. {
  5504. const auto& song = engine.getSong();
  5505. const auto name = juce::String::fromUTF8 (song.activePattern().name.c_str());
  5506. chooser = lynx::ui::makeFileChooser (tr ("Export MIDI"), juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (name + ".mid"),
  5507. "*.mid");
  5508. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  5509. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  5510. auto file = fc.getResult();
  5511. if (safe == nullptr || file == juce::File())
  5512. return;
  5513. if (! file.hasFileExtension ("mid;midi"))
  5514. file = file.withFileExtension (".mid");
  5515. juce::String error;
  5516. if (! MidiFileIo::savePattern (safe->engine.getSong(), safe->engine.getSong().currentPattern, file, error))
  5517. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  5518. });
  5519. }
  5520. else if (is ("pianoRoll.saveScore"))
  5521. {
  5522. const auto channel = engine.getSelectedChannel();
  5523. const auto& song = engine.getSong();
  5524. auto name = channel >= 0 && channel < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str())
  5525. : juce::String ("Score");
  5526. chooser = lynx::ui::makeFileChooser (tr ("Save score as"),
  5527. juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (juce::File::createLegalFileName (name) + ".fsc"),
  5528. "*.fsc;*.mid");
  5529. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  5530. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  5531. auto file = fc.getResult();
  5532. if (safe == nullptr || file == juce::File())
  5533. return;
  5534. if (! file.hasFileExtension ("fsc;mid;midi"))
  5535. file = file.withFileExtension (".fsc");
  5536. if (! safe->saveScore (file))
  5537. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Save score as"),
  5538. tr ("There are no notes to save, or the file could not be written."));
  5539. });
  5540. }
  5541. else if (is ("pianoRoll.copyMidiClipboard")) copyToMidiClipboard();
  5542. else if (is ("pianoRoll.pasteMidiClipboard")) pasteFromMidiClipboard();
  5543. else if (is ("pianoRoll.markerAdd")) editPatternMarker (markerKeyTick(), -1);
  5544. else if (is ("pianoRoll.markerAuto"))
  5545. {
  5546. const auto tick = snap ((double) markerKeyTick(), true);
  5547. if (std::none_of (currentPattern (engine.getSong()).markers.begin(), currentPattern (engine.getSong()).markers.end(),
  5548. [tick] (const Marker& m) { return m.tick == tick; })) // (FL keeps the marker there, no undo step)
  5549. engine.editSong ([tick] (Song& s) { noteedit::addPatternAutoMarker (currentPattern (s), tick); });
  5550. repaint();
  5551. }
  5552. else if (is ("pianoRoll.markerSignature")) addPatternSignatureByKey();
  5553. else if (is ("pianoRoll.browseScores"))
  5554. {
  5555. if (onBrowseScores)
  5556. onBrowseScores();
  5557. }
  5558. else if (is ("pianoRoll.groupNotes") || is ("pianoRoll.ungroupNotes"))
  5559. {
  5560. const auto target = selection;
  5561. if (target.empty())
  5562. return true;
  5563. const auto group = is ("pianoRoll.groupNotes");
  5564. editNotes ([&] (Pattern& p) {
  5565. if (group)
  5566. notetools::groupNotes (p, target);
  5567. else
  5568. notetools::ungroupNotes (p, target);
  5569. });
  5570. repaint();
  5571. }
  5572. else
  5573. return false;
  5574. return true;
  5575. }
  5576. void PianoRollComponent::wheelNoteProperty (int note, float deltaY, bool fine, juce::Point<int> mouse)
  5577. {
  5578. // FL 2026 [SHOT round 166e]: the whole selection wherever the mouse is, else the one note
  5579. const auto targets = note < 0 ? selection : std::vector<int> { note };
  5580. if (targets.empty())
  5581. return;
  5582. const auto now = juce::Time::getMillisecondCounter();
  5583. const auto newBurst = now - lastWheelEdit > 700; // one undo step per burst of wheel moves
  5584. lastWheelEdit = now;
  5585. editNotes ([&] (Pattern& p) {
  5586. for (auto i : targets)
  5587. {
  5588. auto& n = p.notes[(std::size_t) i];
  5589. setLaneValue (n, (float) gesture::wheelStepValue (laneValue (n), deltaY, fine));
  5590. }
  5591. if (laneIsChance())
  5592. notetools::spreadGroupChance (p, targets);
  5593. }, newBurst);
  5594. // hear it (FL previews the single note; the selection's nearest note too is LYNX's own, issue #16) and a single
  5595. // note becomes the template for new notes (FL)
  5596. const auto& notes = currentPattern (engine.getSong()).notes;
  5597. const auto heard = note >= 0 ? note : noteedit::nearestNote (notes, targets, xToTick (mouse.x), yToKey (mouse.y), pixelsPerTick, rowHeight);
  5598. if (heard < 0 || heard >= (int) notes.size())
  5599. return;
  5600. const auto& n = notes[(std::size_t) heard];
  5601. if (note >= 0)
  5602. noteTemplate.takeFrom (n);
  5603. previewEdit (n.key, n.velocity);
  5604. const auto serial = ++wheelPreviewSerial;
  5605. juce::Timer::callAfterDelay (180, [safe = juce::Component::SafePointer<PianoRollComponent> (this), serial] {
  5606. if (safe != nullptr && safe->wheelPreviewSerial == serial && safe->drag == Drag::none)
  5607. safe->previewOff();
  5608. });
  5609. }
  5610. void PianoRollComponent::glideBy (double ticks, double pixels, bool immediate)
  5611. {
  5612. if (! gliding)
  5613. {
  5614. glideX.jumpTo (scrollTicks);
  5615. glideY.jumpTo (scrollY);
  5616. gliding = true;
  5617. }
  5618. const auto grid = gridArea();
  5619. glideX.target = juce::jlimit (0.0, juce::jmax (0.0, (double) viewLengthTicks() - grid.getWidth() / pixelsPerTick), glideX.target + ticks);
  5620. glideY.target = juce::jlimit (0.0, juce::jmax (0.0, (double) rows.count * rowHeight - grid.getHeight()), glideY.target + pixels);
  5621. if (immediate || ! ui::motion::enabled()) // (Settings › General › Animations off: the wheel jumps)
  5622. {
  5623. scrollTicks = glideX.target;
  5624. scrollY = (int) std::round (glideY.target);
  5625. gliding = false;
  5626. updateScrollBars();
  5627. glideX.jumpTo (scrollTicks);
  5628. glideY.jumpTo (scrollY);
  5629. repaint();
  5630. return;
  5631. }
  5632. vblank.start(); // the next frames at the display's refresh (round 190gv: no vertical blanks while still)
  5633. glideFrame();
  5634. }
  5635. void PianoRollComponent::glideFrame()
  5636. {
  5637. if (! gliding)
  5638. return;
  5639. // someone else moved the view (scroll bar, zoom, pan): the glide gives way
  5640. if (std::abs (scrollTicks - glideX.current) > 1e-6 || std::abs ((double) scrollY - std::round (glideY.current)) > 0.5)
  5641. {
  5642. gliding = false;
  5643. return;
  5644. }
  5645. scrollTicks = glideX.step (0.45, 0.5 / pixelsPerTick);
  5646. scrollY = (int) std::round (glideY.step (0.45, 1.0));
  5647. glideY.current = scrollY;
  5648. updateScrollBars();
  5649. glideX.current = scrollTicks; // the scroll bar may have clamped it
  5650. gliding = glideX.isMoving() || glideY.isMoving();
  5651. repaint();
  5652. }
  5653. // Round 190pm (research190oe P23, ui/TouchInput.h): Touch mode's gestures on the Piano roll. A long press on a note opens
  5654. // its properties (the Note inspector, as a double click; FL's right click deletes: that stays on the mouse's right button),
  5655. // in the grid elsewhere the Piano roll's menu, outside the grid the right click there; two fingers pan (Simple layout) and
  5656. // a pinch zooms the time around their centre.
  5657. void PianoRollComponent::touchLongPress (const juce::MouseEvent& rightClick)
  5658. {
  5659. if (gridArea().contains (rightClick.getPosition()))
  5660. {
  5661. bool edge = false;
  5662. if (const auto hit = noteAt (rightClick.x, rightClick.y, edge); hit >= 0)
  5663. {
  5664. const auto indices = isSelected (hit) ? selection : std::vector<int> { hit };
  5665. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) hit];
  5666. const auto area = juce::Rectangle<int> ((int) tickToX ((double) n.start), keyToY (n.key), juce::jmax (8, (int) (n.length * pixelsPerTick)), rowHeight);
  5667. lastTouchActionForSnapshot = "note inspector " + juce::String (hit);
  5668. if (! ui::showingForShots())
  5669. showNoteInspector (engine, indices, hit, localAreaToGlobal (area));
  5670. return;
  5671. }
  5672. lastTouchActionForSnapshot = "menu";
  5673. if (! ui::showingForShots())
  5674. moreMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withTargetScreenArea (
  5675. juce::Rectangle<int> (1, 1).withPosition (localPointToGlobal (rightClick.getPosition()))));
  5676. return;
  5677. }
  5678. lastTouchActionForSnapshot = "right click";
  5679. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  5680. mouseDown (rightClick);
  5681. if (safe != nullptr)
  5682. mouseUp (rightClick);
  5683. }
  5684. void PianoRollComponent::touchPan (float dx, float dy)
  5685. {
  5686. settleViewGlide(); // (rollup 0.1.32 step 2: 190pm's touch gestures land 190qe's zoom glide first, as the wheel and pinch do)
  5687. gliding = false;
  5688. scrollTicks = juce::jmax (0.0, scrollTicks - (double) dx / pixelsPerTick);
  5689. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), scrollY - juce::roundToInt (dy));
  5690. updateScrollBars();
  5691. repaint();
  5692. }
  5693. void PianoRollComponent::touchPinch (float scale, juce::Point<float> centre)
  5694. {
  5695. settleViewGlide(); // (rollup 0.1.32 step 2: 190pm's touch gestures land 190qe's zoom glide first, as the wheel and pinch do)
  5696. gliding = false;
  5697. const auto anchorPixels = (double) juce::jmax (0.0f, centre.x - (float) keyboardWidth);
  5698. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, pixelsPerTick * (double) scale);
  5699. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  5700. pixelsPerTick = zoomed;
  5701. updateScrollBars();
  5702. repaint();
  5703. }
  5704. void PianoRollComponent::mouseMagnify (const juce::MouseEvent& e, float scale)
  5705. {
  5706. settleViewGlide(); // (round 190qe: a zoom glide lands first)
  5707. gliding = false;
  5708. const auto factor = gesture::pinchZoomFactor (scale);
  5709. if (e.mods.isAltDown()) // taller / shorter keys, keeping the key under the pointer in place
  5710. {
  5711. const auto key = yToKey (e.y);
  5712. const auto offset = e.y - keyToY (key);
  5713. const auto height = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, juce::roundToInt (rowHeight * factor));
  5714. rowHeight = height != rowHeight ? height : juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, rowHeight + (factor > 1.0 ? 1 : factor < 1.0 ? -1 : 0));
  5715. scrollY = juce::jmax (0, rowFor (key) * rowHeight + offset - (e.y - headerHeight));
  5716. }
  5717. else
  5718. {
  5719. const auto anchorPixels = (double) juce::jmax (0, e.x - keyboardWidth);
  5720. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, pixelsPerTick * factor);
  5721. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  5722. pixelsPerTick = zoomed;
  5723. }
  5724. updateScrollBars();
  5725. repaint();
  5726. }
  5727. PianoRollComponent::NoteOnScreen PianoRollComponent::firstVisibleNoteForSnapshot (int skip, juce::Point<int> near) const
  5728. {
  5729. const auto& notes = currentPattern (engine.getSong()).notes;
  5730. const auto grid = gridArea().reduced (8);
  5731. NoteOnScreen best;
  5732. for (const auto i : channelNotes())
  5733. {
  5734. const auto& n = notes[(std::size_t) i];
  5735. if (const auto r = noteRect (n.start, n.length, n.key).toNearestInt(); grid.contains (r) && i != skip)
  5736. {
  5737. if (skip < 0)
  5738. return { i, r };
  5739. if (best.index < 0 || r.getCentre().getDistanceFrom (near) < best.bounds.getCentre().getDistanceFrom (near))
  5740. best = { i, r };
  5741. }
  5742. }
  5743. return best;
  5744. }
  5745. void PianoRollComponent::showToolModeMenu()
  5746. {
  5747. drag = Drag::none;
  5748. setMouseCursor (juce::MouseCursor::NormalCursor);
  5749. toolModeMenu (tools, [this] (EditTool t) { tools.setTool (t); }, mainMenu != nullptr ? mainMenu() : juce::PopupMenu())
  5750. .showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  5751. }
  5752. void PianoRollComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& rawWheel)
  5753. {
  5754. settleViewGlide(); // (round 190qe: a zoom glide lands first)
  5755. const LaneScope laneScope (*this, stackedLaneAt (e.getPosition())); // (round 190on)
  5756. const auto wheel = flmods::normalisedWheel (rawWheel); // Windows touchpads: pieces of a notch (round 170e)
  5757. // FL's right-hold + wheel (round 190mp, DE-61; capture 190mp A3.3): each notch down picks the next tool to the right,
  5758. // up the one to the left, stopping at the ends; the held press does nothing more (no erase stroke, no knife, nothing
  5759. // on release)
  5760. if (e.mods.isRightButtonDown() && ! e.mods.isLeftButtonDown() && ! e.mods.isMiddleButtonDown())
  5761. {
  5762. if (wheel.deltaY != 0.0f)
  5763. {
  5764. drag = Drag::none;
  5765. tools.step (wheel.deltaY < 0.0f ? 1 : -1);
  5766. }
  5767. return;
  5768. }
  5769. const auto ctrl = flmods::ctrl (e.mods), alt = e.mods.isAltDown(), shift = e.mods.isShiftDown();
  5770. const auto overGrid = gridArea().contains (e.getPosition()) || velocityArea().contains (e.getPosition());
  5771. // issue #254 (round 190ou): a notch of the horizontal wheel (a tilt wheel, a second wheel) moves the view 1.5 beats
  5772. // sideways whatever the zoom, as in FL 2026 (a trackpad's swipe and Shift+wheel keep their own ways below)
  5773. if (! ctrl && ! alt)
  5774. if (const auto notch = gesture::horizontalWheelNotch (wheel.deltaX, wheel.deltaY, wheel.isSmooth, shift); notch != 0)
  5775. {
  5776. gliding = false;
  5777. glideBy (notch * gesture::horizontalWheelBeats * ppq, 0.0);
  5778. return;
  5779. }
  5780. // the wheel over the zoom wheel: one zoom level a notch (FL: the only wheel gesture of the vertical zoom)
  5781. if (zoomWheelArea().contains (e.getPosition()))
  5782. {
  5783. if (wheel.deltaY != 0.0f)
  5784. {
  5785. const auto key = zoomAnchorKey();
  5786. setRowHeightAround (rowHeight + (wheel.deltaY > 0 ? 2 : -2), key, keyToY (key) + rowHeight / 2);
  5787. }
  5788. return;
  5789. }
  5790. // Alt+wheel: the velocity (or the lane's property) of the selected notes wherever the mouse is, with nothing
  5791. // selected of the note nearest to the mouse (FL 2026, round 166e); Ctrl+Alt: fine steps
  5792. if (alt && ! shift && overGrid && wheel.deltaY != 0.0f)
  5793. {
  5794. auto note = -1;
  5795. if (selection.empty())
  5796. {
  5797. note = hoverAt (e.getPosition()).note;
  5798. if (note < 0)
  5799. note = noteedit::nearestNote (currentPattern (engine.getSong()).notes, channelNotes(), xToTick (e.x), yToKey (e.y), pixelsPerTick,
  5800. velocityArea().contains (e.getPosition()) ? 0.0 : rowHeight);
  5801. }
  5802. if (note >= 0 || ! selection.empty())
  5803. {
  5804. wheelNoteProperty (note, wheel.deltaY, ctrl, e.getPosition());
  5805. return;
  5806. }
  5807. }
  5808. if (shift && alt) // nudge the selection by the grid
  5809. {
  5810. if (wheel.deltaY != 0.0f && ! selection.empty())
  5811. {
  5812. const auto now = juce::Time::getMillisecondCounter();
  5813. const auto newBurst = now - lastWheelEdit > 700;
  5814. lastWheelEdit = now;
  5815. const auto ticks = (wheel.deltaY > 0 ? 1 : -1) * gridTicks();
  5816. editNotes ([this, ticks] (Pattern& p) {
  5817. auto deltaTicks = ticks;
  5818. auto deltaKeys = 0;
  5819. noteedit::move (p, selection, deltaTicks, deltaKeys);
  5820. }, newBurst);
  5821. sortNotes();
  5822. }
  5823. return;
  5824. }
  5825. gliding = false;
  5826. if (ctrl && alt)
  5827. {
  5828. // vertical zoom keeping the key under the mouse in place
  5829. const auto key = yToKey (e.y);
  5830. const auto offset = e.y - keyToY (key);
  5831. rowHeight = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, rowHeight + (wheel.deltaY > 0 ? 2 : -2));
  5832. scrollY = juce::jmax (0, rowFor (key) * rowHeight + offset - (e.y - headerHeight));
  5833. }
  5834. else if (ctrl)
  5835. {
  5836. // zoom keeping the tick under the mouse in place (issue #276, round 190qr: with the LYNX extra "Zoom around the
  5837. // song position", the playhead when it is in view)
  5838. const auto anchorPixels = zoomanchor::anchorX (zoomanchor::atSongPosition() && playheadTick >= 0.0, (double) juce::jmax (0, e.x - keyboardWidth),
  5839. tickToX (playheadTick) - keyboardWidth, 0.0, (double) gridArea().getWidth());
  5840. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, maxPixelsPerTick, pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  5841. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  5842. pixelsPerTick = zoomed;
  5843. }
  5844. else
  5845. {
  5846. // plain wheel: up/down (Shift: left/right); a horizontal wheel or trackpad swipe scrolls sideways
  5847. const auto vertical = gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 3.0 * rowHeight);
  5848. const auto sideways = gesture::wheelScrollPixels (wheel.deltaX, wheel.isSmooth, 60.0);
  5849. if (shift)
  5850. glideBy (gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 80.0) / pixelsPerTick, 0.0, wheel.isSmooth);
  5851. else
  5852. glideBy (sideways / pixelsPerTick, vertical, wheel.isSmooth); // a trackpad moves the view at once
  5853. return;
  5854. }
  5855. updateScrollBars();
  5856. repaint();
  5857. }
  5858. // --- keyboard ----------------------------------------------------------------
  5859. void PianoRollComponent::deleteSelection()
  5860. {
  5861. if (selection.empty())
  5862. return;
  5863. const auto doomed = selection;
  5864. fadeOut (doomed); // (issue #250)
  5865. setSelection ({});
  5866. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  5867. }
  5868. void PianoRollComponent::fadeOut (const std::vector<int>& notes)
  5869. {
  5870. // issue #250 (round 190oq): each deleted note in view leaves FL's ghost (nothing at all when Animations are off or
  5871. // effects reduced: ui/DeleteFade.h)
  5872. if (! ui::DeleteFade::enabled())
  5873. return;
  5874. const auto& pattern = currentPattern (engine.getSong());
  5875. const auto grid = gridArea().toFloat();
  5876. for (const auto i : notes)
  5877. if (i >= 0 && i < (int) pattern.notes.size())
  5878. {
  5879. const auto& n = pattern.notes[(std::size_t) i];
  5880. if (const auto r = noteRect (n.start, n.length, n.key); r.intersects (grid))
  5881. deleteFade.add (r, theme::noteGroupColour (n.colour, n.velocity));
  5882. }
  5883. }
  5884. void PianoRollComponent::paintOverChildren (juce::Graphics& g)
  5885. {
  5886. deleteFade.paint (g, gridArea()); // (issue #250: nothing while no note is fading)
  5887. }
  5888. void PianoRollComponent::copySelection()
  5889. {
  5890. clipboard = noteedit::copy (currentPattern (engine.getSong()), selectionOrAll());
  5891. publishNotes();
  5892. }
  5893. // issue #232 stage 2 (round 190nz): the note clipboard also on the system clipboard, for another LYNX SHARE window
  5894. void PianoRollComponent::publishNotes()
  5895. {
  5896. if (! windowclip::enabled() || clipboard.empty())
  5897. return;
  5898. crossclipboard::Payload copy;
  5899. copy.kind = crossclipboard::Kind::notes;
  5900. copy.notes = clipboard;
  5901. windowclip::publish (std::move (copy));
  5902. }
  5903. // Pain point 26 (round 177d, LYNX's own; FL's ghost notes can only be looked at): the ghost notes on show (the other
  5904. // channels' notes in this pattern, and this channel's notes in the clips that play at the same time) go to the note
  5905. // clipboard, so Ctrl+V pastes them into the channel being edited, where they were drawn.
  5906. std::vector<Note> PianoRollComponent::visibleGhostNotes() const
  5907. {
  5908. std::vector<Note> out;
  5909. if (! showGhosts || allChannels)
  5910. return out;
  5911. const auto& song = engine.getSong();
  5912. for (const auto& n : currentPattern (song).notes)
  5913. if (! edits (n) && ghostShown (n.channel))
  5914. out.push_back (n);
  5915. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, engine.getSelectedChannel()))
  5916. out.push_back (n);
  5917. std::stable_sort (out.begin(), out.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  5918. return out;
  5919. }
  5920. void PianoRollComponent::copyGhostNotes()
  5921. {
  5922. auto ghosts = visibleGhostNotes();
  5923. if (ghosts.empty())
  5924. return;
  5925. const auto count = (int) ghosts.size();
  5926. clipboard = std::move (ghosts);
  5927. publishNotes();
  5928. ui::postHint ({ tr ("Copied {0} ghost notes: Ctrl+V pastes them into this channel", { juce::String (count) }) }, 2500);
  5929. }
  5930. void PianoRollComponent::paste()
  5931. {
  5932. // issue #232 (round 190nz): notes copied in another LYNX SHARE window paste here, on the channel being edited
  5933. auto incoming = windowclip::incoming (crossclipboard::Kind::notes);
  5934. if (incoming && ! incoming->notes.empty())
  5935. clipboard = incoming->notes;
  5936. else
  5937. incoming.reset();
  5938. if (clipboard.empty())
  5939. return;
  5940. // issue #211 (round 190mq): where the notes go depends on the layout (core/PastePlace.h): FL's rule in the Pattern
  5941. // layout (the part of the pattern in view), Live's insert marker in Clip-launch, the playhead in Simple. Pasted
  5942. // notes are selected, ready to drag.
  5943. const auto offset = pasteOffset();
  5944. std::vector<int> added;
  5945. // ("All": each note keeps its channel; another window's notes go on the channel being edited)
  5946. const auto channel = allChannels && ! incoming ? -1 : engine.getSelectedChannel();
  5947. editNotes ([&added, channel, offset] (Pattern& p) {
  5948. added = noteedit::paste (p, clipboard, offset, channel);
  5949. notetools::regroup (p, added); // copies of grouped notes form groups of their own
  5950. });
  5951. setSelection (added);
  5952. sortNotes();
  5953. if (incoming)
  5954. ui::postHint ({ windowclip::pastedFrom (*incoming) }, 2500);
  5955. }
  5956. std::int64_t PianoRollComponent::pasteOffset() const
  5957. {
  5958. if (clipboard.empty())
  5959. return 0;
  5960. pasteplace::Where w;
  5961. w.first = clipboard.front().start;
  5962. for (const auto& n : clipboard)
  5963. w.first = std::min (w.first, n.start);
  5964. w.rulerMark = rulerMark;
  5965. w.grid = gridTicks();
  5966. w.viewFrom = (std::int64_t) std::max (0.0, scrollTicks);
  5967. w.viewTo = (std::int64_t) xToTick (gridArea().getRight());
  5968. if (timeFrom >= 0 && timeTo > timeFrom)
  5969. w.selection = timeFrom;
  5970. // the song position in this pattern (the playhead while it plays; stopped, where it would start)
  5971. const auto& song = engine.getSong();
  5972. const auto position = playheadTick >= 0.0 ? playheadTick
  5973. : transportedit::patternPlayhead (song, song.currentPattern, engine.getTransport().positionTicks.load(),
  5974. engine.patternLinearOrigin());
  5975. if (position >= 0.0)
  5976. w.position = snap (position, true);
  5977. const auto rule = pasteplace::ruleFor (layoutstyle::current());
  5978. return pasteplace::start (rule, w, pasteplace::UniformBars { song.barTicks() }) - w.first;
  5979. }
  5980. void PianoRollComponent::duplicateSelection()
  5981. {
  5982. const auto source = selectionOrAll();
  5983. if (source.empty())
  5984. return;
  5985. std::vector<int> added;
  5986. const auto meter = engine.getSong().meter();
  5987. editNotes ([&added, &source, meter] (Pattern& p) {
  5988. added = noteedit::duplicateBars (p, source, meter); // FL: whole bars later (round 170h)
  5989. notetools::regroup (p, added);
  5990. });
  5991. setSelection (added);
  5992. sortNotes();
  5993. }
  5994. void PianoRollComponent::quantizeOperation (int kind)
  5995. {
  5996. const auto grid = gridTicks();
  5997. runOperation ([grid, kind] (Pattern& p, const std::vector<int>& t) {
  5998. if (kind == 1)
  5999. noteedit::quantizeFull (p, t, grid);
  6000. else
  6001. transportedit::quantizeNoteStarts (p, t, grid, kind == 2 ? 0.5 : 1.0);
  6002. return t;
  6003. });
  6004. }
  6005. void PianoRollComponent::nudge (std::int64_t ticks, int keys)
  6006. {
  6007. if (selection.empty())
  6008. return;
  6009. // folded to the scale (round 166d): Up / Down step through the shown keys (an octave stays an octave)
  6010. if (folded() && keys != 0 && std::abs (keys) < 12)
  6011. {
  6012. editNotes ([this, &ticks, keys] (Pattern& p) {
  6013. auto noKeys = 0;
  6014. noteedit::move (p, selection, ticks, noKeys);
  6015. for (auto i : selection)
  6016. if (i >= 0 && i < (int) p.notes.size())
  6017. p.notes[(std::size_t) i].key = rows.step (p.notes[(std::size_t) i].key, keys);
  6018. });
  6019. }
  6020. else
  6021. {
  6022. if (keys == 1 || keys == -1) // snap to scale: up / down step along the scale (every selected note, issue #14)
  6023. if (const auto scale = snapScale(); scale.active())
  6024. {
  6025. editNotes ([this, keys, scale] (Pattern& p) { scalesnap::moveBySteps (p, selection, keys, scale); });
  6026. keys = 0;
  6027. if (ticks == 0)
  6028. {
  6029. sortNotes();
  6030. return;
  6031. }
  6032. }
  6033. editNotes ([this, &ticks, &keys] (Pattern& p) { noteedit::move (p, selection, ticks, keys); });
  6034. }
  6035. if (keys != 0 && selection.size() == 1)
  6036. {
  6037. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) selection[0]];
  6038. previewEdit (n.key, n.velocity);
  6039. juce::Timer::callAfterDelay (150, [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  6040. if (safe != nullptr)
  6041. safe->previewOff();
  6042. });
  6043. }
  6044. sortNotes();
  6045. }
  6046. bool PianoRollComponent::handleKey (const juce::KeyPress& key)
  6047. {
  6048. // round 190im (R15): a key that changed the song is an edit by hand: Follow pauses (when that option is on)
  6049. const juce::ScopeGuard followEdit { [this, before = engine.getPublishCount()] {
  6050. EditorGlobals::get().pauseFollowIfEdited (EditorGlobals::FollowView::pianoRoll, before, engine.getPublishCount());
  6051. } };
  6052. const auto mods = key.getModifiers();
  6053. const auto cmd = mods.isCommandDown();
  6054. const auto alt = mods.isAltDown();
  6055. const auto shift = mods.isShiftDown();
  6056. const auto code = key.getKeyCode();
  6057. const auto letter = keys::letterOfKeyCode (code); // (0 for F-keys, numpad, arrows: issue #12)
  6058. const auto grid = gridTicks();
  6059. const auto bar = engine.getSong().barTicks();
  6060. // round 190hr: the Clip-launch layout's docked editor takes the reference's grid keys (Ctrl+1…5) and Quantize
  6061. // (Ctrl+U / Ctrl+Shift+U) before the FL editor's own (FL's Ctrl+U chop stays in the Pattern layout)
  6062. if (liveGridOn() && cmd && ! alt)
  6063. {
  6064. const char* live = nullptr;
  6065. if (letter == 'U')
  6066. live = shift ? "pianoRoll.liveQuantizeSettings" : "pianoRoll.liveQuantize";
  6067. else if (! shift && code >= '1' && code <= '5')
  6068. {
  6069. static constexpr const char* gridKeys[] { "pianoRoll.liveGridNarrower", "pianoRoll.liveGridWider", "pianoRoll.liveGridTriplet",
  6070. "pianoRoll.liveGridSnap", "pianoRoll.liveGridFixed" };
  6071. live = gridKeys[code - '1'];
  6072. }
  6073. if (live != nullptr && runAction (live))
  6074. return true;
  6075. }
  6076. // (issue #219, round 190ng: Backspace's snap on / off is the key map's playlist.snapToggle / pianoRoll.snapToggle now, so it
  6077. // can be given another key)
  6078. if (code == juce::KeyPress::deleteKey && ! cmd) // (Ctrl+Shift+Del: pattern.delete; Ctrl+Del: pianoRoll.deleteSpace)
  6079. {
  6080. deleteSelection();
  6081. return true;
  6082. }
  6083. if (code == juce::KeyPress::escapeKey)
  6084. {
  6085. // (issue #217, round 190ng: an Esc with nothing selected is left to the main window, which closes the Piano roll as FL)
  6086. if (selection.empty() && timeFrom < 0)
  6087. return false;
  6088. setSelection ({});
  6089. setTimeSelection (-1, -1);
  6090. return true;
  6091. }
  6092. if (alt && cmd && letter == 'V') // editable ghost notes
  6093. {
  6094. editGhosts = ! editGhosts;
  6095. if (editGhosts && ! showGhosts)
  6096. ghostButton.setToggleState (true, juce::sendNotificationSync);
  6097. repaint();
  6098. return true;
  6099. }
  6100. if (alt && ! cmd && letter == 'V')
  6101. {
  6102. ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync);
  6103. return true;
  6104. }
  6105. if (cmd && alt && code == juce::KeyPress::homeKey)
  6106. {
  6107. resizeFromLeft = ! resizeFromLeft;
  6108. return true;
  6109. }
  6110. if (cmd && letter == 'A')
  6111. {
  6112. selectAll();
  6113. return true;
  6114. }
  6115. if (cmd && ! shift && letter == 'C') // (Ctrl+Shift+C: pattern.clone)
  6116. {
  6117. copySelection();
  6118. return true;
  6119. }
  6120. if (cmd && letter == 'X')
  6121. {
  6122. copySelection();
  6123. deleteSelection();
  6124. return true;
  6125. }
  6126. if (cmd && ! shift && letter == 'V') // (Ctrl+Shift+V: pianoRoll.pasteMidiClipboard)
  6127. {
  6128. paste();
  6129. return true;
  6130. }
  6131. if (cmd && letter == 'B')
  6132. {
  6133. duplicateSelection();
  6134. return true;
  6135. }
  6136. // quick note operations: one undo step each, on the selection (or all notes). The quantize ones are key map
  6137. // actions (pianoRoll.quickQuantize / quantizeStarts / quantizeHalf) so they can be reassigned.
  6138. if (cmd && letter == 'U')
  6139. {
  6140. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); });
  6141. return true;
  6142. }
  6143. if (cmd && letter == 'G')
  6144. {
  6145. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; });
  6146. return true;
  6147. }
  6148. if (cmd && letter == 'L')
  6149. {
  6150. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; });
  6151. return true;
  6152. }
  6153. if (shift && ! cmd && ! alt && letter == 'D')
  6154. {
  6155. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::shrinkToGrid (p, t, grid); return t; });
  6156. return true;
  6157. }
  6158. if (cmd && shift && (code == juce::KeyPress::leftKey || code == juce::KeyPress::rightKey))
  6159. {
  6160. const auto steps = code == juce::KeyPress::rightKey ? 1 : -1;
  6161. runOperation ([grid, bar, steps] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, steps); return t; });
  6162. return true;
  6163. }
  6164. // FL's editor keys (ShortcutsModule EEMuteAction / EEUnmuteAction / EEDeselAction, round 167j): Alt+M mutes,
  6165. // Shift+Alt+M unmutes, Ctrl+D deselects. (Ctrl+M stays FL's metronome.)
  6166. if (alt && ! cmd && letter == 'M')
  6167. {
  6168. auto mute = ! shift;
  6169. // issue #249 (round 190oq, LYNX extra, off = FL): Alt+M on notes that are all muted unmutes them
  6170. if (mute && mutekeys::toggles())
  6171. {
  6172. const auto& notes = currentPattern (engine.getSong()).notes;
  6173. const auto target = selectionOrAll();
  6174. mute = target.empty() || ! std::all_of (target.begin(), target.end(), [&notes] (int i) {
  6175. return i >= 0 && i < (int) notes.size() && notes[(std::size_t) i].muted;
  6176. });
  6177. }
  6178. setNotesMuted (mute);
  6179. return true;
  6180. }
  6181. if (cmd && ! alt && ! shift && letter == 'D')
  6182. {
  6183. setSelection ({});
  6184. setTimeSelection (-1, -1);
  6185. rulerMark = -1;
  6186. return true;
  6187. }
  6188. if (cmd && letter == 'P')
  6189. {
  6190. togglePorta();
  6191. return true;
  6192. }
  6193. // FL's editor arrow keys (noteedit::arrowMove): Shift+Up/Down a semitone, Ctrl+Up/Down an octave,
  6194. // Shift+Left/Right one grid step
  6195. if (! selection.empty())
  6196. {
  6197. using noteedit::Arrow;
  6198. const auto arrow = code == juce::KeyPress::upKey ? std::optional<Arrow> (Arrow::up)
  6199. : code == juce::KeyPress::downKey ? std::optional<Arrow> (Arrow::down)
  6200. : code == juce::KeyPress::leftKey ? std::optional<Arrow> (Arrow::left)
  6201. : code == juce::KeyPress::rightKey ? std::optional<Arrow> (Arrow::right)
  6202. : std::nullopt;
  6203. if (arrow)
  6204. if (const auto move = noteedit::arrowMove (*arrow, cmd, shift, alt); move.handled)
  6205. {
  6206. nudge (move.gridSteps * grid, move.keys);
  6207. return true;
  6208. }
  6209. }
  6210. // (the tools and the other single letters are key map actions now: runKeyAction, issue #12)
  6211. return false;
  6212. }
  6213. bool PianoRollComponent::runKeyAction (const std::string& id)
  6214. {
  6215. for (const auto& t : editTools())
  6216. if (t.tool != EditTool::slip && id == "pianoRoll.tool." + std::string (editToolId (t.tool)))
  6217. {
  6218. tools.setTool (t.tool);
  6219. return true;
  6220. }
  6221. if (id == "pianoRoll.slide") slideButton.setToggleState (! slideButton.getToggleState(), juce::dontSendNotification);
  6222. else if (id == "pianoRoll.previousChannel") stepChannel (-1, false);
  6223. else if (id == "pianoRoll.nextChannel") stepChannel (1, false);
  6224. else if (id == "pianoRoll.previousChannelWithNotes") stepChannel (-1, true);
  6225. else if (id == "pianoRoll.nextChannelWithNotes") stepChannel (1, true);
  6226. else return false;
  6227. return true;
  6228. }
  6229. void PianoRollComponent::refreshToolKeys (const std::function<juce::String (const std::string&)>& keyOf)
  6230. {
  6231. tools.refreshKeys ([&keyOf] (EditTool t) { return keyOf ("pianoRoll.tool." + std::string (editToolId (t))); });
  6232. // round 179a: the slide toggle is only an icon, so its tips name its key the way the tool buttons do
  6233. const auto slideKey = keyOf ("pianoRoll.slide");
  6234. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)")
  6235. + (slideKey.isNotEmpty() ? " (" + slideKey + ")" : juce::String()));
  6236. ui::setQuickTip (slideButton, tr ("Slide notes"), slideKey);
  6237. }
  6238. juce::PopupMenu PianoRollComponent::midiMenu()
  6239. {
  6240. juce::PopupMenu menu;
  6241. menu.addItem (tr ("Import .mid into this channel...") + keyText ("pianoRoll.importMidi"), [this] { runAction ("pianoRoll.importMidi"); });
  6242. menu.addItem (tr ("Export pattern as .mid...") + keyText ("pianoRoll.exportMidi"), [this] { runAction ("pianoRoll.exportMidi"); });
  6243. return menu;
  6244. }
  6245. void PianoRollComponent::importMidi (const midiimport::ParsedMidi& midi, const juce::String& name)
  6246. {
  6247. // FL's "Import MIDI data" window with Blend (REA round 146b): which tracks / channels / controller
  6248. auto& remembered = channelMidiImportOptions(); // (round 190qj: shared with the Channel rack's drop)
  6249. juce::Component::SafePointer<PianoRollComponent> safe (this);
  6250. showMidiImportDialog (name, midi, remembered, true, [safe, midi] (const midiimport::Options& o) {
  6251. channelMidiImportOptions() = o;
  6252. if (safe == nullptr)
  6253. return;
  6254. std::vector<int> added;
  6255. std::string err;
  6256. const auto channel = safe->engine.getSelectedChannel();
  6257. safe->engine.editSong ([&] (Song& s) { added = midiimport::importIntoChannel (s, channel, midi, o, err); });
  6258. if (added.empty())
  6259. {
  6260. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", juce::String::fromUTF8 (err.c_str()));
  6261. return;
  6262. }
  6263. safe->knownNoteCount = currentPattern (safe->engine.getSong()).notes.size();
  6264. safe->setSelection (added);
  6265. safe->scrollToNotes();
  6266. safe->repaint();
  6267. });
  6268. }
  6269. // --- other -------------------------------------------------------------------
  6270. void PianoRollComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
  6271. {
  6272. if (bar == &hBar)
  6273. scrollTicks = start;
  6274. else
  6275. scrollY = (int) start;
  6276. repaint();
  6277. }
  6278. void PianoRollComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  6279. {
  6280. // pattern/channel switched or the pattern changed externally (undo, another window): the selection no longer applies
  6281. const auto& song = engine.getSong();
  6282. const auto count = currentPattern (song).notes.size();
  6283. if (song.currentPattern != knownPattern || engine.getSelectedChannel() != knownChannel || count != knownNoteCount)
  6284. {
  6285. if (engine.getSelectedChannel() != knownChannel)
  6286. {
  6287. stopListening();
  6288. if (knownChannel >= 0)
  6289. allChannels = false; // another channel picked (Channel Rack, keys): back to it alone
  6290. }
  6291. if (song.currentPattern != knownPattern)
  6292. {
  6293. timeFrom = timeTo = -1; // (the time selection belongs to the pattern it was made in)
  6294. rulerMark = -1;
  6295. }
  6296. knownPattern = song.currentPattern;
  6297. knownChannel = engine.getSelectedChannel();
  6298. knownNoteCount = count;
  6299. if (drag == Drag::none)
  6300. selection.clear();
  6301. }
  6302. followButton.setToggleState (EditorGlobals::get().isFollowing (true), juce::dontSendNotification);
  6303. syncPadRows();
  6304. refreshChannelBox();
  6305. rebuildLaneBox();
  6306. updateScrollBars();
  6307. repaint();
  6308. }
  6309. std::optional<AutomationTarget> PianoRollComponent::eventLaneTarget() const
  6310. {
  6311. const auto k = laneId() - eventLaneIdBase;
  6312. if (k >= 0 && k < (int) eventTargets.size())
  6313. return eventTargets[(std::size_t) k];
  6314. return std::nullopt;
  6315. }
  6316. void PianoRollComponent::rebuildLaneBox (std::optional<AutomationTarget> shown, bool force)
  6317. {
  6318. // the pattern's event lanes, plus the one shown (it may have no events yet)
  6319. if (! shown)
  6320. shown = eventLaneTarget();
  6321. std::vector<AutomationTarget> targets;
  6322. for (const auto& lane : currentPattern (engine.getSong()).events)
  6323. if (lane.target.kind != AutomationTargetKind::none && ! lane.events.empty())
  6324. targets.push_back (lane.target);
  6325. if (shown && std::find (targets.begin(), targets.end(), *shown) == targets.end())
  6326. targets.push_back (*shown);
  6327. for (const auto& l : stacked) // (round 190on: the stacked lanes' targets too, even with no event yet)
  6328. if (l->spec.target && std::find (targets.begin(), targets.end(), *l->spec.target) == targets.end())
  6329. targets.push_back (*l->spec.target);
  6330. if (targets == eventTargets && ! force)
  6331. return;
  6332. eventTargets = targets;
  6333. const auto previous = laneBox.getSelectedId();
  6334. laneBox.clear (juce::dontSendNotification);
  6335. addNoteLanes();
  6336. if (! eventTargets.empty())
  6337. laneBox.addSectionHeading (tr ("Pattern events"));
  6338. for (int k = 0; k < (int) eventTargets.size(); ++k)
  6339. laneBox.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
  6340. auto id = previous >= 1 && previous <= laneLast ? previous : 1;
  6341. if (shown)
  6342. id = eventLaneIdBase + (int) (std::find (eventTargets.begin(), eventTargets.end(), *shown) - eventTargets.begin());
  6343. laneBox.setSelectedId (id, juce::dontSendNotification);
  6344. rebuildStackedBoxes(); // (round 190on: their lists hold the same event lanes)
  6345. }
  6346. void PianoRollComponent::showEventLane (const AutomationTarget& target)
  6347. {
  6348. rebuildLaneBox (target, true);
  6349. repaint();
  6350. }
  6351. void PianoRollComponent::drawEvents (int fromX, int toX, int y, bool erase)
  6352. {
  6353. const auto target = eventLaneTarget();
  6354. if (! target)
  6355. return;
  6356. const auto lane = velocityArea();
  6357. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8));
  6358. const auto step = std::max<std::int64_t> (1, gridTicks());
  6359. const auto t0 = std::max<std::int64_t> (0, (std::int64_t) std::floor (xToTick (juce::jmin (fromX, toX)) / (double) step) * step);
  6360. const auto t1 = std::max (t0 + step, (std::int64_t) std::floor (xToTick (juce::jmax (fromX, toX)) / (double) step) * step + step);
  6361. const auto pattern = engine.getSong().currentPattern;
  6362. engine.editSong ([&] (Song& s) {
  6363. if (pattern < 0 || pattern >= (int) s.patterns.size())
  6364. return;
  6365. auto& p = s.patterns[(std::size_t) pattern];
  6366. if (erase)
  6367. {
  6368. if (auto* l = eventedit::findLane (p, *target))
  6369. eventedit::erase (*l, t0, t1);
  6370. eventedit::removeEmptyLanes (p);
  6371. }
  6372. else
  6373. eventedit::fill (eventedit::laneFor (p, *target), t0, t1, value, step);
  6374. });
  6375. repaint (velocityArea());
  6376. }
  6377. NoteMask PianoRollComponent::soundingNow() const
  6378. {
  6379. if (! allChannels)
  6380. return engine.soundingKeys (engine.getSelectedChannel());
  6381. // "All": every channel with notes in this pattern
  6382. NoteMask all {};
  6383. const auto& song = engine.getSong();
  6384. std::vector<char> seen (song.channels.size(), 0);
  6385. for (const auto& n : currentPattern (song).notes)
  6386. if (n.channel >= 0 && n.channel < (int) seen.size() && ! seen[(std::size_t) n.channel])
  6387. {
  6388. seen[(std::size_t) n.channel] = 1;
  6389. const auto k = engine.soundingKeys (n.channel);
  6390. all[0] |= k[0], all[1] |= k[1];
  6391. }
  6392. if (const auto selected = engine.getSelectedChannel(); selected >= 0 && selected < (int) seen.size() && ! seen[(std::size_t) selected])
  6393. {
  6394. const auto k = engine.soundingKeys (selected);
  6395. all[0] |= k[0], all[1] |= k[1];
  6396. }
  6397. return all;
  6398. }
  6399. void PianoRollComponent::timerCallback()
  6400. {
  6401. if (holdRing && hold != Hold::none) // round 190mr (DE-63): the hold ring grows
  6402. repaint (holdRingArea());
  6403. if (channelBox.getSelectedId() != (allChannels ? allChannelsId : engine.getSelectedChannel() + 1))
  6404. refreshChannelBox();
  6405. updateChordReadout();
  6406. // round 190pf (P13): the rows follow the Chord lane's chord at the song position (a check of two ints per tick)
  6407. if (chordlane::pianoRollHighlight())
  6408. {
  6409. const auto& song = engine.getSong();
  6410. const auto now = song.chords().empty() ? chordlane::Highlight {}
  6411. : chordlane::highlightAt (song, (std::int64_t) engine.getTransport().positionTicks.load());
  6412. if (now != shownChord)
  6413. {
  6414. shownChord = now;
  6415. repaint();
  6416. }
  6417. }
  6418. else if (shownChord.root >= 0)
  6419. {
  6420. shownChord = {};
  6421. repaint();
  6422. }
  6423. // the keys the channel plays light up on the keyboard (song, pattern, typing keyboard, MIDI)
  6424. if (const auto lit = isShowing() ? soundingNow() : NoteMask {}; lit != litKeys)
  6425. {
  6426. litKeys = lit;
  6427. repaint (0, headerHeight, keyboardWidth, getHeight() - headerHeight);
  6428. }
  6429. if (const bool playing = engine.getTransport().playing.load(); playButton.getToggleState() != playing)
  6430. playButton.setToggleState (playing, juce::dontSendNotification);
  6431. }
  6432. // round 190ip: the playhead as paint() draws it (the line in the grid, the triangle in the ruler), for the GPU overlay
  6433. void PianoRollComponent::paintPlayheadAt (juce::Graphics& g, float x)
  6434. {
  6435. const auto grid = gridArea();
  6436. g.setColour (theme::colour::playhead);
  6437. {
  6438. juce::Graphics::ScopedSaveState state (g);
  6439. if (g.reduceClipRegion (grid))
  6440. g.drawVerticalLine ((int) x, (float) grid.getY(), (float) grid.getBottom());
  6441. }
  6442. juce::Graphics::ScopedSaveState state (g);
  6443. if (g.reduceClipRegion (juce::Rectangle<int> (keyboardWidth, rulerTop, grid.getWidth(), timelineHeight)))
  6444. {
  6445. juce::Path tri;
  6446. tri.addTriangle (x - 5, (float) rulerTop, x + 5, (float) rulerTop, x, (float) rulerTop + 8);
  6447. g.fillPath (tri);
  6448. }
  6449. }
  6450. ui::MotionOverlay::Mark PianoRollComponent::playheadMark() const
  6451. {
  6452. const auto grid = gridArea();
  6453. ui::MotionOverlay::Mark m;
  6454. m.x = (float) tickToX (playheadTick);
  6455. m.extent = juce::Rectangle<int>::leftTopRightBottom (-7, rulerTop, 7, grid.getBottom());
  6456. m.clip = juce::Rectangle<int>::leftTopRightBottom (grid.getX(), rulerTop, grid.getRight(), grid.getBottom());
  6457. m.look = ((std::uint64_t) (std::uint32_t) theme::colour::playhead.getARGB() << 32) ^ ((std::uint64_t) (std::uint32_t) grid.getY() << 20)
  6458. ^ (std::uint64_t) (std::uint32_t) grid.getHeight() ^ ((std::uint64_t) (std::uint32_t) keyboardWidth << 44);
  6459. return m;
  6460. }
  6461. juce::Rectangle<int> PianoRollComponent::playheadColumn (double tick) const
  6462. {
  6463. return tick >= 0.0 ? juce::Rectangle<int> ((int) tickToX (tick) - 7, 0, 14, getHeight()) : juce::Rectangle<int>();
  6464. }
  6465. bool PianoRollComponent::playheadFrame (double nowMs)
  6466. {
  6467. const auto feel = feelFrame (nowMs); // round 190qe: the edge scroll of a drag, the zoom glide
  6468. auto& transport = engine.getTransport();
  6469. auto tick = -1.0;
  6470. const auto playing = transport.playing.load();
  6471. // round 190im (R15): a scroll by hand while playing (sideways, same zoom, not by Follow) pauses Follow
  6472. auto& globals = EditorGlobals::get();
  6473. globals.noteTransport (playing);
  6474. if (playing && scrollTicks != followSeenScroll && pixelsPerTick == followSeenZoom)
  6475. globals.pauseFollowForScroll (EditorGlobals::FollowView::pianoRoll);
  6476. followSeenScroll = scrollTicks;
  6477. followSeenZoom = pixelsPerTick;
  6478. // the playhead shows while the edited pattern plays: Pattern mode, or a clip of it in Song mode (round 162);
  6479. // stopped in Step edit too (round 170e5): it is where the next played note goes (FL enters step-edit notes at the
  6480. // song position, which it draws in the Piano roll), and it moves a snap step on after each one
  6481. if ((playing || engine.isStepEdit()) && ui::showingOrShot (*this))
  6482. {
  6483. const auto& song = engine.getSong();
  6484. // (between two audio blocks it moves on at the song's tempo: smooth at 144 Hz, round 174e)
  6485. tick = transportedit::patternPlayhead (song, song.currentPattern, transport.positionTicks.load() + engine.playheadAdvanceTicks(),
  6486. engine.patternLinearOrigin());
  6487. // round 190im (R13, DL-74): docked in the Clip View for a clip of the grid, the clip's own position while it is
  6488. // launched (Live's manual 8.7) wins over the Playlist's
  6489. if (launchedPlayhead != nullptr)
  6490. if (const auto launched = launchedPlayhead(); launched >= 0.0)
  6491. tick = launched;
  6492. }
  6493. // whenever it moved: the line is anti-aliased, so even a fraction of a pixel shows (zoomed out, a playhead crossing
  6494. // a few pixels a second glides at the display's rate instead of stepping, as FL's does)
  6495. const auto moved = (tick < 0.0) != (playheadTick < 0.0) || std::abs ((tick - playheadTick) * pixelsPerTick) >= 0.002;
  6496. // round 190ip: stopped (step edit keeps it), the playhead is painted again; the overlay goes once that is on screen
  6497. if (gpuPlayhead.isShowing() && (! playing || ! isShowing()))
  6498. {
  6499. gpuPlayhead.hide (tick >= 0.0 && isShowing()); // (gone or no longer shown: at once)
  6500. repaint (playheadColumn (playheadTick));
  6501. }
  6502. if (moved)
  6503. {
  6504. // (old and new column as one rectangle when they overlap: each rectangle of a repaint is a paint)
  6505. auto column = [this] (double t) { return playheadColumn (t); };
  6506. auto dirty = [this] (juce::Rectangle<int> r) {
  6507. if (! r.isEmpty())
  6508. repaint (r);
  6509. };
  6510. const auto before = column (playheadTick);
  6511. playheadTick = tick;
  6512. // while playing the GPU moves it (nothing under it is painted); the frame that starts or ends, the columns are
  6513. // painted once
  6514. const auto gpu = ui::stepMark (gpuPlayhead, playing && tick >= 0.0 && isShowing(), playheadMark(), tick >= 0.0);
  6515. // Follow: a page further when the playhead leaves the view (off: the view stays where it is)
  6516. const auto grid = gridArea();
  6517. // (Pattern mode loops the pattern: the view holds still at its end and comes back in one jump at the wrap;
  6518. // a take with Loop record off, and Song mode, go on past it: plain paging)
  6519. const auto& followSong = engine.getSong();
  6520. const auto loops = followSong.mode == PlayMode::pattern && engine.patternLinearOrigin() < 0.0 && followSong.currentPattern >= 0
  6521. && followSong.currentPattern < (int) followSong.patterns.size();
  6522. const auto loopTicks = loops ? (double) followSong.activePattern().effectiveLength (followSong.meter()) : 0.0;
  6523. const auto newStart = transportedit::followViewStartInLoop (scrollTicks, grid.getWidth() / pixelsPerTick, tick, 20.0 / pixelsPerTick,
  6524. 20.0 / pixelsPerTick, loopTicks);
  6525. if (EditorGlobals::get().followsNow (EditorGlobals::FollowView::pianoRoll) && tick >= 0.0 && newStart != scrollTicks && drag == Drag::none)
  6526. {
  6527. scrollTicks = newStart;
  6528. followSeenScroll = scrollTicks; // (round 190im: not a scroll by hand)
  6529. updateScrollBars();
  6530. repaint();
  6531. if (gpuPlayhead.isShowing())
  6532. gpuPlayhead.show (playheadMark()); // (at its place in the new page)
  6533. }
  6534. else if (gpu.onOverlay && ! gpu.flipped)
  6535. {
  6536. // (the GPU moved it: nothing under it is painted)
  6537. }
  6538. else if (const auto after = column (tick); ! before.isEmpty() && ! after.isEmpty() && std::abs (after.getX() - before.getX()) <= 14)
  6539. dirty (before.getUnion (after));
  6540. else
  6541. {
  6542. dirty (before);
  6543. dirty (after);
  6544. }
  6545. }
  6546. // round 177d: the notes held in a take grow with the playhead (only their rows, from their start)
  6547. if (engine.isLiveRecording() && isShowing())
  6548. {
  6549. juce::Rectangle<int> area;
  6550. for (const auto& n : engine.liveRecording().held)
  6551. {
  6552. const auto x0 = (int) tickToX ((double) n.start) - 2;
  6553. const auto x1 = juce::jmax (x0 + 8, (int) tickToX ((double) (n.start + n.length)) + 8);
  6554. area = area.getUnion (juce::Rectangle<int> (x0, keyToY (n.key), x1 - x0, rowHeight + 1));
  6555. }
  6556. const auto dirty = area.getUnion (liveHeldArea).getIntersection (gridArea());
  6557. liveHeldArea = area;
  6558. if (! dirty.isEmpty())
  6559. repaint (dirty);
  6560. }
  6561. else if (! liveHeldArea.isEmpty())
  6562. {
  6563. repaint (liveHeldArea);
  6564. liveHeldArea = {};
  6565. }
  6566. return playing || moved || feel;
  6567. }
  6568. // --- round 168g: FL's Piano roll File / Edit / View items ----------------------------------------------------------------
  6569. void PianoRollComponent::setTimeSelection (std::int64_t from, std::int64_t to)
  6570. {
  6571. if (from < 0 || to <= from)
  6572. from = to = -1;
  6573. if (from == timeFrom && to == timeTo)
  6574. return;
  6575. timeFrom = from;
  6576. timeTo = to;
  6577. repaint();
  6578. }
  6579. void PianoRollComponent::spaceOperation (int kind)
  6580. {
  6581. // FL needs a time selection for these (FUN_00eb35f0: nothing without one)
  6582. if (timeFrom < 0 || timeTo <= timeFrom)
  6583. {
  6584. ui::postHint ({ tr ("Select a time range on the ruler first (Ctrl+drag)") }, 2000);
  6585. return;
  6586. }
  6587. std::vector<int> channel;
  6588. const auto& notes = currentPattern (engine.getSong()).notes;
  6589. for (int i = 0; i < (int) notes.size(); ++i)
  6590. if (edits (notes[(std::size_t) i]))
  6591. channel.push_back (i);
  6592. const auto from = timeFrom, to = timeTo;
  6593. const auto& song = engine.getSong();
  6594. const auto end = currentPattern (song).effectiveLength (song.meter());
  6595. const auto who = allChannels ? -1 : engine.getSelectedChannel();
  6596. std::vector<int> moved;
  6597. setSelection ({});
  6598. editNotes ([&] (Pattern& p) {
  6599. if (kind == 0 || kind == 1)
  6600. moved = noteedit::insertSpace (p, channel, from, to, kind == 1);
  6601. else if (kind == 2)
  6602. moved = noteedit::deleteSpace (p, channel, from, to);
  6603. else
  6604. noteedit::trimToSelection (p, who, from, to, end);
  6605. noteedit::sortTracking (p, moved);
  6606. });
  6607. if (kind == 3)
  6608. setTimeSelection (-1, -1); // (FL clears the time selection after a trim)
  6609. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  6610. setSelection (moved); // FL selects the notes that moved (FUN_00e3b1a0)
  6611. }
  6612. void PianoRollComponent::insertControllerValue()
  6613. {
  6614. // FL's Ctrl+I (EEInitAction → FUN_00eb38d0): the event lane's control, its current value, at the start of the
  6615. // time selection (or at the pattern's start)
  6616. const auto target = eventLaneTarget();
  6617. if (! target)
  6618. {
  6619. ui::postHint ({ tr ("Show a control's events in the bottom lane first (its box on the left)") }, 2000);
  6620. return;
  6621. }
  6622. const auto value = engine.getSong().targetValue (*target);
  6623. const auto at = timeFrom >= 0 ? timeFrom : (std::int64_t) 0;
  6624. engine.editSong ([&] (Song& s) { eventedit::setEvent (eventedit::laneFor (currentPattern (s), *target), at, value); });
  6625. repaint (velocityArea());
  6626. }
  6627. void PianoRollComponent::deleteAllNotes()
  6628. {
  6629. // FL's Edit › Delete all (FUN_00e3d230): every note of the edited channel in the pattern, one undo step
  6630. std::vector<int> doomed;
  6631. const auto& notes = currentPattern (engine.getSong()).notes;
  6632. for (int i = 0; i < (int) notes.size(); ++i)
  6633. if (edits (notes[(std::size_t) i]))
  6634. doomed.push_back (i);
  6635. if (doomed.empty())
  6636. return;
  6637. setSelection ({});
  6638. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  6639. }
  6640. bool PianoRollComponent::openScore (const juce::File& file)
  6641. {
  6642. juce::MemoryBlock bytes;
  6643. if (! file.loadFileAsData (bytes))
  6644. return false;
  6645. const auto score = prtools::parseScore (std::span<const std::uint8_t> (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize()));
  6646. if (! score)
  6647. return false;
  6648. const auto channel = engine.getSelectedChannel();
  6649. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  6650. return false;
  6651. // FL's score loading (FUN_00ff85c0): the channel's notes in the pattern are replaced by the score's
  6652. const auto loaded = prtools::notesFromScore (*score, channel);
  6653. std::vector<int> added;
  6654. setSelection ({});
  6655. editNotes ([&] (Pattern& p) {
  6656. std::vector<int> old;
  6657. for (int i = 0; i < (int) p.notes.size(); ++i)
  6658. if (p.notes[(std::size_t) i].channel == channel)
  6659. old.push_back (i);
  6660. noteedit::remove (p, old);
  6661. added = noteedit::paste (p, loaded, 0, channel);
  6662. noteedit::sortTracking (p, added);
  6663. });
  6664. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  6665. repaint();
  6666. return true;
  6667. }
  6668. bool PianoRollComponent::saveScore (const juce::File& file) const
  6669. {
  6670. // FL (FUN_0121b1b0): every note of the edited channel; "*.mid" in the same window saves a MIDI file
  6671. const auto& notes = currentPattern (engine.getSong()).notes;
  6672. std::vector<Note> mine;
  6673. for (const auto& n : notes)
  6674. if (n.channel == engine.getSelectedChannel())
  6675. mine.push_back (n);
  6676. if (mine.empty())
  6677. return false;
  6678. if (file.hasFileExtension ("mid;midi"))
  6679. {
  6680. const auto& song = engine.getSong();
  6681. const auto c = engine.getSelectedChannel();
  6682. const auto smf = MidiFileIo::writeNotes (song, mine, c >= 0 && c < (int) song.channels.size() ? song.channels[(std::size_t) c].name : std::string());
  6683. return file.replaceWithData (smf.getData(), smf.getSize());
  6684. }
  6685. const auto bytes = prtools::writeScore (mine);
  6686. return file.replaceWithData (bytes.data(), bytes.size());
  6687. }
  6688. void PianoRollComponent::setNoteClipboard (std::vector<Note> notes)
  6689. {
  6690. clipboard = std::move (notes);
  6691. publishNotes();
  6692. }
  6693. bool PianoRollComponent::copyToMidiClipboard() const
  6694. {
  6695. const auto& song = engine.getSong();
  6696. const auto c = engine.getSelectedChannel();
  6697. std::vector<Note> mine;
  6698. for (const auto& n : currentPattern (song).notes)
  6699. if (n.channel == c)
  6700. mine.push_back (n);
  6701. if (mine.empty())
  6702. return false;
  6703. const auto smf = MidiFileIo::writeNotes (song, mine, c >= 0 && c < (int) song.channels.size() ? song.channels[(std::size_t) c].name : std::string());
  6704. const auto ok = midiclipboard::put (smf);
  6705. ui::postHint ({ ok ? tr ("Copied {0} notes to the MIDI clipboard", { juce::String ((int) mine.size()) }) : tr ("The clipboard is busy: try again") }, 2000);
  6706. return ok;
  6707. }
  6708. void PianoRollComponent::pasteFromMidiClipboard()
  6709. {
  6710. const auto smf = midiclipboard::get();
  6711. if (! smf)
  6712. {
  6713. ui::postHint ({ tr ("There is no MIDI data in the clipboard") }, 2000);
  6714. return;
  6715. }
  6716. juce::String error;
  6717. const auto midi = MidiFileIo::parseBytes (smf->getData(), smf->getSize(), error);
  6718. if (! midi)
  6719. {
  6720. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", tr ("Error parsing the MIDI data..."));
  6721. return;
  6722. }
  6723. importMidi (*midi, tr ("MIDI from clipboard")); // (FL: the same "Import MIDI data" window, FUN_00e1d090)
  6724. }
  6725. bool PianoRollComponent::loadFile (const juce::File& file)
  6726. {
  6727. if (isScoreFile (file))
  6728. return openScore (file);
  6729. if (isMidiFile (file))
  6730. {
  6731. juce::String error;
  6732. const auto midi = MidiFileIo::parseFile (file, error);
  6733. if (! midi)
  6734. {
  6735. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  6736. return true;
  6737. }
  6738. importMidi (*midi, file.getFileName());
  6739. return true;
  6740. }
  6741. if (BrowserComponent::isAudioFile (file))
  6742. {
  6743. loadBackgroundWave (file);
  6744. return true;
  6745. }
  6746. return false;
  6747. }
  6748. bool PianoRollComponent::isInterestedInFileDrag (const juce::StringArray& files)
  6749. {
  6750. for (const auto& f : files)
  6751. if (const juce::File file (f); isScoreFile (file) || isMidiFile (file) || BrowserComponent::isAudioFile (file))
  6752. return true;
  6753. return false;
  6754. }
  6755. void PianoRollComponent::filesDropped (const juce::StringArray& files, int, int)
  6756. {
  6757. for (const auto& f : files)
  6758. if (loadFile (juce::File (f)))
  6759. return;
  6760. }
  6761. bool PianoRollComponent::isInterestedInDragSource (const juce::DragAndDropTarget::SourceDetails& details)
  6762. {
  6763. if (! BrowserComponent::isBrowserDrag (details))
  6764. return false;
  6765. const auto file = BrowserComponent::draggedFile (details);
  6766. return isScoreFile (file) || isMidiFile (file) || BrowserComponent::isAudioFile (file);
  6767. }
  6768. void PianoRollComponent::itemDropped (const juce::DragAndDropTarget::SourceDetails& details)
  6769. {
  6770. loadFile (BrowserComponent::draggedFile (details));
  6771. }
  6772. bool PianoRollComponent::isBackgroundWaveShown() noexcept
  6773. {
  6774. return backgroundWaveOn() && backgroundWave() != nullptr;
  6775. }
  6776. void PianoRollComponent::setBackgroundWaveShown (bool on)
  6777. {
  6778. backgroundWaveOn() = on;
  6779. if (on && backgroundWave() == nullptr)
  6780. ui::postHint ({ tr ("Drop an audio file on the Piano roll to see it as the background waveform") }, 2500);
  6781. repaint();
  6782. }
  6783. void PianoRollComponent::loadBackgroundWave (const juce::File& file)
  6784. {
  6785. // peaks (min / max per 256 samples, every channel) read off the message thread
  6786. juce::Component::SafePointer<PianoRollComponent> safe (this);
  6787. juce::Thread::launch ([file, safe] {
  6788. auto wave = std::make_shared<BackgroundWave>();
  6789. wave->file = file;
  6790. juce::AudioFormatManager formats;
  6791. registerAudioFormats (formats);
  6792. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (file)); reader != nullptr && reader->lengthInSamples > 0)
  6793. {
  6794. wave->sampleRate = reader->sampleRate > 0 ? reader->sampleRate : 44100.0;
  6795. wave->samples = juce::jmin<std::int64_t> (reader->lengthInSamples, (std::int64_t) (wave->sampleRate * 60.0 * 30.0)); // (30 min at most)
  6796. const auto channels = (int) juce::jlimit (1u, 8u, reader->numChannels);
  6797. constexpr int chunk = BackgroundWave::perPeak * 256;
  6798. juce::AudioBuffer<float> buffer (channels, chunk);
  6799. for (std::int64_t pos = 0; pos < wave->samples; pos += chunk)
  6800. {
  6801. const auto n = (int) juce::jmin<std::int64_t> (chunk, wave->samples - pos);
  6802. buffer.clear();
  6803. reader->read (&buffer, 0, n, pos, true, channels > 1);
  6804. for (int b = 0; b < n; b += BackgroundWave::perPeak)
  6805. {
  6806. auto lo = 0.0f, hi = 0.0f;
  6807. const auto m = juce::jmin (BackgroundWave::perPeak, n - b);
  6808. for (int c = 0; c < channels; ++c)
  6809. {
  6810. const auto range = juce::FloatVectorOperations::findMinAndMax (buffer.getReadPointer (c, b), m);
  6811. lo = juce::jmin (lo, range.getStart());
  6812. hi = juce::jmax (hi, range.getEnd());
  6813. }
  6814. wave->lo.push_back (lo);
  6815. wave->hi.push_back (hi);
  6816. }
  6817. }
  6818. }
  6819. juce::MessageManager::callAsync ([safe, wave] {
  6820. if (wave->lo.empty())
  6821. {
  6822. ui::postHint ({ tr ("This audio file could not be read") }, 2000);
  6823. return;
  6824. }
  6825. backgroundWave() = wave;
  6826. backgroundWaveOn() = true; // FL: loading one turns the view on (FUN_00ead950 (1))
  6827. if (safe != nullptr)
  6828. safe->repaint();
  6829. });
  6830. });
  6831. }
  6832. void PianoRollComponent::paintBackgroundWave (juce::Graphics& g, juce::Rectangle<int> grid)
  6833. {
  6834. const auto wave = backgroundWave();
  6835. if (! backgroundWaveOn() || wave == nullptr || wave->lo.empty())
  6836. return;
  6837. // FL (FUN_00e45a00): from the pattern's start, as long as the audio lasts at the song tempo, across the whole grid
  6838. // height (centred, 90% of the half height)
  6839. const auto& song = engine.getSong();
  6840. const auto ticksPerSecond = juce::jmax (1.0, song.bpm) / 60.0 * ppq;
  6841. const auto ticksPerPeak = BackgroundWave::perPeak / wave->sampleRate * ticksPerSecond;
  6842. const auto centre = (float) grid.getCentreY();
  6843. const auto amplitude = (float) grid.getHeight() * 0.5f * 0.9f;
  6844. const auto x0 = juce::jmax (grid.getX(), (int) std::floor (tickToX (0.0)));
  6845. const auto x1 = juce::jmin (grid.getRight(), (int) std::ceil (tickToX ((double) wave->lo.size() * ticksPerPeak)));
  6846. if (x1 <= x0)
  6847. return;
  6848. juce::RectangleList<float> bars;
  6849. for (int x = x0; x < x1; ++x)
  6850. {
  6851. const auto p0 = (std::int64_t) std::floor (xToTick (x) / ticksPerPeak);
  6852. const auto p1 = juce::jmax (p0 + 1, (std::int64_t) std::floor (xToTick (x + 1) / ticksPerPeak));
  6853. auto lo = 0.0f, hi = 0.0f;
  6854. for (auto p = juce::jmax<std::int64_t> (0, p0); p < juce::jmin<std::int64_t> ((std::int64_t) wave->lo.size(), p1); ++p)
  6855. {
  6856. lo = juce::jmin (lo, wave->lo[(std::size_t) p]);
  6857. hi = juce::jmax (hi, wave->hi[(std::size_t) p]);
  6858. }
  6859. const auto top = centre - juce::jlimit (0.0f, 1.0f, hi) * amplitude, bottom = centre - juce::jlimit (-1.0f, 0.0f, lo) * amplitude;
  6860. bars.addWithoutMerging ({ (float) x, top, 1.0f, juce::jmax (1.0f, bottom - top) });
  6861. }
  6862. g.setColour (theme::colour::textPrimary.withAlpha (0.16f));
  6863. g.fillRectList (bars);
  6864. }
  6865. juce::PopupMenu PianoRollComponent::fileMenu()
  6866. {
  6867. // FL's EEFileMenu (DFM): Open score, Browse scores, Save score as | Import / Export MIDI, Paste from / Copy to MIDI
  6868. // clipboard
  6869. juce::PopupMenu menu;
  6870. menu.addItem (theme::mnemonic (tr ("Open score..."), 'O') + keyText ("pianoRoll.openScore"), [this] { runAction ("pianoRoll.openScore"); });
  6871. menu.addItem (theme::mnemonic (tr ("Browse scores"), 'B') + keyText ("pianoRoll.browseScores"), onBrowseScores != nullptr, false, [this] { runAction ("pianoRoll.browseScores"); });
  6872. menu.addItem (theme::mnemonic (tr ("Save score as..."), 'S') + keyText ("pianoRoll.saveScore"), [this] { runAction ("pianoRoll.saveScore"); });
  6873. menu.addSeparator();
  6874. menu.addItem (theme::mnemonic (tr ("Import MIDI file..."), 'I') + keyText ("pianoRoll.importMidi"), [this] { runAction ("pianoRoll.importMidi"); });
  6875. menu.addItem (theme::mnemonic (tr ("Export as MIDI file..."), 'E') + keyText ("pianoRoll.exportMidi"), [this] { runAction ("pianoRoll.exportMidi"); });
  6876. menu.addItem (theme::mnemonic (tr ("Paste from MIDI clipboard..."), 'P') + keyText ("pianoRoll.pasteMidiClipboard"), midiclipboard::hasMidi(), false,
  6877. [this] { runAction ("pianoRoll.pasteMidiClipboard"); });
  6878. menu.addItem (theme::mnemonic (tr ("Copy to MIDI clipboard"), 'C') + keyText ("pianoRoll.copyMidiClipboard"), [this] { runAction ("pianoRoll.copyMidiClipboard"); });
  6879. return menu;
  6880. }
  6881. juce::PopupMenu PianoRollComponent::editMenu()
  6882. {
  6883. // FL's EEEditMenu, the items that apply to notes (DFM; Shift / Transpose = the arrow keys, round 167j)
  6884. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  6885. const auto grid = gridTicks();
  6886. juce::PopupMenu menu;
  6887. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", ! selection.empty(), false, [this] { copySelection(); deleteSelection(); });
  6888. menu.addItem (theme::mnemonic (tr ("Copy"), 'C') + "\tCtrl+C", [this] { copySelection(); });
  6889. menu.addItem (tr ("Copy ghost notes"), ! visibleGhostNotes().empty(), false, [this] { copyGhostNotes(); }); // (LYNX, round 177d)
  6890. menu.addItem (theme::mnemonic (tr ("Paste"), 'P') + "\tCtrl+V", ! clipboard.empty() || windowclip::hasIncoming (crossclipboard::Kind::notes), false,
  6891. [this] { paste(); });
  6892. menu.addItem (theme::mnemonic (tr ("Duplicate"), 'u') + "\tCtrl+B", [this] { duplicateSelection(); });
  6893. menu.addItem (theme::mnemonic (tr ("Delete"), 'D') + "\tDel", ! selection.empty(), false, [this] { deleteSelection(); });
  6894. menu.addItem (theme::mnemonic (tr ("Delete all"), 'a') + keyText ("pianoRoll.deleteAll"), [this] { runAction ("pianoRoll.deleteAll"); });
  6895. menu.addSeparator();
  6896. menu.addItem (tr ("Shift left") + "\tShift+Left", ! selection.empty(), false, [this, grid] { nudge (-grid, 0); });
  6897. menu.addItem (tr ("Shift right") + "\tShift+Right", ! selection.empty(), false, [this, grid] { nudge (grid, 0); });
  6898. menu.addItem (tr ("Transpose up") + "\tShift+Up", ! selection.empty(), false, [this] { nudge (0, 1); });
  6899. menu.addItem (tr ("Transpose down") + "\tShift+Down", ! selection.empty(), false, [this] { nudge (0, -1); });
  6900. menu.addItem (tr ("Transpose one octave up") + "\tCtrl+Up", ! selection.empty(), false, [this] { nudge (0, 12); });
  6901. menu.addItem (tr ("Transpose one octave down") + "\tCtrl+Down", ! selection.empty(), false, [this] { nudge (0, -12); });
  6902. menu.addSeparator();
  6903. menu.addItem (tr ("Insert space") + keyText ("pianoRoll.insertSpace"), hasTime, false, [this] { runAction ("pianoRoll.insertSpace"); });
  6904. menu.addItem (tr ("Slice & insert space") + keyText ("pianoRoll.sliceInsertSpace"), hasTime, false, [this] { runAction ("pianoRoll.sliceInsertSpace"); });
  6905. menu.addItem (tr ("Delete space") + keyText ("pianoRoll.deleteSpace"), hasTime, false, [this] { runAction ("pianoRoll.deleteSpace"); });
  6906. menu.addItem (tr ("Trim") + keyText ("pianoRoll.trimSpace"), hasTime, false, [this] { runAction ("pianoRoll.trimSpace"); });
  6907. menu.addSeparator();
  6908. menu.addItem (tr ("Insert current controller value") + keyText ("pianoRoll.insertControllerValue"), eventLaneTarget().has_value(), false,
  6909. [this] { runAction ("pianoRoll.insertControllerValue"); });
  6910. return menu;
  6911. }
  6912. juce::PopupMenu PianoRollComponent::stampMenu()
  6913. {
  6914. // the toolbar chord box's items, the chosen one ticked ("Note" = no stamp: single notes)
  6915. juce::PopupMenu menu;
  6916. for (int i = 0; i < chordBox.getNumItems(); ++i)
  6917. {
  6918. const auto id = chordBox.getItemId (i);
  6919. if (id == degreeStampId) // round 190nu: the Scale degree chord, its options beside it
  6920. {
  6921. menu.addItem (chordBox.getItemText (i), true, isDegreeStamp(), [this] { setDegreeStamp (true); });
  6922. menu.addSubMenu (tr ("Scale degree chord options"), degreeOptionsMenu());
  6923. menu.addSeparator();
  6924. continue;
  6925. }
  6926. menu.addItem (chordBox.getItemText (i) + (id == 1 ? keyText ("pianoRoll.stampNone") : juce::String()), true, chordBox.getSelectedId() == id,
  6927. [this, id] { chordBox.setSelectedId (id, juce::sendNotificationSync); });
  6928. }
  6929. return menu;
  6930. }
  6931. juce::PopupMenu PianoRollComponent::viewMenu()
  6932. {
  6933. // FL's EEViewMenu, its "Helpers" items (DFM)
  6934. juce::PopupMenu menu;
  6935. menu.addItem (tr ("Note grid highlights") + keyText ("pianoRoll.gridHighlights"), true, gridHighlights, [this] { runAction ("pianoRoll.gridHighlights"); });
  6936. menu.addSubMenu (tr ("Scale highlighting"), scaleHighlightMenu()); // (round 190jv; FL's EEAutoKeyMenu)
  6937. menu.addItem (tr ("Show chord name for selection") + keyText ("pianoRoll.showChordName"), true, showChordName,
  6938. [this] { runAction ("pianoRoll.showChordName"); });
  6939. menu.addItem (tr ("Background waveform") + keyText ("pianoRoll.backgroundWave"), true, isBackgroundWaveShown(),
  6940. [this] { runAction ("pianoRoll.backgroundWave"); });
  6941. menu.addItem (tr ("Ruler: song bars (LYNX)") + keyText ("pianoRoll.songBarsRuler"), true, songBarsRuler, [this] { runAction ("pianoRoll.songBarsRuler"); });
  6942. // round 190pf (research190oe P13): the rows light the Chord lane's chord at the song position
  6943. menu.addItem (tr ("Highlight the Chord lane's chord (LYNX)"), true, chordlane::pianoRollHighlight(), [this] {
  6944. workflowextras::setExtra ("pianoRoll.chordHighlight", ! chordlane::pianoRollHighlight());
  6945. repaint();
  6946. });
  6947. if (layoutstyle::current() != layoutstyle::Style::clipLaunch) // (round 190on: the Clip-launch layout always offers them)
  6948. menu.addItem (tr ("Stacked controller lanes (LYNX)") + keyText ("pianoRoll.stackedLanes"), true, stackedLanesExtra,
  6949. [this] { runAction ("pianoRoll.stackedLanes"); });
  6950. {
  6951. // round 190j (discussion #136): flat = LYNX's keyboard until round 190oo; "Piano keys" = FL 2026's own keyboard
  6952. // (the white keys meet behind the black ones, with lines only between B / C and E / F: flshots/fl-pr-keys-x3.png),
  6953. // the default since round 190oo (O-2); the lined piano keys stay as they were
  6954. juce::PopupMenu style;
  6955. const auto add = [this, &style] (const juce::String& name, pianokeys::Style value) {
  6956. style.addItem (name, true, keyStyle == value, [this, value] { setKeyStyle (value); });
  6957. };
  6958. add (tr ("Flat keys"), pianokeys::Style::flat);
  6959. add (tr ("Piano keys"), pianokeys::Style::fl);
  6960. add (tr ("Piano keys (lines between the white keys)"), pianokeys::Style::piano);
  6961. menu.addSubMenu (tr ("Keyboard style"), style);
  6962. }
  6963. if (const auto wave = backgroundWave())
  6964. menu.addItem (tr ("Remove the background waveform ({0})", { wave->file.getFileName() }), [this] {
  6965. backgroundWave().reset();
  6966. backgroundWaveOn() = false;
  6967. repaint();
  6968. });
  6969. return menu;
  6970. }
  6971. // FL's View › Scale highlighting (EEAutoKeyMenu, round 190jv): in FL's DFM order — "Root note" and the twelve roots,
  6972. // "Scale", Snap to scale, FL's Default / Black notes (LYNX: "No scale", the black-key rows) and Automatic; FL appends
  6973. // its Reference scales after the last of them, here LYNX's scale list (the toolbar scale box's). The roots apply to a
  6974. // chosen scale, so they wait for one.
  6975. juce::PopupMenu PianoRollComponent::scaleHighlightMenu()
  6976. {
  6977. juce::PopupMenu menu;
  6978. const auto scale = scaleIndex(), root = scaleRoot();
  6979. menu.addSectionHeader (tr ("Root note"));
  6980. for (int r = 0; r < 12; ++r)
  6981. menu.addItem (juce::String (notenames::pitchName (r)), scale > 0, scale > 0 && root == r, [this, r, scale] { setScale (r, scale); });
  6982. // issue #203 (round 190ll): FL draws the roots and the scales in two columns ("Root note" | "Scale"; live190cq
  6983. // curves190bw-05c-scale-highlighting-menu.png), the toolbar's scale box opens this menu too
  6984. menu.addColumnBreak();
  6985. menu.addSectionHeader (tr ("Scale"));
  6986. menu.addItem (tr ("Snap notes to the scale") + keyText ("pianoRoll.scaleSnap"), scale > 0, scaleSnap, [this] { setScaleSnap (! scaleSnap); });
  6987. // FL's radio group Default / Black notes / Automatic (round 190mq, issue #212: Default = no black-key rows)
  6988. menu.addItem (tr ("Default"), true, scaleBox.getSelectedId() == 1 && ! blackKeyRows, [this] {
  6989. blackKeyRows = false;
  6990. setScale (0, 0);
  6991. repaint();
  6992. });
  6993. menu.addItem (tr (notetools::scales()[0].name), true, scaleBox.getSelectedId() == 1 && blackKeyRows, [this] {
  6994. blackKeyRows = true;
  6995. setScale (0, 0);
  6996. repaint();
  6997. });
  6998. menu.addItem (tr ("Automatic"), true, isAutoScale(), [this] { setAutoScale (true); });
  6999. menu.addSeparator();
  7000. for (int s = 1; s < (int) notetools::scales().size(); ++s)
  7001. menu.addItem (tr (notetools::scales()[(std::size_t) s].name), true, scale == s, [this, s, root] { setScale (root, s); });
  7002. return menu;
  7003. }
  7004. // --- round 190nu: the Scale degree chord's ghost and its preview (core/KeyRegions.h) -----------------------------------
  7005. juce::Rectangle<int> PianoRollComponent::degreeGhostArea() const
  7006. {
  7007. if (degreeGhost.tick < 0 || degreeGhost.keys.empty())
  7008. return {};
  7009. const auto lo = *std::min_element (degreeGhost.keys.begin(), degreeGhost.keys.end());
  7010. const auto hi = *std::max_element (degreeGhost.keys.begin(), degreeGhost.keys.end());
  7011. const auto x = (int) tickToX ((double) degreeGhost.tick);
  7012. const auto w = juce::jmax (6, (int) ((double) degreeGhost.length * pixelsPerTick)) + 200; // (and its label)
  7013. return juce::Rectangle<int>::leftTopRightBottom (x - 2, keyToY (hi) - 22, x + w, keyToY (lo) + rowHeight + 22).getIntersection (gridArea());
  7014. }
  7015. void PianoRollComponent::clearDegreeGhost()
  7016. {
  7017. stopDegreeHear();
  7018. if (degreeGhost.tick < 0)
  7019. return;
  7020. repaint (degreeGhostArea());
  7021. degreeGhost = {};
  7022. }
  7023. void PianoRollComponent::updateDegreeGhost (juce::Point<int> at)
  7024. {
  7025. const auto tool = tools.getTool();
  7026. bool right = false;
  7027. if (! isDegreeStamp() || drag != Drag::none || ! gridArea().contains (at) || (tool != EditTool::pencil && tool != EditTool::brush)
  7028. || noteAt (at.x, at.y, right) >= 0)
  7029. return clearDegreeGhost();
  7030. DegreeGhost next;
  7031. next.tick = juce::jmax<std::int64_t> (0, snap (xToTick (at.x), true));
  7032. next.length = newNoteLength();
  7033. const auto clicked = yToKey (at.y);
  7034. next.keys = stampKeys (clicked, next.tick);
  7035. const auto scale = scaleDegreesAt (next.tick);
  7036. if (! scale.valid())
  7037. next.label = tr ("No key here: add a key marker (Time markers) or choose a scale");
  7038. else
  7039. {
  7040. int root = clicked;
  7041. const auto shape = keyregions::diatonicChord (scale, clicked, degreeSize, degreeInversion, root);
  7042. std::vector<int> keys;
  7043. for (const auto i : shape)
  7044. keys.push_back (root + i);
  7045. const auto numeral = keyregions::degreeNumeral (scale, root, keys, degreeSize);
  7046. const auto detected = prtools::detectChord (keys, notenames::currentFlats.load() || keyregions::prefersFlats (scale));
  7047. next.label = juce::String::fromUTF8 (numeral.c_str()) + (detected ? juce::String::fromUTF8 (" \xc2\xb7 ") + juce::String::fromUTF8 (detected->name.c_str()) : juce::String());
  7048. }
  7049. if (next.tick == degreeGhost.tick && next.keys == degreeGhost.keys && next.label == degreeGhost.label)
  7050. return;
  7051. repaint (degreeGhostArea());
  7052. degreeGhost = std::move (next);
  7053. repaint (degreeGhostArea());
  7054. // the preview: the chord sounds once the mouse rests on it (a quarter of a second), not while it moves on
  7055. stopDegreeHear();
  7056. if (degreeHear && scale.valid())
  7057. {
  7058. degreeHearStage = 0;
  7059. degreeHearTimer.startTimer (300);
  7060. }
  7061. }
  7062. void PianoRollComponent::degreeHearStep()
  7063. {
  7064. for (const auto k : degreeSounding)
  7065. engine.sendLiveNote (degreeSoundingChannel, k, 0.0f, false);
  7066. degreeSounding.clear();
  7067. if (degreeHearStage == 0 && degreeGhost.tick >= 0)
  7068. {
  7069. degreeSoundingChannel = engine.getSelectedChannel();
  7070. for (const auto k : degreeGhost.keys)
  7071. {
  7072. engine.sendLiveNote (degreeSoundingChannel, k, noteTemplate.velocity, true);
  7073. degreeSounding.push_back (k);
  7074. }
  7075. degreeHearStage = 1;
  7076. degreeHearTimer.startTimer (700); // (how long it sounds)
  7077. return;
  7078. }
  7079. degreeHearTimer.stopTimer();
  7080. }
  7081. void PianoRollComponent::stopDegreeHear()
  7082. {
  7083. degreeHearTimer.stopTimer();
  7084. for (const auto k : degreeSounding)
  7085. engine.sendLiveNote (degreeSoundingChannel, k, 0.0f, false);
  7086. degreeSounding.clear();
  7087. degreeHearStage = 0;
  7088. }
  7089. juce::PopupMenu PianoRollComponent::degreeOptionsMenu()
  7090. {
  7091. juce::PopupMenu menu;
  7092. const auto pick = [this] (keyregions::DegreeSize size) {
  7093. degreeSize = size;
  7094. degreeGhost.label.clear(); // (the ghost takes the new shape at the next mouse move)
  7095. if (mixeroptions::changed) mixeroptions::changed(); // (saved with the UI options)
  7096. };
  7097. menu.addSectionHeader (tr ("Chord"));
  7098. menu.addItem (tr ("Triad"), true, degreeSize == keyregions::DegreeSize::triad, [pick] { pick (keyregions::DegreeSize::triad); });
  7099. menu.addItem (tr ("6th"), true, degreeSize == keyregions::DegreeSize::sixth, [pick] { pick (keyregions::DegreeSize::sixth); });
  7100. menu.addItem (tr ("7th"), true, degreeSize == keyregions::DegreeSize::seventh, [pick] { pick (keyregions::DegreeSize::seventh); });
  7101. menu.addItem (tr ("9th"), true, degreeSize == keyregions::DegreeSize::ninth, [pick] { pick (keyregions::DegreeSize::ninth); });
  7102. menu.addSectionHeader (tr ("Inversion"));
  7103. const char* names[] = { TR_NOOP ("Root position"), TR_NOOP ("1st inversion"), TR_NOOP ("2nd inversion"), TR_NOOP ("3rd inversion"), TR_NOOP ("4th inversion") };
  7104. const auto most = degreeSize == keyregions::DegreeSize::triad ? 2 : degreeSize == keyregions::DegreeSize::ninth ? 4 : 3;
  7105. for (int i = 0; i <= most; ++i)
  7106. menu.addItem (tr (names[i]), true, degreeInversion == i, [this, i] {
  7107. degreeInversion = i;
  7108. if (mixeroptions::changed) mixeroptions::changed();
  7109. });
  7110. menu.addSeparator();
  7111. menu.addItem (tr ("Hear the chord before clicking"), true, degreeHear, [this] {
  7112. degreeHear = ! degreeHear;
  7113. if (! degreeHear)
  7114. stopDegreeHear();
  7115. if (mixeroptions::changed) mixeroptions::changed();
  7116. });
  7117. return menu;
  7118. }
  7119. // FL's key menu (View › Scale highlighting's, on a key marker: "Root note" and "Scale" side by side; Default and Black
  7120. // notes first): a root keeps the scale, a scale keeps the root; for a new marker the root shown is the key in force there
  7121. juce::PopupMenu PianoRollComponent::keyChoiceMenu (const keyregions::State& current, std::function<void (keyregions::State)> pick)
  7122. {
  7123. juce::PopupMenu menu;
  7124. const auto isKey = current.kind == keyregions::State::key;
  7125. const auto root = isKey ? current.value.root : juce::jmax (0, scaleTonic());
  7126. const auto scale = isKey ? current.value.flScale : keyregions::majorScale();
  7127. menu.addSectionHeader (tr ("Root note"));
  7128. for (int r = 0; r < 12; ++r)
  7129. menu.addItem (juce::String (notenames::pitchName (r)), true, isKey && root == r,
  7130. [pick, r, scale] { pick ({ keyregions::State::key, { r, scale } }); });
  7131. menu.addColumnBreak();
  7132. menu.addSectionHeader (tr ("Scale"));
  7133. menu.addItem (tr ("Default"), true, current.kind == keyregions::State::editor, [pick] { pick ({ keyregions::State::editor, {} }); });
  7134. menu.addItem (tr ("Black notes"), true, current.kind == keyregions::State::none, [pick] { pick ({ keyregions::State::none, {} }); });
  7135. menu.addSeparator();
  7136. const auto& list = notetools::flReferenceScales();
  7137. for (int k = 0; k < (int) list.size(); ++k) // (in FL's menu order: rollup 0.1.31 step 3)
  7138. {
  7139. const auto i = notetools::flMenuScaleIndex (k);
  7140. menu.addItem (tr (list[(std::size_t) i].name), true, isKey && scale == i, [pick, root, i] { pick ({ keyregions::State::key, { root, i } }); });
  7141. }
  7142. return menu;
  7143. }
  7144. // --- the pattern's time markers (round 168g, docs/analise/REA_rodada168g.md §M13) --------------------------------------
  7145. juce::PopupMenu PianoRollComponent::markersMenu()
  7146. {
  7147. // FL's EEMarkerMenu (the Piano roll shows the Playlist's Time markers items, on the pattern's own markers)
  7148. juce::PopupMenu menu;
  7149. menu.addItem (tr ("Add one...") + keyText ("pianoRoll.markerAdd"), [this] { runAction ("pianoRoll.markerAdd"); });
  7150. menu.addItem (tr ("Add auto") + keyText ("pianoRoll.markerAuto"), [this] { runAction ("pianoRoll.markerAuto"); });
  7151. menu.addItem (tr ("Add time signature change...") + keyText ("pianoRoll.markerSignature"), [this] { runAction ("pianoRoll.markerSignature"); });
  7152. {
  7153. // round 190nu: FL's "Add key marker" (at the time selection's start, else the playhead, as the other markers here)
  7154. // and LYNX's key region over the time selection (its end brings back what was there)
  7155. const auto tick = markerKeyTick();
  7156. const auto here = keyregions::stateAt (currentPattern (engine.getSong()), tick);
  7157. menu.addSubMenu (tr ("Add key marker"), keyChoiceMenu (here, [this, tick] (keyregions::State s) { addKeyMarker (tick, s); }));
  7158. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  7159. const auto from = timeFrom, to = timeTo;
  7160. menu.addSubMenu (tr ("Key region for the time selection"),
  7161. keyChoiceMenu (hasTime ? keyregions::stateAt (currentPattern (engine.getSong()), from) : here,
  7162. [this, from, to] (keyregions::State s) { addKeyRegion (from, to, s); }),
  7163. hasTime);
  7164. }
  7165. const auto any = ! currentPattern (engine.getSong()).markers.empty();
  7166. menu.addSeparator();
  7167. menu.addItem (tr ("Delete all markers"), any, false, [this] {
  7168. engine.editSong ([] (Song& s) { currentPattern (s).markers.clear(); });
  7169. repaint();
  7170. });
  7171. return menu;
  7172. }
  7173. std::int64_t PianoRollComponent::markerKeyTick() const
  7174. {
  7175. // like the Playlist's (FL FUN_0122b0d0 / FUN_01229d20): the time selection's start; else the playhead when it is
  7176. // in view; else the bar line nearest the view's left edge
  7177. if (timeFrom >= 0 && timeTo > timeFrom)
  7178. return timeFrom;
  7179. const auto left = std::max (0.0, scrollTicks);
  7180. const auto right = xToTick (gridArea().getRight());
  7181. if (playheadTick >= left && playheadTick <= right)
  7182. return (std::int64_t) playheadTick;
  7183. const auto bar = engine.getSong().barTicks();
  7184. const auto at = (std::int64_t) left;
  7185. return at % bar > bar / 2 ? (at / bar + 1) * bar : at / bar * bar;
  7186. }
  7187. void PianoRollComponent::editPatternMarker (std::int64_t tick, int existing)
  7188. {
  7189. const auto& markers = currentPattern (engine.getSong()).markers;
  7190. const auto current = existing >= 0 && existing < (int) markers.size() ? juce::String::fromUTF8 (markers[(std::size_t) existing].name.c_str())
  7191. : tr ("Marker");
  7192. // FL's "Marker name" prompt
  7193. auto* window = new juce::AlertWindow (existing >= 0 ? tr ("Rename marker") : tr ("New marker"), {}, juce::MessageBoxIconType::NoIcon, this);
  7194. window->addTextEditor ("name", current);
  7195. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7196. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7197. juce::Component::SafePointer<PianoRollComponent> safe (this);
  7198. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, tick, existing, window] (int result) {
  7199. if (result != 1 || safe == nullptr)
  7200. return;
  7201. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  7202. safe->engine.editSong ([tick, existing, name] (Song& s) {
  7203. auto& p = currentPattern (s);
  7204. if (existing < 0)
  7205. noteedit::addPatternMarker (p, { tick, name, 0, 4 });
  7206. else if (existing < (int) p.markers.size())
  7207. p.markers[(std::size_t) existing].name = name;
  7208. });
  7209. safe->repaint();
  7210. }),
  7211. true);
  7212. }
  7213. void PianoRollComponent::addPatternSignatureByKey()
  7214. {
  7215. const auto& song = engine.getSong();
  7216. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  7217. const auto from = hasTime ? timeFrom : snap ((double) markerKeyTick(), true);
  7218. const auto to = hasTime ? timeTo : (std::int64_t) -1;
  7219. const auto current = noteedit::patternSignatureAt (currentPattern (song), from, song.meter());
  7220. auto* window = new juce::AlertWindow (tr ("Add time signature change..."), {}, juce::MessageBoxIconType::NoIcon, this);
  7221. juce::StringArray numerators, denominators;
  7222. for (int n = 1; n <= 32; ++n)
  7223. numerators.add (juce::String (n));
  7224. for (int d : { 1, 2, 4, 8, 16, 32 })
  7225. denominators.add (juce::String (d));
  7226. window->addComboBox ("numerator", numerators, tr ("Numerator"));
  7227. window->addComboBox ("denominator", denominators, tr ("Denominator"));
  7228. window->getComboBoxComponent ("numerator")->setText (juce::String (current.first), juce::dontSendNotification);
  7229. window->getComboBoxComponent ("denominator")->setText (juce::String (current.second), juce::dontSendNotification);
  7230. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7231. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7232. juce::Component::SafePointer<PianoRollComponent> safe (this);
  7233. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, from, to, window] (int result) {
  7234. if (result != 1 || safe == nullptr)
  7235. return;
  7236. const auto n = window->getComboBoxComponent ("numerator")->getText().getIntValue();
  7237. const auto d = window->getComboBoxComponent ("denominator")->getText().getIntValue();
  7238. safe->engine.editSong ([from, to, n, d] (Song& s) {
  7239. noteedit::addPatternSignatureChange (currentPattern (s), from, to, n, d, s.meter());
  7240. });
  7241. safe->repaint();
  7242. }),
  7243. true);
  7244. }
  7245. int PianoRollComponent::markerAtX (int x) const
  7246. {
  7247. // the flag and the name to its right (the last one drawn wins, as it is on top)
  7248. const auto& markers = currentPattern (engine.getSong()).markers;
  7249. for (int i = (int) markers.size() - 1; i >= 0; --i)
  7250. {
  7251. const auto mx = (int) tickToX ((double) markers[(std::size_t) i].tick);
  7252. if (x >= mx - 3 && x <= mx + 60)
  7253. return i;
  7254. }
  7255. return -1;
  7256. }
  7257. void PianoRollComponent::showPatternMarkerMenu (int index)
  7258. {
  7259. patternMarkerMenu (index).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  7260. }
  7261. juce::PopupMenu PianoRollComponent::patternMarkerMenu (int index)
  7262. {
  7263. juce::PopupMenu menu;
  7264. const auto& markers = currentPattern (engine.getSong()).markers;
  7265. if (index >= 0 && index < (int) markers.size()) // (FL's heading: "C Minor Natural (Aeolian) - Key/Scale at 3:01:00")
  7266. {
  7267. const auto& m = markers[(std::size_t) index];
  7268. auto title = juce::String::fromUTF8 (m.name.c_str());
  7269. if (m.action != 0)
  7270. title += " - " + tr (markers::actionName (m.action));
  7271. menu.addSectionHeader (title);
  7272. }
  7273. menu.addItem (tr ("Rename marker..."), [this, index] { editPatternMarker (0, index); });
  7274. menu.addItem (tr ("Delete marker"), [this, index] {
  7275. engine.editSong ([index] (Song& s) {
  7276. auto& markers = currentPattern (s).markers;
  7277. if (index >= 0 && index < (int) markers.size())
  7278. markers.erase (markers.begin() + index);
  7279. });
  7280. repaint();
  7281. });
  7282. // round 190nu: FL's Action › Key/scale (on any marker: it becomes a key marker, named after its key)
  7283. if (index >= 0 && index < (int) markers.size())
  7284. {
  7285. const auto& m = markers[(std::size_t) index];
  7286. const auto now = keyregions::isKeyMarker (m) ? keyregions::stateOf (m) : keyregions::stateAt (currentPattern (engine.getSong()), m.tick);
  7287. menu.addSubMenu (tr ("Key/scale"), keyChoiceMenu (now, [this, index] (keyregions::State s) {
  7288. engine.editSong ([index, s] (Song& song) {
  7289. auto& list = currentPattern (song).markers;
  7290. if (index >= 0 && index < (int) list.size())
  7291. keyregions::setState (list[(std::size_t) index], s);
  7292. });
  7293. repaint();
  7294. }),
  7295. true, juce::Image(), keyregions::isKeyMarker (m));
  7296. }
  7297. menu.addSeparator();
  7298. menu.addSubMenu (tr ("Time markers"), markersMenu());
  7299. return menu;
  7300. }
  7301. // --- MPE lanes (round 190hy, issue #108; core/NoteCurves.h, docs/analise/REA_rodada190hy-mpe.md) -------------------
  7302. // Each note's own pitch bend / slide / pressure curve, edited as Live 11+ edits its note expression: the lane shows the
  7303. // curves over the notes' lengths (the selected notes brighter), a drag draws the curve of the note under the mouse (a
  7304. // selected one first), a point is dragged to move it and double-clicked to delete it; LYNX's own lane gestures on top
  7305. // (right-drag erases, Alt+click clears). FL 2026 has no per-note curves (FLEngine / Fruity Wrapper strings: none).
  7306. void PianoRollComponent::setMpeView (bool on)
  7307. {
  7308. if (mpeStacked == on)
  7309. return;
  7310. mpeStacked = on;
  7311. // (three lanes need room: the Clip-launch dock's 30 px lane grows while the MPE tab shows)
  7312. if (fitKeysToNotes && ! on)
  7313. velocityHeight = compactVelocityHeight; // (on: layoutEventPane sizes the three lanes)
  7314. resized();
  7315. repaint();
  7316. }
  7317. std::vector<std::pair<juce::Rectangle<int>, int>> PianoRollComponent::mpeLaneAreas() const
  7318. {
  7319. std::vector<std::pair<juce::Rectangle<int>, int>> out;
  7320. const auto lane = velocityArea();
  7321. if (lane.getHeight() < 12)
  7322. return out;
  7323. if (mpeStacked) // (round 190jd: the lanes the "Show Lane:" menu checks, stacked in its order, over the footer)
  7324. {
  7325. auto rest = lane.withTrimmedBottom (mpetab::footerHeight);
  7326. const auto shown = mpetab::shownLanes (mpeShownLanes);
  7327. const auto h = rest.getHeight() / juce::jmax (1, (int) shown.size());
  7328. for (std::size_t k = 0; k < shown.size(); ++k)
  7329. out.push_back ({ k + 1 < shown.size() ? rest.removeFromTop (h) : rest, mpeLaneIdOf (shown[k]) });
  7330. }
  7331. else if (isMpeLane (laneId()))
  7332. out.push_back ({ lane, laneId() });
  7333. return out;
  7334. }
  7335. int PianoRollComponent::mpeLaneAt (juce::Point<int> p, juce::Rectangle<int>* area) const
  7336. {
  7337. for (const auto& [r, id] : mpeLaneAreas())
  7338. if (r.contains (p))
  7339. {
  7340. if (area != nullptr)
  7341. *area = r;
  7342. return id;
  7343. }
  7344. return 0;
  7345. }
  7346. float PianoRollComponent::mpePitchRange() const
  7347. {
  7348. // ±12 semitones, or ±24 / ±48 when a shown note's curve goes further (Live's lane spans the MPE range, ±48)
  7349. auto reach = 0.0f;
  7350. const auto& notes = currentPattern (engine.getSong()).notes;
  7351. for (auto i : channelNotes())
  7352. if (const auto& n = notes[(std::size_t) i]; n.curves.has())
  7353. for (const auto& q : n.curves->lane (NoteCurveLane::pitch))
  7354. reach = juce::jmax (reach, std::abs (q.value));
  7355. return reach <= 1200.0f ? 1200.0f : reach <= 2400.0f ? 2400.0f : notecurves::maxPitchCents;
  7356. }
  7357. float PianoRollComponent::mpeNorm (int lane, float value, float range) const noexcept
  7358. {
  7359. return lane == laneMpePitch ? juce::jlimit (0.0f, 1.0f, 0.5f + value / (2.0f * range)) : juce::jlimit (0.0f, 1.0f, value);
  7360. }
  7361. float PianoRollComponent::mpeValue (int lane, float norm, float range) const noexcept
  7362. {
  7363. norm = juce::jlimit (0.0f, 1.0f, norm);
  7364. if (lane != laneMpePitch)
  7365. return norm;
  7366. const auto cents = (norm - 0.5f) * 2.0f * range;
  7367. return std::abs (cents) < range * 0.015f ? 0.0f : std::round (cents); // (snaps to no bend; whole cents)
  7368. }
  7369. float PianoRollComponent::mpeBase (int lane, const Note& n) noexcept
  7370. {
  7371. return lane == laneMpePitch ? 0.0f : lane == laneMpeSlide ? n.modX : mpe::pressureOfModY (n.modY);
  7372. }
  7373. int PianoRollComponent::mpeNoteAt (int x) const
  7374. {
  7375. const auto tick = xToTick (x);
  7376. const auto& notes = currentPattern (engine.getSong()).notes;
  7377. auto best = -1;
  7378. auto bestSelected = false;
  7379. for (auto i : channelNotes())
  7380. {
  7381. const auto& n = notes[(std::size_t) i];
  7382. if (tick < (double) n.start || tick >= (double) (n.start + n.length))
  7383. continue;
  7384. const auto selected = isSelected (i);
  7385. if (best < 0 || (selected && ! bestSelected)
  7386. || (selected == bestSelected && n.start >= notes[(std::size_t) best].start))
  7387. {
  7388. best = i;
  7389. bestSelected = selected;
  7390. }
  7391. }
  7392. return best;
  7393. }
  7394. int PianoRollComponent::mpePointAt (int note, int lane, juce::Rectangle<int> area, juce::Point<int> p, float range) const
  7395. {
  7396. const auto& notes = currentPattern (engine.getSong()).notes;
  7397. if (note < 0 || note >= (int) notes.size() || ! notes[(std::size_t) note].curves.has())
  7398. return -1;
  7399. const auto& n = notes[(std::size_t) note];
  7400. const auto usable = (float) area.getHeight() - 8.0f;
  7401. const auto& points = n.curves->lane ((NoteCurveLane) (lane - laneMpePitch));
  7402. auto best = -1;
  7403. auto bestDistance = 6.0f;
  7404. for (int k = 0; k < (int) points.size(); ++k)
  7405. {
  7406. const auto x = (float) tickToX ((double) n.start + (double) points[(std::size_t) k].tick);
  7407. const auto y = (float) area.getBottom() - 2.0f - usable * mpeNorm (lane, points[(std::size_t) k].value, range);
  7408. if (const auto d = juce::jmax (std::abs (x - (float) p.x), std::abs (y - (float) p.y)); d < bestDistance)
  7409. {
  7410. bestDistance = d;
  7411. best = k;
  7412. }
  7413. }
  7414. return best;
  7415. }
  7416. void PianoRollComponent::paintMpeLane (juce::Graphics& g, juce::Rectangle<int> area, int lane, float range)
  7417. {
  7418. using namespace theme::colour;
  7419. juce::Graphics::ScopedSaveState state (g);
  7420. g.reduceClipRegion (area);
  7421. const auto& notes = currentPattern (engine.getSong()).notes;
  7422. const auto usable = (float) area.getHeight() - 8.0f;
  7423. const auto yOf = [&] (float norm) { return (float) area.getBottom() - 2.0f - usable * norm; };
  7424. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7425. if (mpeStacked && lane != laneMpePitch) // (the stacked lanes' dividers)
  7426. {
  7427. g.setColour (border);
  7428. g.drawHorizontalLine (area.getY(), (float) area.getX(), (float) area.getRight());
  7429. }
  7430. if (lane == laneMpePitch) // the "no bend" line, and one per octave
  7431. {
  7432. g.setColour (textPrimary.withAlpha (0.15f));
  7433. g.drawHorizontalLine ((int) yOf (0.5f), (float) area.getX(), (float) area.getRight());
  7434. for (auto c = 1200.0f; c < range; c += 1200.0f)
  7435. for (auto sign : { -1.0f, 1.0f })
  7436. {
  7437. g.setColour (textPrimary.withAlpha (0.06f));
  7438. g.drawHorizontalLine ((int) yOf (mpeNorm (lane, sign * c, range)), (float) area.getX(), (float) area.getRight());
  7439. }
  7440. }
  7441. for (auto i : channelNotes())
  7442. {
  7443. const auto& n = notes[(std::size_t) i];
  7444. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  7445. if (x1 < (float) area.getX() || x0 > (float) area.getRight())
  7446. continue;
  7447. const auto selected = isSelected (i);
  7448. auto colour = selected ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  7449. if (n.muted)
  7450. colour = noteMuted;
  7451. // the note's length, faintly (where its curve lives)
  7452. g.setColour (colour.withAlpha (selected ? 0.10f : 0.05f));
  7453. g.fillRect (juce::Rectangle<float> (x0, (float) area.getY() + 1.0f, juce::jmax (1.0f, x1 - x0), (float) area.getHeight() - 1.0f));
  7454. const auto& points = n.curves->lane (curveLane);
  7455. const auto base = mpeBase (lane, n);
  7456. if (points.empty()) // (no curve: the note's own value, dashed)
  7457. {
  7458. const auto y = yOf (mpeNorm (lane, base, range));
  7459. const float dash[] = { 3.0f, 3.0f };
  7460. g.setColour (colour.withAlpha (selected ? 0.55f : 0.3f));
  7461. g.drawDashedLine (juce::Line<float> (x0, y, x1, y), dash, 2, 1.0f);
  7462. continue;
  7463. }
  7464. juce::Path path;
  7465. path.startNewSubPath (x0, yOf (mpeNorm (lane, points.front().value, range)));
  7466. for (const auto& q : points)
  7467. {
  7468. if ((double) q.tick > (double) n.length)
  7469. break;
  7470. path.lineTo ((float) tickToX ((double) n.start + (double) q.tick), yOf (mpeNorm (lane, q.value, range)));
  7471. }
  7472. path.lineTo (x1, yOf (mpeNorm (lane, n.curves->valueAt (curveLane, (double) n.length, base), range)));
  7473. g.setColour (colour.withAlpha (selected ? 0.95f : 0.6f));
  7474. g.strokePath (path, juce::PathStrokeType (selected ? 1.6f : 1.2f));
  7475. if (selected || points.size() <= 64) // (a recorded take's many points only on the notes being edited)
  7476. for (const auto& q : points)
  7477. if ((double) q.tick <= (double) n.length)
  7478. {
  7479. const auto px = (float) tickToX ((double) n.start + (double) q.tick), py = yOf (mpeNorm (lane, q.value, range));
  7480. g.fillEllipse (px - (selected ? 2.5f : 1.8f), py - (selected ? 2.5f : 1.8f), selected ? 5.0f : 3.6f, selected ? 5.0f : 3.6f);
  7481. }
  7482. }
  7483. if (mpeStacked) // (round 190jd: Live names the stacked lanes in the footer and its left column, not in the lane)
  7484. return;
  7485. // the lane's name and range, top left (as the property lanes write theirs)
  7486. juce::String name = lane == laneMpePitch ? tr ("MPE pitch bend") : lane == laneMpeSlide ? tr ("MPE slide") : tr ("MPE pressure");
  7487. if (lane == laneMpePitch)
  7488. name << " " << juce::String::fromUTF8 ("\xc2\xb1") << tr ("{0} st", { juce::String (juce::roundToInt (range / 100.0f)) });
  7489. g.setColour (textSecondary.withAlpha (0.8f));
  7490. g.setFont (theme::font (theme::type::caption, true));
  7491. textcache::drawText (g, name, area.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  7492. }
  7493. void PianoRollComponent::paintMpePitchOnNotes (juce::Graphics& g, juce::Rectangle<int> grid)
  7494. {
  7495. // as Live's MPE view: the note's pitch over its key row, one row per semitone (its fine pitch included)
  7496. using namespace theme::colour;
  7497. juce::Graphics::ScopedSaveState state (g);
  7498. g.reduceClipRegion (grid);
  7499. const auto& notes = currentPattern (engine.getSong()).notes;
  7500. for (auto i : channelNotes())
  7501. {
  7502. const auto& n = notes[(std::size_t) i];
  7503. if (! n.curves.has() || n.curves->lane (NoteCurveLane::pitch).empty())
  7504. continue;
  7505. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  7506. if (x1 < (float) grid.getX() || x0 > (float) grid.getRight())
  7507. continue;
  7508. const auto centre = (float) keyToY (n.key) + (float) rowHeight * 0.5f;
  7509. const auto yOf = [&] (float cents) { return centre - (n.finePitch + cents) / 100.0f * (float) rowHeight; };
  7510. const auto& points = n.curves->lane (NoteCurveLane::pitch);
  7511. juce::Path path;
  7512. path.startNewSubPath (x0, yOf (points.front().value));
  7513. for (const auto& q : points)
  7514. {
  7515. if ((double) q.tick > (double) n.length)
  7516. break;
  7517. path.lineTo ((float) tickToX ((double) n.start + (double) q.tick), yOf (q.value));
  7518. }
  7519. path.lineTo (x1, yOf (n.curves->valueAt (NoteCurveLane::pitch, (double) n.length, 0.0f)));
  7520. g.setColour (juce::Colours::black.withAlpha (0.45f));
  7521. g.strokePath (path, juce::PathStrokeType (2.6f));
  7522. g.setColour ((isSelected (i) ? accentHover.brighter (0.4f) : textPrimary).withAlpha (0.9f));
  7523. g.strokePath (path, juce::PathStrokeType (1.3f));
  7524. }
  7525. }
  7526. void PianoRollComponent::editNoteCurves (int note, const std::function<void (Note&)>& edit)
  7527. {
  7528. editNotes ([note, &edit] (Pattern& p) {
  7529. if (note >= 0 && note < (int) p.notes.size())
  7530. edit (p.notes[(std::size_t) note]);
  7531. });
  7532. }
  7533. bool PianoRollComponent::mpeMouseDown (const juce::MouseEvent& e)
  7534. {
  7535. juce::Rectangle<int> area;
  7536. const auto lane = mpeLaneAt (e.getPosition(), &area);
  7537. if (lane == 0)
  7538. return mpeStacked; // (round 190jd: the MPE tab's footer under the lanes takes the press)
  7539. mpeDragLane = lane;
  7540. mpeDragRange = mpePitchRange();
  7541. lastMpeX = e.x;
  7542. lastMpeY = e.y;
  7543. mpeDragNote = mpeNoteAt (e.x);
  7544. mpeDragPoint = -1;
  7545. if (mpeStacked && mpeFocusLane != lane)
  7546. {
  7547. mpeFocusLane = lane; // (the footer names the lane edited last, as Live's)
  7548. repaint (mpeFooterArea());
  7549. }
  7550. if (mpeGhost.x >= 0.0f)
  7551. updateMpeGhost ({ -1, -1 });
  7552. if (mpeDragNote < 0)
  7553. return true; // (no note there: nothing to draw on)
  7554. if (! isMpeLane (lane)) // round 190jd: the MPE tab's Velocity / Release Velocity lanes: the note under the mouse
  7555. {
  7556. if (! e.mods.isLeftButtonDown())
  7557. return true;
  7558. drag = Drag::mpeValue;
  7559. mpeMouseDrag (e);
  7560. return true;
  7561. }
  7562. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7563. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) mpeDragNote];
  7564. const auto norm = (float) (area.getBottom() - 2 - e.y) / (float) juce::jmax (1, area.getHeight() - 8);
  7565. const auto value = mpeValue (lane, norm, mpeDragRange);
  7566. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  7567. const auto base = mpeBase (lane, n);
  7568. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click: the note's lane back to its own value
  7569. {
  7570. editNoteCurves (mpeDragNote, [curveLane] (Note& m) { notecurves::clearLane (m.curves, curveLane); });
  7571. mpeDragNote = -1;
  7572. return true;
  7573. }
  7574. if (e.mods.isRightButtonDown()) // right-drag erases the points it crosses
  7575. {
  7576. drag = Drag::mpeErase;
  7577. editNoteCurves (mpeDragNote, [curveLane, tick] (Note& m) { notecurves::erase (m.curves, curveLane, tick - 1.0, tick + 1.0); });
  7578. return true;
  7579. }
  7580. if (mpeStacked && ! drawmode::isOn())
  7581. {
  7582. // round 190jd, Live 12.4's pointer (q3-live-mpe-3…5): a point is dragged, a click ON the line adds a point there
  7583. // (and drags it), a click off the line does nothing; Draw Mode (B) draws
  7584. const auto hit = mpeLaneHit (mpeDragNote, lane, area, e.getPosition(), mpeDragRange);
  7585. if (hit.hit == mpetab::Hit::point)
  7586. {
  7587. drag = Drag::mpePoint;
  7588. mpeDragPoint = hit.index;
  7589. return true;
  7590. }
  7591. if (hit.hit != mpetab::Hit::line)
  7592. return true;
  7593. const auto onLine = n.curves.has() ? n.curves->valueAt (curveLane, tick, base) : base;
  7594. mpeCreatedAt = juce::Time::getMillisecondCounter();
  7595. auto added = -1;
  7596. editNoteCurves (mpeDragNote, [curveLane, tick, onLine, base, &added] (Note& m) { added = notecurves::addPoint (m.curves, curveLane, tick, onLine, base); });
  7597. drag = Drag::mpePoint;
  7598. mpeDragPoint = added;
  7599. lastMpeY = juce::roundToInt (hit.lineY); // (the point starts on the line; the drag moves it from there)
  7600. return true;
  7601. }
  7602. if (const auto point = mpePointAt (mpeDragNote, lane, area, e.getPosition(), mpeDragRange); point >= 0)
  7603. {
  7604. drag = Drag::mpePoint; // (a point: dragged)
  7605. mpeDragPoint = point;
  7606. return true;
  7607. }
  7608. drag = Drag::mpeDraw; // (elsewhere: drawing starts with a point here)
  7609. mpeCreatedAt = juce::Time::getMillisecondCounter();
  7610. editNoteCurves (mpeDragNote, [curveLane, tick, value, base] (Note& m) { notecurves::addPoint (m.curves, curveLane, tick, value, base); });
  7611. return true;
  7612. }
  7613. bool PianoRollComponent::mpeMouseDrag (const juce::MouseEvent& e)
  7614. {
  7615. const auto& notes = currentPattern (engine.getSong()).notes;
  7616. if (drag == Drag::mpeValue) // round 190jd: the note under the mouse takes the value (a selected one first)
  7617. {
  7618. juce::Rectangle<int> area;
  7619. for (const auto& [r, id] : mpeLaneAreas())
  7620. if (id == mpeDragLane)
  7621. area = r;
  7622. const auto note = mpeNoteAt (e.x);
  7623. if (area.isEmpty() || note < 0)
  7624. return true;
  7625. mpeDragNote = note;
  7626. const auto v = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - 2 - e.y) / (float) juce::jmax (1, area.getHeight() - 8));
  7627. const auto lane = mpeDragLane;
  7628. editNotes ([note, lane, v] (Pattern& p) {
  7629. if (note >= 0 && note < (int) p.notes.size())
  7630. setMpeValueLaneValue (lane, p.notes[(std::size_t) note], v);
  7631. });
  7632. return true;
  7633. }
  7634. if (mpeDragNote < 0 || mpeDragNote >= (int) notes.size())
  7635. return true;
  7636. if (drag == Drag::mpeBend) // round 190jd: a pitch point on the note, one key row a semitone (Live: "0 st", "1 st" …)
  7637. {
  7638. const auto& n = notes[(std::size_t) mpeDragNote];
  7639. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  7640. const auto cents = mpetab::bendCents (mpeBendStart, (float) (e.y - mpeBendY0), (float) rowHeight, e.mods.isShiftDown());
  7641. const auto point = mpeDragPoint;
  7642. editNoteCurves (mpeDragNote, [point, tick, cents] (Note& m) { notecurves::movePoint (m.curves, NoteCurveLane::pitch, point, tick, cents); });
  7643. lastMpeX = e.x;
  7644. lastMpeY = e.y;
  7645. return true;
  7646. }
  7647. juce::Rectangle<int> area;
  7648. for (const auto& [r, id] : mpeLaneAreas())
  7649. if (id == mpeDragLane)
  7650. area = r;
  7651. if (area.isEmpty())
  7652. return true;
  7653. const auto& n = notes[(std::size_t) mpeDragNote];
  7654. const auto lane = mpeDragLane;
  7655. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7656. const auto valueAtY = [&] (int y) { return mpeValue (lane, (float) (area.getBottom() - 2 - y) / (float) juce::jmax (1, area.getHeight() - 8), mpeDragRange); };
  7657. const auto tickAtX = [&] (int x) { return juce::jlimit (0.0, (double) n.length, xToTick (x) - (double) n.start); };
  7658. const auto t0 = tickAtX (lastMpeX), t1 = tickAtX (e.x);
  7659. const auto v0 = valueAtY (lastMpeY), v1 = valueAtY (e.y);
  7660. const auto base = mpeBase (lane, n);
  7661. if (drag == Drag::mpePoint)
  7662. {
  7663. const auto point = mpeDragPoint;
  7664. editNoteCurves (mpeDragNote, [curveLane, point, t1, v1] (Note& m) { notecurves::movePoint (m.curves, curveLane, point, t1, v1); });
  7665. }
  7666. else if (drag == Drag::mpeDraw)
  7667. {
  7668. // (one point every 3 pixels along the drag)
  7669. const auto step = juce::jmax (1.0, 3.0 / juce::jmax (1.0e-9, pixelsPerTick));
  7670. editNoteCurves (mpeDragNote, [=] (Note& m) { notecurves::drawLine (m.curves, curveLane, t0, v0, t1, v1, step, base); });
  7671. }
  7672. else
  7673. editNoteCurves (mpeDragNote, [=] (Note& m) { notecurves::erase (m.curves, curveLane, juce::jmin (t0, t1) - 1.0, juce::jmax (t0, t1) + 1.0); });
  7674. lastMpeX = e.x;
  7675. lastMpeY = e.y;
  7676. return true;
  7677. }
  7678. bool PianoRollComponent::mpeDoubleClick (const juce::MouseEvent& e)
  7679. {
  7680. juce::Rectangle<int> area;
  7681. const auto lane = mpeLaneAt (e.getPosition(), &area);
  7682. if (lane == 0 || e.mods.isRightButtonDown() || ! isMpeLane (lane)) // (round 190jd: Velocity / Release Velocity have no points)
  7683. return lane != 0 || mpeStacked;
  7684. // the first click of this double click drew the point: that was adding it, not deleting it
  7685. if (juce::Time::getMillisecondCounter() - mpeCreatedAt < 800)
  7686. return true;
  7687. const auto note = mpeNoteAt (e.x);
  7688. const auto range = mpePitchRange();
  7689. if (const auto point = mpePointAt (note, lane, area, e.getPosition(), range); point >= 0)
  7690. {
  7691. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7692. editNoteCurves (note, [curveLane, point] (Note& m) { notecurves::removePoint (m.curves, curveLane, point); });
  7693. }
  7694. return true;
  7695. }
  7696. // --- the MPE tab as Live 12.4's (round 190jd; core/MpeTab.h, /mnt/e/lynx-work/livecheck190iw/ANSWERS.md Q3) -----------
  7697. int PianoRollComponent::mpeLaneIdOf (mpetab::Lane lane) noexcept
  7698. {
  7699. switch (lane)
  7700. {
  7701. case mpetab::Lane::slide: return laneMpeSlide;
  7702. case mpetab::Lane::pressure: return laneMpePressure;
  7703. case mpetab::Lane::velocity: return laneVelocity;
  7704. case mpetab::Lane::releaseVelocity: return laneRelease;
  7705. }
  7706. return laneMpePressure;
  7707. }
  7708. float PianoRollComponent::mpeValueLaneValue (int lane, const Note& n) noexcept
  7709. {
  7710. return lane == laneRelease ? n.release : n.velocity;
  7711. }
  7712. void PianoRollComponent::setMpeValueLaneValue (int lane, Note& n, float v) noexcept
  7713. {
  7714. v = std::round (juce::jlimit (0.0f, 1.0f, v) * 127.0f) / 127.0f; // (Live's whole velocity steps)
  7715. if (lane == laneRelease)
  7716. n.release = v;
  7717. else
  7718. n.velocity = juce::jmax (1.0f / 127.0f, v); // (a note keeps a velocity of at least 1, as Live's)
  7719. }
  7720. void PianoRollComponent::setMpeLanesForSnapshot (mpetab::LaneSet lanes)
  7721. {
  7722. mpeShownLanes = lanes == 0 ? mpetab::defaultLanes : lanes;
  7723. resized();
  7724. repaint();
  7725. }
  7726. juce::Rectangle<int> PianoRollComponent::mpeFooterArea() const
  7727. {
  7728. if (! mpeStacked)
  7729. return {};
  7730. const auto lane = velocityArea();
  7731. return { 0, lane.getBottom() - mpetab::footerHeight, lane.getRight(), mpetab::footerHeight };
  7732. }
  7733. juce::PopupMenu PianoRollComponent::mpeLaneMenu()
  7734. {
  7735. // Live 12.4's ▾ button (q3-live-mpe-show-lane-menu.png): "Show Lane:" and four check items, several at once
  7736. juce::PopupMenu menu;
  7737. menu.addSectionHeader (tr ("Show Lane:"));
  7738. const std::pair<mpetab::Lane, juce::String> items[] { { mpetab::Lane::slide, tr ("Slide") },
  7739. { mpetab::Lane::pressure, tr ("Pressure") },
  7740. { mpetab::Lane::velocity, tr ("Velocity") },
  7741. { mpetab::Lane::releaseVelocity, tr ("Release Velocity") } };
  7742. for (const auto& [lane, name] : items)
  7743. {
  7744. const auto shown = mpetab::shows (mpeShownLanes, lane);
  7745. // (the last lane shown stays: the menu greys it out)
  7746. const auto enabled = ! shown || mpetab::countOf (mpeShownLanes) > 1;
  7747. menu.addItem (name, enabled, shown, [safe = juce::Component::SafePointer<PianoRollComponent> (this), lane] {
  7748. if (safe == nullptr)
  7749. return;
  7750. mpeShownLanes = mpetab::toggled (mpeShownLanes, lane);
  7751. const auto id = mpeLaneIdOf (lane);
  7752. if (mpetab::shows (mpeShownLanes, lane))
  7753. safe->mpeFocusLane = id;
  7754. else if (safe->mpeFocusLane == id)
  7755. safe->mpeFocusLane = mpeLaneIdOf (mpetab::shownLanes (mpeShownLanes).back());
  7756. safe->resized();
  7757. safe->repaint();
  7758. });
  7759. }
  7760. return menu;
  7761. }
  7762. mpetab::HitResult PianoRollComponent::mpeLaneHit (int note, int lane, juce::Rectangle<int> area, juce::Point<int> p, float range) const
  7763. {
  7764. const auto& notes = currentPattern (engine.getSong()).notes;
  7765. if (note < 0 || note >= (int) notes.size() || ! isMpeLane (lane))
  7766. return {};
  7767. const auto& n = notes[(std::size_t) note];
  7768. const auto usable = (float) area.getHeight() - 8.0f;
  7769. const auto yOf = [&] (float v) { return (float) area.getBottom() - 2.0f - usable * mpeNorm (lane, v, range); };
  7770. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7771. const auto base = mpeBase (lane, n);
  7772. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  7773. std::vector<mpetab::Px> points, line;
  7774. if (n.curves.has() && ! n.curves->lane (curveLane).empty())
  7775. {
  7776. const auto& q = n.curves->lane (curveLane);
  7777. line.push_back ({ x0, yOf (q.front().value) });
  7778. for (const auto& k : q)
  7779. {
  7780. if ((double) k.tick > (double) n.length)
  7781. break;
  7782. const mpetab::Px px { (float) tickToX ((double) n.start + (double) k.tick), yOf (k.value) };
  7783. points.push_back (px);
  7784. line.push_back (px);
  7785. }
  7786. line.push_back ({ x1, yOf (n.curves->valueAt (curveLane, (double) n.length, base)) });
  7787. }
  7788. else
  7789. line = { { x0, yOf (base) }, { x1, yOf (base) } }; // (no curve: the note's own value, the dashed line)
  7790. return mpetab::hitTest (points, line, x0, x1, { (float) p.x, (float) p.y });
  7791. }
  7792. std::pair<int, int> PianoRollComponent::mpePitchPointAt (juce::Point<int> p) const
  7793. {
  7794. const auto& notes = currentPattern (engine.getSong()).notes;
  7795. for (auto i : channelNotes())
  7796. {
  7797. const auto& n = notes[(std::size_t) i];
  7798. if (! isSelected (i) || ! n.curves.has())
  7799. continue;
  7800. const auto& q = n.curves->lane (NoteCurveLane::pitch);
  7801. std::vector<mpetab::Px> points;
  7802. const auto centre = (float) keyToY (n.key) + (float) rowHeight * 0.5f;
  7803. for (const auto& k : q)
  7804. if ((double) k.tick <= (double) n.length)
  7805. points.push_back ({ (float) tickToX ((double) n.start + (double) k.tick), centre - (n.finePitch + k.value) / 100.0f * (float) rowHeight });
  7806. if (const auto hit = mpetab::hitTest (points, {}, 0.0f, 0.0f, { (float) p.x, (float) p.y }); hit.hit == mpetab::Hit::point)
  7807. return { i, hit.index };
  7808. }
  7809. return { -1, -1 };
  7810. }
  7811. bool PianoRollComponent::mpePitchMouseDown (const juce::MouseEvent& e, int hit, bool onEdge)
  7812. {
  7813. // Live 12.4 (q3-live-mpe-1, -6): a selected note's pitch point is dragged up / down in semitones; a click on a selected
  7814. // note adds a pitch point there (the curve's value, "0 st" on a plain note); an unselected note is selected and moved
  7815. // as in the Notes tab
  7816. if (e.mods.isShiftDown() || flmods::ctrl (e.mods) || e.mods.isAltDown() || ! gridArea().contains (e.getPosition()))
  7817. return false;
  7818. const auto tool = tools.getTool();
  7819. if (tool != EditTool::pencil && tool != EditTool::lasso)
  7820. return false;
  7821. const auto grabbed = mpePitchPointAt (e.getPosition());
  7822. auto note = grabbed.first, point = grabbed.second;
  7823. const auto& notes = currentPattern (engine.getSong()).notes;
  7824. if (note < 0)
  7825. {
  7826. if (hit < 0 || onEdge || ! isSelected (hit))
  7827. return false;
  7828. const auto& n = notes[(std::size_t) hit];
  7829. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  7830. const auto value = n.curves.has() ? n.curves->valueAt (NoteCurveLane::pitch, tick, 0.0f) : 0.0f;
  7831. note = hit;
  7832. editNoteCurves (note, [tick, value, &point] (Note& m) { point = notecurves::addPoint (m.curves, NoteCurveLane::pitch, tick, value, 0.0f); });
  7833. mpeCreatedAt = juce::Time::getMillisecondCounter();
  7834. }
  7835. const auto& after = currentPattern (engine.getSong()).notes;
  7836. if (note < 0 || note >= (int) after.size() || ! after[(std::size_t) note].curves.has())
  7837. return true;
  7838. const auto& q = after[(std::size_t) note].curves->lane (NoteCurveLane::pitch);
  7839. if (point < 0 || point >= (int) q.size())
  7840. return true;
  7841. drag = Drag::mpeBend;
  7842. mpeDragNote = note;
  7843. mpeDragPoint = point;
  7844. mpeBendStart = q[(std::size_t) point].value;
  7845. mpeBendY0 = e.y;
  7846. lastMpeX = e.x;
  7847. lastMpeY = e.y;
  7848. return true;
  7849. }
  7850. bool PianoRollComponent::mpePitchDoubleClick (const juce::MouseEvent& e)
  7851. {
  7852. if (e.mods.isRightButtonDown() || flmods::ctrl (e.mods))
  7853. return false;
  7854. // the first click of this double click added the point: that was adding it, not deleting it
  7855. if (juce::Time::getMillisecondCounter() - mpeCreatedAt < 800)
  7856. return true;
  7857. if (const auto grabbed = mpePitchPointAt (e.getPosition()); grabbed.first >= 0)
  7858. {
  7859. const auto point = grabbed.second;
  7860. editNoteCurves (grabbed.first, [point] (Note& m) { notecurves::removePoint (m.curves, NoteCurveLane::pitch, point); });
  7861. return true;
  7862. }
  7863. bool rightEdge = false, leftEdge = false;
  7864. const auto hit = noteAt (e.x, e.y, rightEdge, leftEdge);
  7865. return hit >= 0 && isSelected (hit); // (a selected note's body is the pitch editor here: no note properties)
  7866. }
  7867. juce::Rectangle<int> PianoRollComponent::mpeGhostBounds() const
  7868. {
  7869. if (mpeGhost.x < 0.0f)
  7870. return {};
  7871. return juce::Rectangle<int> (juce::roundToInt (mpeGhost.x) - 6, juce::roundToInt (mpeGhost.y) - 22, 48, 30);
  7872. }
  7873. void PianoRollComponent::updateMpeGhost (juce::Point<int> p)
  7874. {
  7875. juce::Point<float> ghost { -1.0f, -1.0f };
  7876. juce::String text;
  7877. juce::Rectangle<int> area;
  7878. if (mpeStacked && drag == Drag::none && velocityArea().contains (p) && ! drawmode::isOn())
  7879. if (const auto lane = mpeLaneAt (p, &area); isMpeLane (lane))
  7880. if (const auto note = mpeNoteAt (p.x); note >= 0)
  7881. {
  7882. const auto hit = mpeLaneHit (note, lane, area, p, mpePitchRange());
  7883. if (hit.hit == mpetab::Hit::line)
  7884. {
  7885. ghost = { (float) p.x, hit.lineY };
  7886. const auto norm = juce::jlimit (0.0f, 1.0f, ((float) area.getBottom() - 2.0f - hit.lineY) / (float) juce::jmax (1, area.getHeight() - 8));
  7887. const auto v = mpeValue (lane, norm, mpePitchRange());
  7888. text = juce::String (juce::roundToInt (lane == laneMpeSlide ? (float) mpe::timbreOfModX (v) : v * 127.0f));
  7889. }
  7890. }
  7891. if (ghost == mpeGhost && text == mpeGhostText)
  7892. return;
  7893. const auto before = mpeGhostBounds();
  7894. mpeGhost = ghost;
  7895. mpeGhostText = text;
  7896. // (only the two small boxes: the old ghost and the new one)
  7897. if (! before.isEmpty())
  7898. repaint (before);
  7899. if (const auto now = mpeGhostBounds(); ! now.isEmpty())
  7900. repaint (now);
  7901. }
  7902. juce::String PianoRollComponent::hoverMpeLineForSnapshot (int laneId, double tick)
  7903. {
  7904. for (const auto& [area, id] : mpeLaneAreas())
  7905. if (id == laneId)
  7906. for (auto y = area.getY(); y < area.getBottom(); ++y)
  7907. {
  7908. updateMpeGhost ({ juce::roundToInt (tickToX (tick)), y });
  7909. if (mpeGhost.x >= 0.0f)
  7910. return mpeGhostText;
  7911. }
  7912. return {};
  7913. }
  7914. void PianoRollComponent::paintMpeValueLane (juce::Graphics& g, juce::Rectangle<int> area, int lane)
  7915. {
  7916. // Live's Velocity / Release Velocity lanes in the MPE tab: one stem per note, its value at the top (a dot)
  7917. using namespace theme::colour;
  7918. juce::Graphics::ScopedSaveState state (g);
  7919. g.reduceClipRegion (area);
  7920. g.setColour (border);
  7921. g.drawHorizontalLine (area.getY(), (float) area.getX(), (float) area.getRight());
  7922. const auto& notes = currentPattern (engine.getSong()).notes;
  7923. const auto usable = (float) area.getHeight() - 8.0f;
  7924. for (auto i : channelNotes())
  7925. {
  7926. const auto& n = notes[(std::size_t) i];
  7927. const auto x = (float) tickToX ((double) n.start);
  7928. if (x < (float) area.getX() - 4.0f || x > (float) area.getRight() + 4.0f)
  7929. continue;
  7930. const auto selected = isSelected (i);
  7931. auto colour = selected ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  7932. if (n.muted)
  7933. colour = noteMuted;
  7934. const auto y = (float) area.getBottom() - 2.0f - usable * mpeValueLaneValue (lane, n);
  7935. g.setColour (colour.withAlpha (selected ? 0.95f : 0.6f));
  7936. g.fillRect (juce::Rectangle<float> (x, y, 1.0f, (float) area.getBottom() - y));
  7937. g.drawEllipse (x - 2.5f, y - 2.5f, 5.0f, 5.0f, 1.2f);
  7938. }
  7939. }
  7940. void PianoRollComponent::paintMpeTabFrame (juce::Graphics& g)
  7941. {
  7942. // Live 12.4's MPE tab around the stacked lanes (q3-pair-live-vs-lynx-mpe-tab.png): the key column shows each lane's
  7943. // icon (Slide ⇕, Pressure ↓) and scale (127 / 0; Pressure 127 / 64 / 0); the footer row the ▾ "Show Lane" button and
  7944. // the focused lane's name; over a lane's line, the ghost point with its value
  7945. using namespace theme::colour;
  7946. const auto lanes = mpeLaneAreas();
  7947. const auto font = theme::font (theme::type::caption);
  7948. for (const auto& [area, id] : lanes)
  7949. {
  7950. const juce::Rectangle<int> column { 0, area.getY(), keyboardWidth, area.getHeight() };
  7951. if (! g.clipRegionIntersects (column))
  7952. continue;
  7953. g.setColour (border);
  7954. g.drawHorizontalLine (column.getY(), 0.0f, (float) keyboardWidth);
  7955. g.setColour (textSecondary.withAlpha (0.85f));
  7956. // the icon, left
  7957. {
  7958. const auto c = juce::Point<float> (9.0f, (float) column.getCentreY());
  7959. juce::Path icon;
  7960. if (id == laneMpeSlide) // ⇕
  7961. {
  7962. icon.addTriangle (c.x - 3.0f, c.y - 2.0f, c.x + 3.0f, c.y - 2.0f, c.x, c.y - 6.0f);
  7963. icon.addTriangle (c.x - 3.0f, c.y + 2.0f, c.x + 3.0f, c.y + 2.0f, c.x, c.y + 6.0f);
  7964. icon.addRectangle (c.x - 0.5f, c.y - 2.0f, 1.0f, 4.0f);
  7965. }
  7966. else if (id == laneMpePressure) // ↓
  7967. {
  7968. icon.addRectangle (c.x - 0.5f, c.y - 6.0f, 1.0f, 8.0f);
  7969. icon.addTriangle (c.x - 3.5f, c.y + 1.0f, c.x + 3.5f, c.y + 1.0f, c.x, c.y + 6.0f);
  7970. }
  7971. else // Velocity / Release Velocity: a stem with its dot
  7972. {
  7973. icon.addRectangle (c.x - 0.5f, c.y - 3.0f, 1.0f, 9.0f);
  7974. icon.addEllipse (c.x - 2.5f, c.y - 6.0f, 5.0f, 5.0f);
  7975. }
  7976. g.fillPath (icon);
  7977. }
  7978. // the scale, right-aligned against the lane with its ticks
  7979. const auto usable = (float) area.getHeight() - 8.0f;
  7980. const auto yOf = [&] (float norm) { return (float) area.getBottom() - 2.0f - usable * norm; };
  7981. std::vector<std::pair<float, const char*>> marks { { 1.0f, "127" }, { 0.0f, "0" } };
  7982. if (id == laneMpePressure && area.getHeight() >= 36)
  7983. marks.insert (marks.begin() + 1, { 0.5f, "64" });
  7984. g.setFont (font);
  7985. for (const auto& [norm, label] : marks)
  7986. {
  7987. const auto y = yOf (norm);
  7988. g.setColour (textSecondary.withAlpha (0.5f));
  7989. g.fillRect (juce::Rectangle<float> ((float) keyboardWidth - 5.0f, std::round (y), 4.0f, 1.0f));
  7990. g.setColour (textSecondary.withAlpha (0.85f));
  7991. const juce::Rectangle<float> box ((float) keyboardWidth - 36.0f, y - 6.0f, 29.0f, 12.0f);
  7992. textcache::drawText (g, label, box.toNearestInt(), juce::Justification::centredRight, false);
  7993. }
  7994. g.setColour (textSecondary.withAlpha (0.4f));
  7995. g.fillRect ((float) keyboardWidth - 2.0f, yOf (1.0f), 1.0f, yOf (0.0f) - yOf (1.0f) + 1.0f);
  7996. }
  7997. // the footer: ▾ and the focused lane's name (Live: "▾ Slide", "▾ Pressure")
  7998. if (const auto footer = mpeFooterArea(); ! footer.isEmpty() && g.clipRegionIntersects (footer))
  7999. {
  8000. g.setColour (bg2);
  8001. g.fillRect (footer);
  8002. g.setColour (border);
  8003. g.drawHorizontalLine (footer.getY(), 0.0f, (float) footer.getRight());
  8004. const auto cy = (float) footer.getCentreY();
  8005. juce::Path arrow;
  8006. arrow.addTriangle (6.0f, cy - 2.0f, 13.0f, cy - 2.0f, 9.5f, cy + 2.5f);
  8007. g.setColour (textSecondary);
  8008. g.fillPath (arrow);
  8009. auto focus = mpeFocusLane;
  8010. auto found = false;
  8011. for (const auto& lane : lanes)
  8012. found = found || lane.second == focus;
  8013. if (! found && ! lanes.empty())
  8014. focus = lanes.back().second;
  8015. const auto name = focus == laneMpeSlide ? tr ("Slide") : focus == laneMpePressure ? tr ("Pressure")
  8016. : focus == laneRelease ? tr ("Release Velocity") : tr ("Velocity");
  8017. g.setFont (font);
  8018. textcache::drawText (g, name, footer.withTrimmedLeft (18).withWidth (juce::jmax (40, keyboardWidth + 120)), juce::Justification::centredLeft, true);
  8019. }
  8020. // the ghost point on the hovered line, with its value (Live: "63", "15")
  8021. if (mpeGhost.x >= 0.0f && g.clipRegionIntersects (mpeGhostBounds()))
  8022. {
  8023. g.setColour (accentHover.withAlpha (0.9f));
  8024. g.drawEllipse (mpeGhost.x - 3.0f, mpeGhost.y - 3.0f, 6.0f, 6.0f, 1.2f);
  8025. const juce::Rectangle<float> tag (mpeGhost.x + 4.0f, mpeGhost.y - 20.0f, 26.0f, 14.0f);
  8026. g.setColour (bg0.withAlpha (0.9f));
  8027. g.fillRoundedRectangle (tag, 2.0f);
  8028. g.setColour (textPrimary);
  8029. g.setFont (font);
  8030. textcache::drawText (g, mpeGhostText, tag.toNearestInt(), juce::Justification::centred, false);
  8031. }
  8032. }
  8033. } // namespace lynx