PianoRollComponent.cpp 368 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224
  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/MuteKeys.h"
  8. #include "core/RulerGestures.h" // round 190nq (#227)
  9. #include "ui/ChordHelper.h"
  10. #include "ui/MixerComponent.h"
  11. #include "ui/PaintAB.h"
  12. #include "core/ChordReadout.h"
  13. #include "core/ClipLoopOps.h"
  14. #include "core/RowBands.h"
  15. #include "core/PastePlace.h"
  16. #include "ui/WindowClipboard.h" // issue #232 stage 2 (round 190nz)
  17. #include "core/LayoutStyle.h"
  18. #include "core/KeyMap.h"
  19. #include "core/NoteNames.h"
  20. #include "core/TransportEdit.h"
  21. #include "ui/UiTrace.h"
  22. #include "ui/TextCache.h"
  23. #include "core/EditorPolish.h"
  24. #include "core/MagicLasso.h"
  25. #include "core/EventEdit.h"
  26. #include "core/MarkerPlan.h"
  27. #include "core/NoteEdit.h"
  28. #include "core/FlSettings.h"
  29. #include "core/Details190mr.h"
  30. #include "core/NoteTools.h"
  31. #include "core/ScaleDetect.h"
  32. #include "core/Mpe.h"
  33. #include "core/NoteCurves.h"
  34. #include "core/DrawMode.h"
  35. #include "core/Rack.h"
  36. #include <array>
  37. #include "engine/MidiFileIo.h"
  38. #include "engine/Mp3Format.h"
  39. #include "core/PianoRollTools.h"
  40. #include "ui/BrowserComponent.h"
  41. #include "ui/Dialogs.h"
  42. #include "ui/MidiClipboard.h"
  43. #include "ui/MidiToolsPanel.h"
  44. #include "ui/ToolWindow.h"
  45. #include "engine/Text.h"
  46. #include <optional>
  47. #include "ui/AutomationUi.h"
  48. #include "ui/EventEditor.h"
  49. #include "ui/HintBar.h"
  50. #include "platform/Paths.h"
  51. #include "ui/I18n.h"
  52. #include "ui/Theme.h"
  53. namespace lynx
  54. {
  55. namespace
  56. {
  57. bool isBlackKey (int key)
  58. {
  59. const auto n = key % 12;
  60. return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
  61. }
  62. // Round 190jo (design190ia FM-15 / FM-16): FL's note, lit from the top (its upper part +6 %, the rest -4 % of its colour,
  63. // 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),
  64. // 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
  65. // velocity range of LYNX's red), bold, at the small text size.
  66. void paintNoteBody (juce::Graphics& g, juce::Rectangle<float> r, juce::Colour fill, juce::Colour edge)
  67. {
  68. // (perf: two solid fills instead of a gradient, whose brush the Direct2D renderer makes again for every note; the
  69. // upper half lighter reads as FL's top-lit note)
  70. g.setColour (fill.withMultipliedBrightness (0.96f));
  71. g.fillRoundedRectangle (r, 2.0f);
  72. if (r.getHeight() >= 8.0f)
  73. {
  74. g.setColour (fill.withMultipliedBrightness (1.06f));
  75. g.fillRect (juce::Rectangle<float> (r.getX() + 1.0f, r.getY() + 1.0f, r.getWidth() - 2.0f, std::floor (r.getHeight() * 0.45f)));
  76. }
  77. g.setColour (edge.isTransparent() ? fill.withMultipliedBrightness (0.72f) : edge);
  78. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  79. }
  80. juce::Colour noteLabelColour (juce::Colour fill)
  81. {
  82. return fill.getPerceivedBrightness() > 0.5f ? theme::colour::bg0 : theme::colour::textPrimary;
  83. }
  84. juce::Font noteLabelFont (int rowHeight)
  85. {
  86. return theme::font (juce::jmin (theme::type::small, gesture::labelHeight (rowHeight) - 1.0f), true);
  87. }
  88. // FL-style name: key 60 = C5.
  89. juce::String keyName (int key)
  90. {
  91. return juce::String (notenames::keyName (key)); // Settings › General › Note names (round 165f)
  92. }
  93. // (round 190ea: never out of range: an empty pattern when a hand-built song has none; an edit keeps one first)
  94. const Pattern& currentPattern (const Song& s)
  95. {
  96. return s.activePattern();
  97. }
  98. Pattern& currentPattern (Song& s)
  99. {
  100. return s.activePattern();
  101. }
  102. // "\t" + the key map's shortcut of `id` for a menu item (empty when unbound or no key map is connected)
  103. juce::String keyText (const std::string& id)
  104. {
  105. return PianoRollComponent::shortcutText ? PianoRollComponent::shortcutText (id) : juce::String();
  106. }
  107. struct NamedIntervals
  108. {
  109. const char* name;
  110. std::vector<int> intervals;
  111. };
  112. const std::vector<NamedIntervals>& chords()
  113. {
  114. static const std::vector<NamedIntervals> list {
  115. { TR_NOOP ("Note"), { 0 } }, { TR_NOOP ("Major"), { 0, 4, 7 } }, { TR_NOOP ("Minor"), { 0, 3, 7 } }, { "Dim", { 0, 3, 6 } },
  116. { "Aug", { 0, 4, 8 } }, { "Sus2", { 0, 2, 7 } }, { "Sus4", { 0, 5, 7 } }, { "7", { 0, 4, 7, 10 } },
  117. { "Maj7", { 0, 4, 7, 11 } }, { "m7", { 0, 3, 7, 10 } }, { "m9", { 0, 3, 7, 10, 14 } }, { TR_NOOP ("Octave"), { 0, 12 } },
  118. };
  119. return list;
  120. }
  121. const std::vector<notetools::ScaleInfo>& scales()
  122. {
  123. return notetools::scales();
  124. }
  125. // a detected chord in the chosen note names (Settings › General, round 165f): "Do m7/Mib"; "" when none
  126. juce::String chordName (const std::vector<int>& keys)
  127. {
  128. // FL's own names (round 181b, core/ChordReadout.h): the same for the panel, this readout and the bubble
  129. if ((int) keys.size() < chordread::minKeys || (int) keys.size() > chordread::maxKeys)
  130. return {};
  131. std::array<std::string, 12> notes;
  132. for (int pc = 0; pc < 12; ++pc)
  133. {
  134. auto name = juce::String (notenames::pitchName (pc));
  135. if (name.endsWithChar ('#'))
  136. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266F);
  137. else if (name.length() > 1 && name.endsWithChar ('b'))
  138. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266D);
  139. notes[(std::size_t) pc] = name.toStdString();
  140. }
  141. chordread::NameOptions options;
  142. options.notes = &notes;
  143. const auto named = chordread::nameKeys (keys, options);
  144. const auto text = juce::String::fromUTF8 (named.text.c_str());
  145. return named.novelty ? tr (text) : text;
  146. }
  147. // View › Background waveform (round 168g): one for every editor, like FL's (PTR_DAT_015e2698 / DAT_016ba824)
  148. struct BackgroundWave
  149. {
  150. juce::File file;
  151. std::vector<float> lo, hi; // per peak block
  152. double sampleRate = 44100.0;
  153. std::int64_t samples = 0;
  154. static constexpr int perPeak = 256;
  155. };
  156. std::shared_ptr<const BackgroundWave>& backgroundWave()
  157. {
  158. static std::shared_ptr<const BackgroundWave> wave;
  159. return wave;
  160. }
  161. bool& backgroundWaveOn()
  162. {
  163. static bool on = false;
  164. return on;
  165. }
  166. bool isScoreFile (const juce::File& f) { return f.hasFileExtension ("fsc"); }
  167. bool isMidiFile (const juce::File& f) { return f.hasFileExtension ("mid;midi"); }
  168. } // namespace
  169. // Live's Randomization Amount slider: a 38 x 13 box, 1 px #111111 edge, the value's share of 127 filled teal (#007383)
  170. // over #242424, the number in the middle [SHOT live-01-velocity-lane.png x 566…603, y 980…992]. Drag up / down or the
  171. // wheel change it; typed digits then Enter set it and randomize (manual 10.5.12), Escape forgets them.
  172. class PianoRollComponent::LiveAmountBox final : public juce::Component, public juce::SettableTooltipClient
  173. {
  174. public:
  175. std::function<void()> onEnter;
  176. LiveAmountBox()
  177. {
  178. setWantsKeyboardFocus (true);
  179. setTitle (tr ("Randomization Amount"));
  180. setTooltip (tr ("Randomization Amount: velocities move up or down by up to this much (drag, or type a number and press Enter)"));
  181. }
  182. void paint (juce::Graphics& g) override
  183. {
  184. const auto r = getLocalBounds();
  185. g.setColour (juce::Colour (0xff111111));
  186. g.fillRect (r);
  187. const auto inner = r.reduced (1);
  188. g.setColour (juce::Colour (0xff242424));
  189. g.fillRect (inner);
  190. const auto value = typed.isNotEmpty() ? juce::jlimit (0, 127, typed.getIntValue()) : PianoRollComponent::liveRandomizeAmount;
  191. g.setColour (juce::Colour (0xff007383));
  192. g.fillRect (inner.withWidth (juce::roundToInt ((float) inner.getWidth() * (float) value / 127.0f)));
  193. g.setColour (typed.isNotEmpty() ? juce::Colour (0xffffad56) : juce::Colour (0xffb0b0b0));
  194. g.setFont (theme::font (theme::type::caption));
  195. textcache::drawText (g, typed.isNotEmpty() ? typed : juce::String (value), r, juce::Justification::centred, false);
  196. }
  197. void mouseDown (const juce::MouseEvent&) override
  198. {
  199. dragFrom = PianoRollComponent::liveRandomizeAmount;
  200. grabKeyboardFocus();
  201. }
  202. void mouseDrag (const juce::MouseEvent& e) override { set (dragFrom - e.getDistanceFromDragStartY() / 2); }
  203. void mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& w) override
  204. {
  205. set (PianoRollComponent::liveRandomizeAmount + (w.deltaY > 0 ? 1 : w.deltaY < 0 ? -1 : 0));
  206. }
  207. bool keyPressed (const juce::KeyPress& key) override
  208. {
  209. const auto c = key.getTextCharacter();
  210. if (c >= '0' && c <= '9' && typed.length() < 3)
  211. {
  212. typed << juce::String::charToString (c);
  213. repaint();
  214. return true;
  215. }
  216. if (key.isKeyCode (juce::KeyPress::backspaceKey) && typed.isNotEmpty())
  217. {
  218. typed = typed.dropLastCharacters (1);
  219. repaint();
  220. return true;
  221. }
  222. if (key.isKeyCode (juce::KeyPress::returnKey) && typed.isNotEmpty())
  223. {
  224. typeForCheck (typed);
  225. return true;
  226. }
  227. if (key.isKeyCode (juce::KeyPress::escapeKey) && typed.isNotEmpty())
  228. {
  229. typed.clear();
  230. repaint();
  231. return true;
  232. }
  233. return false;
  234. }
  235. void focusLost (FocusChangeType) override
  236. {
  237. typed.clear();
  238. repaint();
  239. }
  240. // the value typed and validated with Enter: set, then the notes randomized
  241. void typeForCheck (const juce::String& text)
  242. {
  243. typed.clear();
  244. set (text.getIntValue());
  245. if (onEnter != nullptr)
  246. onEnter();
  247. }
  248. private:
  249. void set (int v)
  250. {
  251. v = juce::jlimit (1, 127, v);
  252. if (v != PianoRollComponent::liveRandomizeAmount)
  253. {
  254. PianoRollComponent::liveRandomizeAmount = v;
  255. repaint();
  256. }
  257. }
  258. juce::String typed;
  259. int dragFrom = 0;
  260. };
  261. PianoRollComponent::PianoRollComponent (AudioEngine& e)
  262. : engine (e)
  263. {
  264. gpuPlayhead.onHidden = [this] { repaint (playheadColumn (playheadTick)); }; // (round 190ip: painted again)
  265. auto sender = [this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); };
  266. previewNotes.setSender (sender);
  267. listenNotes.setSender (sender);
  268. setWantsKeyboardFocus (false);
  269. setMouseClickGrabsKeyboardFocus (false);
  270. for (auto* bar : { &hBar, &vBar })
  271. {
  272. bar->addListener (this);
  273. bar->setAutoHide (false);
  274. addAndMakeVisible (bar);
  275. }
  276. // the overview strip is the horizontal scroller (FL's Piano Roll has its preview bar on top)
  277. hBar.setVisible (false);
  278. overview.paintContent = [this] (juce::Graphics& g, juce::Rectangle<float> area, double total) { paintOverview (g, area, total); };
  279. overview.onChange = [this] (double start, double length) {
  280. const auto width = (double) gridArea().getWidth();
  281. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, width / juce::jmax (1.0, length));
  282. scrollTicks = juce::jmax (0.0, start);
  283. updateScrollBars();
  284. repaint();
  285. };
  286. overview.onShowAll = [this] { zoomAll(); };
  287. addAndMakeVisible (overview);
  288. grid::fillEditorBox (snapBox);
  289. 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"));
  290. ui::setQuickTip (snapBox, tr ("Piano Roll snap"));
  291. snapBox.setWantsKeyboardFocus (false);
  292. snapBox.setMouseClickGrabsKeyboardFocus (false);
  293. snapBox.onChange = [this] { repaint(); };
  294. addAndMakeVisible (snapBox);
  295. // round 190hr: the reference's grid value and menu (docked only)
  296. liveGridButton.setConnectedEdges (0);
  297. liveGridButton.setTooltip (tr ("Grid: adaptive or fixed, narrower (Ctrl+1) or wider (Ctrl+2), triplet (Ctrl+3), snap (Ctrl+4), fixed / adaptive (Ctrl+5)"));
  298. liveGridButton.onClick = [this] {
  299. liveGridMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&liveGridButton));
  300. };
  301. addChildComponent (liveGridButton);
  302. tools.onChange = [this] (EditTool) {
  303. stopListening();
  304. updateCursor (juce::ModifierKeys::currentModifiers);
  305. };
  306. tools.onZoomMenu = [this] (juce::Component& button) { // (round 190mp, DE-74)
  307. quickZoomMenu ("pianoRoll.", [this] (const std::string& id) { return runAction (id); }, shortcutText, false)
  308. .showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&button));
  309. };
  310. addAndMakeVisible (tools);
  311. 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"));
  312. channelBox.setWantsKeyboardFocus (false);
  313. channelBox.setMouseClickGrabsKeyboardFocus (false);
  314. channelBox.onChange = [this] {
  315. if (channelBox.getSelectedId() == allChannelsId)
  316. {
  317. setAllChannels (true);
  318. return;
  319. }
  320. const auto channel = channelBox.getSelectedId() - 1;
  321. setAllChannels (false);
  322. if (channel >= 0 && channel < (int) engine.getSong().channels.size() && channel != engine.getSelectedChannel())
  323. engine.setSelectedChannel (channel);
  324. };
  325. channelBox.onStep = [this] (int direction, bool all) {
  326. setAllChannels (false);
  327. stepChannel (direction, ! all);
  328. };
  329. addAndMakeVisible (channelBox);
  330. ghostButton.setClickingTogglesState (true);
  331. ghostButton.setToggleState (showGhosts, juce::dontSendNotification);
  332. ghostButton.setOnColour (theme::colour::bg6);
  333. ghostButton.setIconColourWhenOn (theme::colour::textPrimary);
  334. ghostButton.setFlat (true);
  335. ghostButton.setTooltip (tr ("Ghost notes: show the other channels' notes (Alt+V) and, outlined, this channel's notes in the clips "
  336. "playing at the same time; double right-click one to edit its channel; Ctrl+Alt+V makes them editable"));
  337. ui::setQuickTip (ghostButton, tr ("Ghost notes"), "Alt+V");
  338. ui::setQuickTip (moreButton, tr ("Note tools"));
  339. ui::setQuickTip (scaleSnapButton, tr ("Snap to scale"));
  340. ghostButton.onClick = [this] {
  341. showGhosts = ghostButton.getToggleState();
  342. repaint();
  343. };
  344. ghostButton.onRightClick = [this] { // FL: the ghost notes button's menu picks the channels (round 166d)
  345. ghostChannelsMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&ghostButton));
  346. };
  347. moreButton.setFlat (true);
  348. moreButton.setTooltip (tr ("Note operations, left-edge resizing and MIDI import/export"));
  349. moreButton.onClick = [this] { showMoreMenu(); };
  350. scaleSnapButton.setOnColour (theme::colour::bg6);
  351. scaleSnapButton.setIconColourWhenOn (theme::colour::accent);
  352. scaleSnapButton.setFlat (true);
  353. scaleSnapButton.setTooltip (tr ("Snap notes to the scale: new and moved notes, and incoming MIDI, land on the chosen scale"));
  354. scaleSnapButton.onClick = [this] { setScaleSnap (! scaleSnap); };
  355. // Follow (FL: "Auto scrolling"): the view pages along with the playhead while the pattern plays
  356. followButton.setOnColour (theme::colour::bg6);
  357. followButton.setIconColourWhenOn (theme::colour::accent);
  358. followButton.setFlat (true);
  359. followButton.setClickingTogglesState (false);
  360. followButton.setToggleState (EditorGlobals::get().isFollowing (true), juce::dontSendNotification);
  361. followButton.setTooltip (tr ("Follow: the Piano Roll scrolls along with the playhead while this pattern plays; off, you can look around freely"));
  362. ui::setQuickTip (followButton, tr ("Follow the playhead"));
  363. followButton.onClick = [this] { runAction ("pianoRoll.follow"); };
  364. playButton.setFlat (true);
  365. playButton.setClickingTogglesState (false);
  366. playButton.setIconColourWhenOn (theme::colour::accent); // FL: stays a play icon, in the theme colour while playing
  367. playButton.setTooltip (tr ("Play / pause the pattern [RMB] stop and go back to where playback started (again: to the pattern start)"));
  368. playButton.onClick = [this] { if (onPlayPause) onPlayPause(); };
  369. playButton.onRightClick = [this] { if (onPlayRightClick) onPlayRightClick(); };
  370. for (auto* b : { &playButton, &ghostButton, &scaleSnapButton, &moreButton, &followButton })
  371. {
  372. b->setWantsKeyboardFocus (false);
  373. b->setMouseClickGrabsKeyboardFocus (false);
  374. addAndMakeVisible (*b);
  375. }
  376. for (int i = 0; i < (int) chords().size(); ++i)
  377. {
  378. chordBox.addItem (tr (chords()[(std::size_t) i].name), i + 1);
  379. if (i == 0) // round 190nu (LYNX extra, discussion #105): the clicked degree's chord in the key of its region
  380. chordBox.addItem (tr ("Scale degree chord"), degreeStampId);
  381. }
  382. chordBox.setSelectedId (1, juce::dontSendNotification);
  383. chordBox.onPopup = [this] { return stampMenu(); }; // (round 190nu: FL's stamp button opens the Stamp menu; the options of the degree chord on top)
  384. chordBox.setTooltip (tr ("Clicking creates this chord (the clicked note is the root)"));
  385. // scale: root x type
  386. for (int s = 0; s < (int) scales().size(); ++s)
  387. {
  388. if (s == 0)
  389. {
  390. scaleBox.addItem (tr (scales()[0].name), 1);
  391. // FL's View › Scale highlighting › Automatic (round 190jv, core/ScaleDetect.h): the key guessed from the notes
  392. scaleBox.addItem (tr ("Automatic"), autoScaleId);
  393. continue;
  394. }
  395. for (int root = 0; root < 12; ++root)
  396. scaleBox.addItem (tr ("{0} {1}", { juce::String (notenames::pitchName (root)), tr (scales()[(std::size_t) s].name) }), s * 100 + root + 1);
  397. }
  398. scaleBox.setSelectedId (1, juce::dontSendNotification);
  399. scaleSnapButton.setEnabled (false); // until a scale is chosen
  400. scaleBox.setTooltip (tr ("Highlights the notes of a scale"));
  401. // issue #203 (round 190ll): the FL layout's click opens FL's Scale highlighting menu (root and scale apart)
  402. scaleBox.onPopup = [this] { return scaleHighlightMenu(); };
  403. // docked (Clip-launch: Live's Clip View Scale; Simple: BandLab's Smart View): a root box and a scale box
  404. for (int root = 0; root < 12; ++root)
  405. scaleRootBox.addItem (juce::String (notenames::pitchName (root)), root + 1);
  406. scaleNameBox.addItem (tr (scales()[0].name), 1);
  407. scaleNameBox.addItem (tr ("Automatic"), autoScaleId);
  408. for (int s = 1; s < (int) scales().size(); ++s)
  409. scaleNameBox.addItem (tr (scales()[(std::size_t) s].name), s * 100);
  410. scaleRootBox.setTooltip (tr ("Root note"));
  411. scaleNameBox.setTooltip (tr ("Highlights the notes of a scale"));
  412. scaleRootBox.onChange = [this] {
  413. splitRoot = juce::jlimit (0, 11, scaleRootBox.getSelectedId() - 1);
  414. if (scaleIndex() > 0)
  415. setScale (splitRoot, scaleIndex());
  416. };
  417. scaleNameBox.onChange = [this] {
  418. const auto id = scaleNameBox.getSelectedId();
  419. if (id == autoScaleId)
  420. setAutoScale (true);
  421. else
  422. setScale (scaleIndex() > 0 ? scaleRoot() : splitRoot, id >= 100 ? id / 100 : 0);
  423. };
  424. for (auto* box : { &scaleRootBox, &scaleNameBox })
  425. {
  426. box->setWantsKeyboardFocus (false);
  427. box->setMouseClickGrabsKeyboardFocus (false);
  428. addChildComponent (box);
  429. }
  430. refreshScaleBoxes();
  431. // round 170e: an icon (FL's slide tool is one) instead of the word "Slide"
  432. slideButton.setClickingTogglesState (true);
  433. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)"));
  434. ui::setQuickTip (slideButton, tr ("Slide notes"));
  435. slideButton.setWantsKeyboardFocus (false);
  436. slideButton.setMouseClickGrabsKeyboardFocus (false);
  437. slideButton.setOnColour (theme::colour::bg6);
  438. slideButton.setIconColourWhenOn (theme::colour::accent);
  439. slideButton.setFlat (true);
  440. addAndMakeVisible (slideButton);
  441. ui::setQuickTip (chordBox, tr ("Chord stamp"));
  442. ui::setQuickTip (scaleBox, tr ("Scale"));
  443. chordBox.iconLit = [this] { return chordBox.getSelectedId() > 1; };
  444. scaleBox.iconLit = [this] { return scaleIndex() > 0; };
  445. colourButton.setTooltip (tr ("Note colour: new notes get this colour. Click: choose it, colour the selection (Alt+C), "
  446. "select by colour (Shift+C)"));
  447. ui::setQuickTip (colourButton, tr ("Note colour"));
  448. colourButton.setWantsKeyboardFocus (false);
  449. colourButton.setMouseClickGrabsKeyboardFocus (false);
  450. colourButton.onClick = [this] { showColourMenu(); };
  451. addAndMakeVisible (colourButton);
  452. chordLabel.setJustificationType (juce::Justification::centred);
  453. chordLabel.setFont (theme::font (theme::type::caption, true));
  454. chordLabel.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  455. chordLabel.setTooltip (tr ("Chord: the chord of the keys held on the MIDI keyboard or the typing piano, else of the selected notes"));
  456. chordLabel.setInterceptsMouseClicks (true, false);
  457. addAndMakeVisible (chordLabel);
  458. // "Show chord name for selection" (round 168g): FL shows it as a hint 16 px into the editor's top-left corner
  459. chordBubble.setJustificationType (juce::Justification::centred);
  460. chordBubble.setFont (theme::font (theme::type::body, true));
  461. chordBubble.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  462. chordBubble.setColour (juce::Label::backgroundColourId, theme::colour::bg4.withAlpha (0.94f));
  463. chordBubble.setColour (juce::Label::outlineColourId, theme::colour::accent.withAlpha (0.8f));
  464. chordBubble.setInterceptsMouseClicks (false, false);
  465. addChildComponent (chordBubble);
  466. for (auto* box : { static_cast<IconComboBox*> (&chordBox), static_cast<IconComboBox*> (&scaleBox) })
  467. {
  468. box->setWantsKeyboardFocus (false);
  469. box->setMouseClickGrabsKeyboardFocus (false);
  470. box->onChange = [this] {
  471. publishScale();
  472. refreshScaleBoxes(); // (issue #203: the docked root / scale boxes show the choice)
  473. scaleSnapButton.setEnabled (scaleIndex() > 0);
  474. if (rows.count < 128 || foldToScale)
  475. updateKeyRows(); // the folded rows follow the scale
  476. repaint();
  477. };
  478. addAndMakeVisible (box);
  479. }
  480. addNoteLanes();
  481. laneBox.setTooltip (tr ("What the bottom lane edits"));
  482. laneBox.setSelectedId (1, juce::dontSendNotification);
  483. laneBox.setWantsKeyboardFocus (false);
  484. laneBox.setMouseClickGrabsKeyboardFocus (false);
  485. laneBox.onChange = [this] {
  486. if (fitKeysToNotes) // (round gap190og: the Live footer comes and goes with the Velocity lane)
  487. resized();
  488. repaint();
  489. };
  490. addAndMakeVisible (laneBox);
  491. // round gap190og (detail-047): Live's Velocity Controls (shown by resized only in the docked Live look)
  492. liveRandomize.setButtonText (tr ("Randomize"));
  493. liveRandomize.setTooltip (tr ("Randomize: the selected notes' velocities (all the notes with none selected) move at random by up to the amount beside it"));
  494. liveRandomize.setWantsKeyboardFocus (false);
  495. liveRandomize.onClick = [this] { liveRandomizeVelocity(); };
  496. addChildComponent (liveRandomize);
  497. liveRandomAmount = std::make_unique<LiveAmountBox>();
  498. liveRandomAmount->onEnter = [this] { liveRandomizeVelocity(); };
  499. addChildComponent (*liveRandomAmount);
  500. // round 190on (P10): "+" adds a lane above (only while stacked lanes are offered; core/StackedLanes.h)
  501. addLaneButton.setTooltip (tr ("Add a lane above (stacked lanes, LYNX)"));
  502. addLaneButton.setWantsKeyboardFocus (false);
  503. addLaneButton.setMouseClickGrabsKeyboardFocus (false);
  504. addLaneButton.onClick = [this] { addStackedLane(); };
  505. addChildComponent (addLaneButton);
  506. setOpaque (true); // paints every pixel: nothing behind it is redrawn while scrolling
  507. engine.addChangeListener (this);
  508. EditorGlobals::get().addChangeListener (this);
  509. refreshChannelBox();
  510. showingTimer = std::make_unique<ui::TimerWhileShowing> (*this, static_cast<juce::Timer&> (*this), 30); // (stopped while hidden; round 174f)
  511. }
  512. PianoRollComponent::~PianoRollComponent()
  513. {
  514. stopListening();
  515. previewNotes.releaseAll();
  516. EditorGlobals::get().removeChangeListener (this);
  517. engine.removeChangeListener (this);
  518. }
  519. juce::Rectangle<int> PianoRollComponent::gridArea() const
  520. {
  521. return getLocalBounds().withTrimmedLeft (keyboardWidth).withTrimmedTop (headerHeight)
  522. .withTrimmedRight (scrollBarSize).withTrimmedBottom (velocityHeight + eventPaneBarArea().getHeight() + liveFooterHeight());
  523. }
  524. // Round gap190og (detail-047): Live's footer under the editor lanes holds the Velocity Controls; LYNX draws it while the
  525. // 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)
  526. int PianoRollComponent::liveFooterHeight() const
  527. {
  528. return liveNotes() && ! mpeStacked && velocityHeight >= 24 && laneBox.getSelectedId() == laneVelocity ? liveFooterBar : 0;
  529. }
  530. void PianoRollComponent::liveFooterCheck()
  531. {
  532. if (liveFooterHeight() != laidFooter)
  533. {
  534. resized();
  535. repaint();
  536. }
  537. }
  538. void PianoRollComponent::liveRandomizeVelocity()
  539. {
  540. // the selected notes, or every note of the channel shown when none is selected (manual 10.5.12)
  541. const auto target = selectionOrAll();
  542. if (target.empty())
  543. return;
  544. const auto amount = liveRandomizeAmount;
  545. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
  546. editNotes ([&target, amount, seed] (Pattern& p) { cliploop::randomizeVelocity (p, target, amount, seed); });
  547. repaint();
  548. }
  549. juce::Rectangle<int> PianoRollComponent::eventPaneArea() const
  550. {
  551. const auto grid = gridArea();
  552. return { grid.getX(), grid.getBottom() + eventPaneBarArea().getHeight(), grid.getWidth(), velocityHeight };
  553. }
  554. juce::Rectangle<int> PianoRollComponent::velocityArea() const
  555. {
  556. if (! laneAreaOverride.isEmpty())
  557. return laneAreaOverride;
  558. if (stacked.empty())
  559. return eventPaneArea();
  560. return laneAreas().back();
  561. }
  562. // --- round 190on (research190oe P10): stacked controller lanes (core/StackedLanes.h) --------------------------------------
  563. std::vector<juce::Rectangle<int>> PianoRollComponent::laneAreas() const
  564. {
  565. const auto pane = eventPaneArea();
  566. if (stacked.empty())
  567. return { pane };
  568. std::vector<float> weights;
  569. for (const auto& l : stacked)
  570. weights.push_back (l->spec.weight);
  571. weights.push_back (bottomWeight);
  572. const auto heights = stackedlanes::heights (weights, pane.getHeight(), 0);
  573. std::vector<juce::Rectangle<int>> out;
  574. auto y = pane.getY();
  575. for (const auto h : heights)
  576. {
  577. out.push_back ({ pane.getX(), y, pane.getWidth(), h });
  578. y += h;
  579. }
  580. return out;
  581. }
  582. std::vector<std::pair<juce::Rectangle<int>, int>> PianoRollComponent::laneAreasForTests() const
  583. {
  584. std::vector<std::pair<juce::Rectangle<int>, int>> out;
  585. const auto areas = laneAreas();
  586. for (std::size_t i = 0; i < areas.size(); ++i)
  587. out.push_back ({ areas[i], i < stacked.size() ? stackedLaneId (*stacked[i]) : laneBox.getSelectedId() });
  588. return out;
  589. }
  590. PianoRollComponent::LaneScope::LaneScope (PianoRollComponent& o, int index)
  591. : owner (o), savedId (o.laneOverride), savedPainting (o.paintingLane), savedArea (o.laneAreaOverride)
  592. {
  593. owner.paintingLane = index;
  594. if (index >= 0)
  595. owner.enterLane (index);
  596. else
  597. {
  598. owner.laneOverride = 0;
  599. owner.laneAreaOverride = {};
  600. }
  601. }
  602. PianoRollComponent::LaneScope::~LaneScope()
  603. {
  604. owner.laneOverride = savedId;
  605. owner.paintingLane = savedPainting;
  606. owner.laneAreaOverride = savedArea;
  607. }
  608. void PianoRollComponent::enterLane (int index)
  609. {
  610. if (index < 0 || index >= (int) stacked.size())
  611. {
  612. laneOverride = 0;
  613. laneAreaOverride = {};
  614. return;
  615. }
  616. laneOverride = stackedLaneId (*stacked[(std::size_t) index]);
  617. laneAreaOverride = laneAreas()[(std::size_t) index];
  618. }
  619. int PianoRollComponent::stackedLaneId (const StackedLane& lane) const
  620. {
  621. if (lane.spec.target)
  622. {
  623. const auto it = std::find (eventTargets.begin(), eventTargets.end(), *lane.spec.target);
  624. return it == eventTargets.end() ? laneVelocity : eventLaneIdBase + (int) (it - eventTargets.begin());
  625. }
  626. return juce::jlimit (laneVelocity, laneVelocityRange, lane.spec.property);
  627. }
  628. juce::String PianoRollComponent::laneName() const
  629. {
  630. if (laneOverride != 0)
  631. for (const auto& l : stacked)
  632. if (stackedLaneId (*l) == laneOverride)
  633. return l->box.getText();
  634. return laneBox.getText();
  635. }
  636. int PianoRollComponent::stackedLaneAt (juce::Point<int> p) const
  637. {
  638. if (stacked.empty())
  639. return -1;
  640. const auto areas = laneAreas();
  641. for (std::size_t i = 0; i + 1 < areas.size(); ++i)
  642. if (areas[i].withX (0).withWidth (areas[i].getRight()).contains (p))
  643. return (int) i;
  644. return -1;
  645. }
  646. int PianoRollComponent::laneBoundaryAt (juce::Point<int> p) const
  647. {
  648. if (stacked.empty() || p.x < keyboardWidth)
  649. return -1;
  650. const auto areas = laneAreas();
  651. for (std::size_t i = 0; i + 1 < areas.size(); ++i)
  652. if (std::abs (p.y - areas[i].getBottom()) <= 2 && areas[i].getRight() > p.x)
  653. return (int) i;
  654. return -1;
  655. }
  656. bool PianoRollComponent::stackingEnabled() const
  657. {
  658. return stackedlanes::enabled (layoutstyle::current() == layoutstyle::Style::clipLaunch, stackedLanesExtra) && ! mpeStacked;
  659. }
  660. void PianoRollComponent::rebuildStackedBoxes()
  661. {
  662. for (auto& l : stacked)
  663. {
  664. auto& box = l->box;
  665. box.clear (juce::dontSendNotification);
  666. box.addItem (tr ("Velocity"), laneVelocity);
  667. box.addItem (tr ("Pan"), lanePan);
  668. box.addItem (tr ("Fine pitch"), laneFinePitch);
  669. box.addItem (tr ("Release"), laneRelease);
  670. box.addItem (tr ("Mod X"), laneModX);
  671. box.addItem (tr ("Mod Y"), laneModY);
  672. box.addItem (tr ("Chance"), laneChance);
  673. box.addItem (tr ("Velocity range (LYNX)"), laneVelocityRange);
  674. if (! eventTargets.empty())
  675. box.addSectionHeading (tr ("Pattern events"));
  676. for (int k = 0; k < (int) eventTargets.size(); ++k)
  677. box.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
  678. box.setSelectedId (stackedLaneId (*l), juce::dontSendNotification);
  679. }
  680. }
  681. void PianoRollComponent::loadStackedLanes()
  682. {
  683. for (auto& l : stacked)
  684. {
  685. removeChildComponent (&l->box);
  686. removeChildComponent (&l->close);
  687. }
  688. stacked.clear();
  689. stackingWas = stackingEnabled();
  690. if (stackingWas)
  691. for (const auto& spec : stackedlanes::fromText (stackedLanesSaved, &bottomWeight, laneVelocityRange))
  692. {
  693. auto lane = std::make_unique<StackedLane>();
  694. lane->spec = spec;
  695. stacked.push_back (std::move (lane));
  696. }
  697. for (auto& l : stacked)
  698. {
  699. auto* raw = l.get();
  700. raw->box.setTooltip (tr ("What this lane edits"));
  701. raw->box.setWantsKeyboardFocus (false);
  702. raw->box.setMouseClickGrabsKeyboardFocus (false);
  703. raw->box.onChange = [this, raw] {
  704. const auto id = raw->box.getSelectedId();
  705. if (id >= eventLaneIdBase && id - eventLaneIdBase < (int) eventTargets.size())
  706. raw->spec.target = eventTargets[(std::size_t) (id - eventLaneIdBase)];
  707. else
  708. {
  709. raw->spec.target.reset();
  710. raw->spec.property = id;
  711. }
  712. saveStackedLanes();
  713. repaint();
  714. };
  715. raw->close.setTooltip (tr ("Remove this lane"));
  716. raw->close.setWantsKeyboardFocus (false);
  717. raw->close.setMouseClickGrabsKeyboardFocus (false);
  718. raw->close.onClick = [this, raw] {
  719. for (int i = 0; i < (int) stacked.size(); ++i)
  720. if (stacked[(std::size_t) i].get() == raw)
  721. {
  722. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<PianoRollComponent> (this), i] {
  723. if (safe != nullptr)
  724. safe->removeStackedLane (i);
  725. });
  726. return;
  727. }
  728. };
  729. addAndMakeVisible (raw->box);
  730. addAndMakeVisible (raw->close);
  731. }
  732. // the lanes' event targets are in the choosers' lists
  733. rebuildLaneBox (std::nullopt, true);
  734. rebuildStackedBoxes();
  735. layoutEventPane();
  736. resized();
  737. repaint();
  738. }
  739. void PianoRollComponent::stackedLanesChanged()
  740. {
  741. loadStackedLanes();
  742. }
  743. void PianoRollComponent::saveStackedLanes()
  744. {
  745. std::vector<stackedlanes::Lane> specs;
  746. for (const auto& l : stacked)
  747. specs.push_back (l->spec);
  748. stackedLanesSaved = stackedlanes::toText (specs, bottomWeight);
  749. if (EditorGlobals::get().onOptionsChanged)
  750. EditorGlobals::get().onOptionsChanged();
  751. }
  752. void PianoRollComponent::addStackedLane()
  753. {
  754. if (! stackingEnabled() || (int) stacked.size() >= stackedlanes::maxAdded)
  755. return;
  756. // a property the lanes don't show yet (velocity, pan, mod X, mod Y, release, fine pitch, chance, then velocity again)
  757. int property = laneVelocity;
  758. for (const auto candidate : { laneVelocity, lanePan, laneModX, laneModY, laneRelease, laneFinePitch, laneChance })
  759. {
  760. const auto used = laneBox.getSelectedId() == candidate
  761. || std::any_of (stacked.begin(), stacked.end(), [&] (const auto& l) { return ! l->spec.target && l->spec.property == candidate; });
  762. if (! used)
  763. {
  764. property = candidate;
  765. break;
  766. }
  767. }
  768. addStackedLaneForSnapshot (property);
  769. }
  770. void PianoRollComponent::addStackedLaneForSnapshot (int property, std::optional<AutomationTarget> target)
  771. {
  772. std::vector<stackedlanes::Lane> specs;
  773. for (const auto& l : stacked)
  774. specs.push_back (l->spec);
  775. if ((int) specs.size() >= stackedlanes::maxAdded)
  776. return;
  777. stackedlanes::Lane lane;
  778. lane.property = property;
  779. lane.target = target;
  780. specs.insert (specs.begin(), lane); // (the new lane at the top: the lanes already there keep their places)
  781. stackedLanesSaved = stackedlanes::toText (specs, bottomWeight);
  782. loadStackedLanes();
  783. if (fitKeysToNotes) // (the docked editor grows its lanes' area, as its MPE tab does)
  784. layoutEventPane();
  785. saveStackedLanes();
  786. }
  787. void PianoRollComponent::removeStackedLane (int index)
  788. {
  789. if (index < 0 || index >= (int) stacked.size())
  790. return;
  791. std::vector<stackedlanes::Lane> specs;
  792. for (int i = 0; i < (int) stacked.size(); ++i)
  793. if (i != index)
  794. specs.push_back (stacked[(std::size_t) i]->spec);
  795. stackedLanesSaved = stackedlanes::toText (specs, bottomWeight);
  796. loadStackedLanes();
  797. saveStackedLanes();
  798. }
  799. void PianoRollComponent::dragInLaneForSnapshot (int lane, int fromX, int toX, float from, float to)
  800. {
  801. const auto areas = laneAreas();
  802. if (lane < 0 || lane >= (int) areas.size())
  803. return;
  804. const auto area = areas[(std::size_t) lane];
  805. const auto yOf = [&area] (float v) { return area.getBottom() - 2 - juce::roundToInt (v * (float) (area.getHeight() - 8)); };
  806. auto source = juce::Desktop::getInstance().getMainMouseSource();
  807. const auto now = juce::Time::getCurrentTime();
  808. const auto event = [&] (int x, float v, juce::ModifierKeys mods) {
  809. const juce::Point<float> at ((float) x, (float) yOf (v));
  810. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, this, this, now, at, now, 1, false);
  811. };
  812. const auto left = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  813. mouseDown (event (fromX, from, left));
  814. mouseDrag (event (toX, to, left));
  815. mouseUp (event (toX, to, {}));
  816. }
  817. // --- the event editor's divider (round 190fz; FL's TQuickSplitter, the facts in core/EventPaneSplit.h) ---------------
  818. namespace
  819. {
  820. juce::File eventPaneFile() { return platform::settingsFile ("piano-roll-event-pane.txt"); }
  821. } // namespace
  822. evpane::State& PianoRollComponent::eventPaneState()
  823. {
  824. static evpane::State state = evpane::fromText (eventPaneFile().loadFileAsString().toStdString());
  825. return state;
  826. }
  827. void PianoRollComponent::saveEventPaneState()
  828. {
  829. eventPaneFile().replaceWithText (juce::String (evpane::toText (eventPaneState())));
  830. }
  831. juce::Rectangle<int> PianoRollComponent::eventPaneBarArea() const
  832. {
  833. if (fitKeysToNotes) // the Clip-launch dock keeps its short fixed lane (Live's detail view; no divider there)
  834. return {};
  835. return { 0, eventPaneBarTop, getWidth(), evpane::barThickness };
  836. }
  837. void PianoRollComponent::layoutEventPane()
  838. {
  839. if (fitKeysToNotes)
  840. {
  841. // (round 190jd: the MPE tab's lanes, 40 px each as Live's, + the "Show Lane" footer; at most half of the dock,
  842. // at least 22 px a lane, so the notes stay in view; core/MpeTab.h)
  843. if (mpeStacked)
  844. velocityHeight = mpetab::areaHeight (mpetab::countOf (mpeShownLanes), getHeight() - headerHeight);
  845. else if (! stacked.empty()) // round 190on (P10): 40 px a lane, as the MPE tab's, at most half of the dock
  846. velocityHeight = juce::jlimit (compactVelocityHeight, juce::jmax (compactVelocityHeight, (getHeight() - headerHeight) / 2), 40 * ((int) stacked.size() + 1));
  847. eventPaneBarTop = getHeight() - velocityHeight - liveFooterHeight();
  848. return;
  849. }
  850. // the bar's travel: from under the ruler (the grid folded away) to the bottom edge (the event editor folded away);
  851. // the remembered place is a fraction of it, so a taller or shorter window keeps the proportion (FL)
  852. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  853. eventPaneBarTop = evpane::barTopOf (eventPaneState().aspect, top, bottom);
  854. velocityHeight = juce::jmax (0, getHeight() - eventPaneBarTop - evpane::barThickness);
  855. }
  856. void PianoRollComponent::eventPaneChanged()
  857. {
  858. resized();
  859. repaint();
  860. ui::Hint hint; // FL's hint bar shows the place as a percentage while it changes ("80%")
  861. hint.value = juce::String (evpane::percentOf (eventPaneState().aspect)) + "%";
  862. ui::postHint (hint);
  863. }
  864. void PianoRollComponent::moveEventPaneBar (int y)
  865. {
  866. if (fitKeysToNotes)
  867. return;
  868. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  869. eventPaneState().aspect = evpane::aspectOf (evpane::clampBar (y, top, bottom), top, bottom);
  870. eventPaneChanged();
  871. }
  872. void PianoRollComponent::toggleEventPaneAlternate()
  873. {
  874. if (fitKeysToNotes)
  875. return;
  876. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  877. evpane::toggleAlternate (eventPaneState(), evpane::aspectOf (eventPaneBarTop, top, bottom));
  878. eventPaneChanged();
  879. saveEventPaneState();
  880. }
  881. void PianoRollComponent::resetEventPane()
  882. {
  883. if (fitKeysToNotes)
  884. return;
  885. evpane::resetToDefault (eventPaneState());
  886. eventPaneChanged();
  887. saveEventPaneState();
  888. }
  889. double PianoRollComponent::tickToX (double tick) const
  890. {
  891. return keyboardWidth + (tick - scrollTicks) * pixelsPerTick;
  892. }
  893. double PianoRollComponent::xToTick (int x) const
  894. {
  895. return (x - keyboardWidth) / pixelsPerTick + scrollTicks;
  896. }
  897. int PianoRollComponent::keyToY (int key) const
  898. {
  899. return headerHeight + rowFor (key) * rowHeight - scrollY;
  900. }
  901. int PianoRollComponent::rowFor (int key) const noexcept
  902. {
  903. key = juce::jlimit (0, 127, key);
  904. const auto row = rows.rowOfKey[(std::size_t) key];
  905. return row >= 0 ? row : rows.rowOfKey[(std::size_t) rows.step (key, 0)]; // a folded key: the row above it
  906. }
  907. void PianoRollComponent::updateKeyRows()
  908. {
  909. // keep the key at the top of the view where it is when the rows change (fold on/off, another scale)
  910. const auto topKey = yToKey (headerHeight);
  911. rows = ! padRows.empty() ? notetools::keyRowsOf (padRows) : notetools::keyRows (scaleRoot(), scaleIndex(), foldToScale);
  912. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), rowFor (topKey) * rowHeight);
  913. updateScrollBars();
  914. repaint();
  915. }
  916. std::vector<int> PianoRollComponent::wantedPadRows() const
  917. {
  918. const auto& song = engine.getSong();
  919. const auto channel = engine.getSelectedChannel();
  920. if (! EditorGlobals::get().clipLaunchWorkflow || allChannels || channel < 0 || channel >= (int) song.channels.size()
  921. || ! rack::isDrumRack (song.channels[(std::size_t) channel]))
  922. return {};
  923. return rack::filledPadKeys (*rack::rackOf (song.channels[(std::size_t) channel].patcher));
  924. }
  925. void PianoRollComponent::syncPadRows()
  926. {
  927. if (auto wanted = wantedPadRows(); wanted != padRows)
  928. {
  929. padRows = std::move (wanted);
  930. updateKeyRows();
  931. }
  932. }
  933. void PianoRollComponent::setFoldToScale (bool on)
  934. {
  935. foldToScale = on;
  936. updateKeyRows();
  937. }
  938. int PianoRollComponent::yToKey (int y) const
  939. {
  940. const auto row = juce::jlimit (0, juce::jmax (0, rows.count - 1), (y - headerHeight + scrollY) / rowHeight);
  941. return rows.keyOfRow[(std::size_t) row];
  942. }
  943. void PianoRollComponent::setKeyStyle (pianokeys::Style style)
  944. {
  945. if (style == keyStyle)
  946. return;
  947. keyStyle = style;
  948. if (EditorGlobals::get().onOptionsChanged)
  949. EditorGlobals::get().onOptionsChanged(); // (the main window saves it and repaints the other editors)
  950. repaint();
  951. }
  952. int PianoRollComponent::keyboardKeyAt (int x, int y) const
  953. {
  954. const auto key = yToKey (y);
  955. if (! pianokeys::whiteKeysMeet (keyStyle) || folded())
  956. return key;
  957. // "Piano keys" / FL's keys: right of a black key the white keys above and below it meet in the middle of its row
  958. const auto next = pianokeys::keyAt (keyStyle, key, y - keyToY (key), rowHeight, x, blackKeyWidth);
  959. return juce::isPositiveAndBelow (next, 128) && rows.shown (next) ? next : key;
  960. }
  961. std::int64_t PianoRollComponent::gridTicks() const
  962. {
  963. if (liveGridOn()) // round 190hr: the reference's grid while docked in the Clip-launch detail view
  964. return liveGrid.snap ? std::max<std::int64_t> (1, livegrid::stepTicks (liveGrid, pixelsPerTick)) : 1;
  965. const auto bar = engine.getSong().barTicks();
  966. const auto& option = grid::resolve (snapBox);
  967. switch (option.kind)
  968. {
  969. case grid::Kind::none: return 1;
  970. case grid::Kind::ticks: return option.ticks;
  971. case grid::Kind::bar: return bar;
  972. case grid::Kind::screen:
  973. case grid::Kind::nearest: break;
  974. }
  975. return noteedit::screenStep (pixelsPerTick, bar);
  976. }
  977. std::vector<std::int64_t> PianoRollComponent::snapCandidates() const
  978. {
  979. // edges of this channel's notes (except the ones being dragged) and of the visible ghosts
  980. std::vector<std::int64_t> out;
  981. const auto& notes = currentPattern (engine.getSong()).notes;
  982. for (int i = 0; i < (int) notes.size(); ++i)
  983. {
  984. const auto& n = notes[(std::size_t) i];
  985. if ((! edits (n) && (! showGhosts || ! ghostShown (n.channel))) || std::find (dragIndices.begin(), dragIndices.end(), i) != dragIndices.end())
  986. continue;
  987. out.push_back (n.start);
  988. out.push_back (n.start + n.length);
  989. }
  990. return out;
  991. }
  992. std::int64_t PianoRollComponent::snap (double tick, bool enabled) const
  993. {
  994. if (! enabled)
  995. return (std::int64_t) std::floor (tick);
  996. if (! liveGridOn() && grid::resolve (snapBox).kind == grid::Kind::nearest)
  997. return noteedit::snapNearest (tick, snapCandidates(), 10.0 / pixelsPerTick, gridTicks());
  998. return noteedit::snapDown (tick, gridTicks());
  999. }
  1000. std::int64_t PianoRollComponent::newNoteLength() const
  1001. {
  1002. const auto fixed = EditorGlobals::get().getDefaultNoteLength();
  1003. return fixed > 0 ? fixed : lastLength;
  1004. }
  1005. std::int64_t PianoRollComponent::viewLengthTicks() const
  1006. {
  1007. const auto& song = engine.getSong();
  1008. const auto bar = song.barTicks();
  1009. // pattern + 4 bars of headroom to grow
  1010. return currentPattern (song).effectiveLength (song.meter()) + 4 * bar;
  1011. }
  1012. void PianoRollComponent::updateScrollBars()
  1013. {
  1014. const auto grid = gridArea();
  1015. const auto total = (double) viewLengthTicks();
  1016. hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
  1017. hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
  1018. vBar.setRangeLimits (0.0, (double) rows.count * rowHeight, juce::dontSendNotification);
  1019. vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
  1020. scrollTicks = hBar.getCurrentRangeStart();
  1021. scrollY = (int) vBar.getCurrentRangeStart();
  1022. overview.minLength = grid.getWidth() / (120.0 / ticksPerStep);
  1023. overview.setRange (total, scrollTicks, grid.getWidth() / pixelsPerTick);
  1024. }
  1025. void PianoRollComponent::setTitleBarInsets (int left, int right)
  1026. {
  1027. if (left != titleInsetLeft || right != titleInsetRight)
  1028. {
  1029. titleInsetLeft = left;
  1030. titleInsetRight = right;
  1031. resized();
  1032. }
  1033. }
  1034. void PianoRollComponent::resized()
  1035. {
  1036. layoutEventPane(); // (round 190fz: the grid / event editor heights from the divider's place)
  1037. const auto h = toolbarHeight - 6;
  1038. auto bar = juce::Rectangle<int> (4 + titleInsetLeft, 3, juce::jmax (0, getWidth() - 8 - titleInsetLeft - titleInsetRight), h);
  1039. // groups that don't fit in a narrow window are hidden (the tools and the grid always show). The menu button always
  1040. // keeps its place: the optional groups only take what is left beside it (round 190j: on a 1024 px screen the
  1041. // groups before it used up the bar and the Piano roll menu could not be opened).
  1042. const auto reserved = h + 6;
  1043. auto place = [&bar, reserved] (juce::Component& c, int width, bool optional = false) {
  1044. const auto fits = ! optional || width <= bar.getWidth() - reserved;
  1045. c.setVisible (fits);
  1046. c.setBounds (fits ? bar.removeFromLeft (juce::jmin (width, bar.getWidth())) : juce::Rectangle<int>());
  1047. bar.removeFromLeft (juce::jmin (6, bar.getWidth()));
  1048. };
  1049. place (playButton, h);
  1050. place (channelBox, 150);
  1051. place (tools, tools.getIdealWidth (h));
  1052. if (liveGridOn()) // round 190hr: the reference's grid value in place of FL's snap box
  1053. {
  1054. snapBox.setVisible (false);
  1055. liveGridButton.setButtonText (liveGrid.snap ? juce::String (livegrid::stepText (gridTicks(), liveGrid.triplet)) + juce::String::fromUTF8 (" \xe2\x96\xbe")
  1056. : tr ("Off") + juce::String::fromUTF8 (" \xe2\x96\xbe"));
  1057. place (liveGridButton, 72);
  1058. }
  1059. else
  1060. {
  1061. liveGridButton.setVisible (false);
  1062. place (snapBox, 128);
  1063. }
  1064. place (ghostButton, h);
  1065. place (followButton, h);
  1066. place (slideButton, h, true);
  1067. place (colourButton, h, true);
  1068. // the chord stamp shrinks to its icon and arrow before it is hidden (discussion #10; FL's stamp is an icon button)
  1069. place (chordBox, 100 <= bar.getWidth() - reserved ? 100 : pianoroll::compactChordBoxWidth, true);
  1070. if (splitScaleBoxes()) // (issue #203: docked, the root and the scale apart, as Live's Clip View and BandLab)
  1071. {
  1072. scaleBox.setVisible (false);
  1073. place (scaleRootBox, 52, true);
  1074. if (scaleRootBox.isVisible())
  1075. place (scaleNameBox, 124, true);
  1076. else
  1077. scaleNameBox.setVisible (false);
  1078. }
  1079. else
  1080. {
  1081. scaleRootBox.setVisible (false);
  1082. scaleNameBox.setVisible (false);
  1083. place (scaleBox, 164, true);
  1084. }
  1085. if (splitScaleBoxes() ? scaleNameBox.isVisible() : scaleBox.isVisible())
  1086. place (scaleSnapButton, h);
  1087. else
  1088. scaleSnapButton.setVisible (false);
  1089. place (moreButton, h);
  1090. place (chordLabel, 84, true);
  1091. // round 190on (P10): the stacked lanes follow the switch and the layout; with them offered, the "+" sits right of the
  1092. // bottom lane's chooser and each added lane has its chooser and "×" (FL's single lane is unchanged otherwise)
  1093. if (stackingWas != stackingEnabled())
  1094. return loadStackedLanes(); // (it lays everything out again)
  1095. const auto offered = stackingWas && velocityHeight >= 24 && ! mpeStacked;
  1096. const auto buttonSide = 20, chooserWidth = keyboardWidth - 4 - (offered ? buttonSide + 2 : 0);
  1097. laneBox.setBounds (2, velocityArea().getY() + 4, chooserWidth, 20);
  1098. addLaneButton.setBounds (2 + chooserWidth + 2, velocityArea().getY() + 4, buttonSide, buttonSide);
  1099. laidFooter = liveFooterHeight();
  1100. if (const auto footer = laidFooter; footer > 0)
  1101. {
  1102. // Live's footer (capture x 500…559 the button, 566…603 the amount; both 13 px high, 3 px under the footer's line)
  1103. const auto y = getHeight() - footer + 3;
  1104. // (Live: the lane chooser sits in the footer, at its left; rollup 0.1.31 step 5: with stacked lanes offered, round
  1105. // 190on's "+" stays beside it there, at the footer's size)
  1106. const auto footerSide = 15;
  1107. laneBox.setBounds (4, y - 1, keyboardWidth - 8 - (offered ? footerSide + 2 : 0), 15);
  1108. addLaneButton.setBounds (laneBox.getRight() + 2, y - 1, footerSide, footerSide);
  1109. liveRandomize.setBounds (keyboardWidth + 22, y, 60, 13);
  1110. liveRandomAmount->setBounds (liveRandomize.getRight() + 6, y, 38, 13);
  1111. liveRandomize.setVisible (true);
  1112. liveRandomAmount->setVisible (true);
  1113. }
  1114. else
  1115. {
  1116. liveRandomize.setVisible (false);
  1117. liveRandomAmount->setVisible (false);
  1118. }
  1119. laneBox.setVisible (velocityHeight >= 24 && ! mpeStacked); // (the event editor folded away: FL hides its target panel too; the MPE tab names its lanes)
  1120. addLaneButton.setVisible (offered && (int) stacked.size() < stackedlanes::maxAdded);
  1121. {
  1122. const auto areas = laneAreas();
  1123. for (std::size_t i = 0; i < stacked.size() && i < areas.size(); ++i)
  1124. {
  1125. const auto shown = offered && areas[i].getHeight() >= 22;
  1126. stacked[i]->box.setBounds (2, areas[i].getY() + juce::jmin (4, (areas[i].getHeight() - 20) / 2), chooserWidth, 20);
  1127. stacked[i]->close.setBounds (2 + chooserWidth + 2, stacked[i]->box.getY(), buttonSide, buttonSide);
  1128. stacked[i]->box.setVisible (shown);
  1129. stacked[i]->close.setVisible (shown);
  1130. }
  1131. }
  1132. overview.setBounds (keyboardWidth, toolbarHeight, getWidth() - keyboardWidth - zoomWheelSize, overviewHeight);
  1133. vBar.setBounds (getWidth() - scrollBarSize, headerHeight, scrollBarSize, gridArea().getHeight());
  1134. updateScrollBars();
  1135. }
  1136. void PianoRollComponent::squeezeToolbarForSnapshot (int pixels)
  1137. {
  1138. setTitleBarInsets (titleInsetLeft, titleInsetRight + pixels);
  1139. }
  1140. void PianoRollComponent::scrollToNotes (bool fitPattern)
  1141. {
  1142. const auto& song = engine.getSong();
  1143. int low = 128, high = -1;
  1144. for (const auto& n : currentPattern (song).notes)
  1145. if (edits (n))
  1146. {
  1147. low = juce::jmin (low, n.key);
  1148. high = juce::jmax (high, n.key);
  1149. }
  1150. refreshChannelBox();
  1151. if (fitKeysToNotes && high >= 0 && gridArea().getHeight() > 0) // docked: every note's row in the short view, as far as the key height allows
  1152. {
  1153. const auto span = std::abs (rowFor (low) - rowFor (high)) + 3;
  1154. rowHeight = juce::jlimit (gesture::minKeyHeight, undockedRowHeight, gridArea().getHeight() / span);
  1155. }
  1156. const auto centreKey = high >= 0 ? (low + high) / 2 : 66;
  1157. scrollY = rowFor (centreKey) * rowHeight - gridArea().getHeight() / 2;
  1158. scrollTicks = 0.0;
  1159. // FL opens the Piano Roll with the whole pattern across the view (at least one bar)
  1160. if (fitPattern && gridArea().getWidth() > 0)
  1161. {
  1162. const auto bar = (double) song.barTicks();
  1163. const auto length = juce::jmax (bar, (double) currentPattern (song).effectiveLength (song.meter()));
  1164. pixelsPerTick = juce::jlimit (4.0 / ticksPerStep, 64.0 / ticksPerStep, gridArea().getWidth() / length);
  1165. }
  1166. updateScrollBars();
  1167. repaint();
  1168. }
  1169. // --- selection ---------------------------------------------------------------
  1170. std::vector<int> PianoRollComponent::chordIntervals() const
  1171. {
  1172. const auto index = juce::jlimit (0, (int) chords().size() - 1, chordBox.getSelectedId() - 1);
  1173. auto intervals = chords()[(std::size_t) index].intervals;
  1174. // FL 2026's top-down stamp (REA round 153): the clicked key is the chord's highest note
  1175. if (chordTopDown && intervals.size() > 1)
  1176. {
  1177. const auto top = *std::max_element (intervals.begin(), intervals.end());
  1178. for (auto& i : intervals)
  1179. i -= top;
  1180. std::reverse (intervals.begin(), intervals.end()); // the clicked (top) note first: it leads the drag
  1181. }
  1182. return intervals;
  1183. }
  1184. // --- round 190nu: key regions and the Scale degree chord (core/KeyRegions.h) ------------------------------------------
  1185. keyregions::Degrees PianoRollComponent::scaleDegreesAt (std::int64_t tick) const
  1186. {
  1187. const auto state = keyregions::stateAt (currentPattern (engine.getSong()), tick);
  1188. if (state.kind == keyregions::State::key)
  1189. return keyregions::degreesOf (state.value);
  1190. if (state.kind == keyregions::State::none)
  1191. return {};
  1192. if (isAutoScale()) // (the guessed key: 0..11 major, 12..23 minor)
  1193. {
  1194. if (autoKey < 0)
  1195. return {};
  1196. return autoKey < 12 ? keyregions::Degrees { autoKey, { 0, 2, 4, 5, 7, 9, 11 } } : keyregions::Degrees { autoKey - 12, { 0, 2, 3, 5, 7, 8, 10 } };
  1197. }
  1198. if (scaleIndex() > 0)
  1199. return { scaleRoot(), notetools::scales()[(std::size_t) scaleIndex()].intervals };
  1200. return {};
  1201. }
  1202. std::vector<int> PianoRollComponent::stampKeys (int key, std::int64_t tick) const
  1203. {
  1204. std::vector<int> out;
  1205. const auto add = [&out] (int k) {
  1206. if (k >= 0 && k <= 127 && std::find (out.begin(), out.end(), k) == out.end())
  1207. out.push_back (k);
  1208. };
  1209. if (isDegreeStamp())
  1210. {
  1211. int root = key;
  1212. const auto chord = keyregions::diatonicChord (scaleDegreesAt (tick), key, degreeSize, degreeInversion, root);
  1213. if (chord.empty())
  1214. add (key); // (no key here: a single note; the hint says so)
  1215. else
  1216. {
  1217. // the root leads the drag, then the other notes from the lowest up
  1218. const auto rootAt = std::find_if (chord.begin(), chord.end(), [] (int i) { return ((i % 12) + 12) % 12 == 0; });
  1219. add (root + (rootAt != chord.end() ? *rootAt : 0));
  1220. for (const auto i : chord)
  1221. add (root + i);
  1222. }
  1223. return out;
  1224. }
  1225. const auto snapped = snapKey (key);
  1226. for (const auto interval : chordIntervals())
  1227. if (snapped + interval <= 127 && snapped + interval >= 0)
  1228. add (snapKey (snapped + interval)); // with scale snap the chord follows the scale
  1229. return out;
  1230. }
  1231. void PianoRollComponent::addKeyMarker (std::int64_t tick, const keyregions::State& state)
  1232. {
  1233. engine.editSong ([tick, state] (Song& s) { keyregions::addKeyMarker (currentPattern (s), tick, state); });
  1234. repaint();
  1235. }
  1236. void PianoRollComponent::addKeyRegion (std::int64_t from, std::int64_t to, const keyregions::State& state)
  1237. {
  1238. engine.editSong ([from, to, state] (Song& s) { keyregions::addKeyRegion (currentPattern (s), from, to, state); });
  1239. repaint();
  1240. }
  1241. int PianoRollComponent::scaleIndex() const
  1242. {
  1243. const auto id = scaleBox.getSelectedId();
  1244. return id <= 1 || id == autoScaleId ? 0 : id / 100;
  1245. }
  1246. int PianoRollComponent::scaleRoot() const
  1247. {
  1248. const auto id = scaleBox.getSelectedId();
  1249. return id <= 1 || id == autoScaleId ? 0 : (id % 100) - 1;
  1250. }
  1251. bool PianoRollComponent::inScale (int key) const
  1252. {
  1253. if (isAutoScale()) // (round 190jv: the guessed key's scale; no guess, no key in it)
  1254. return scaledetect::inScale (autoKey, key);
  1255. return scaleIndex() > 0 && notetools::inScale (key, scaleRoot(), scaleIndex());
  1256. }
  1257. // FL's Automatic scale highlighting (round 190jv, core/ScaleDetect.h): FL guesses again after every edit and selection
  1258. // change; here the guess is made again when the song, the pattern, the channel or the selection changed since the last
  1259. // paint (no timer, nothing while idle)
  1260. void PianoRollComponent::updateAutoKey()
  1261. {
  1262. if (! isAutoScale())
  1263. return;
  1264. const auto stamp = engine.getSongStamp();
  1265. const auto& song = engine.getSong();
  1266. const auto channel = engine.getSelectedChannel();
  1267. if (autoKeyValid && stamp == autoKeyStamp && song.currentPattern == autoKeyPattern && channel == autoKeyChannel
  1268. && allChannels == autoKeyAllChannels && selection == autoKeySelection)
  1269. return;
  1270. autoKeyValid = true;
  1271. autoKeyStamp = stamp;
  1272. autoKeyPattern = song.currentPattern;
  1273. autoKeyChannel = channel;
  1274. autoKeyAllChannels = allChannels;
  1275. autoKeySelection = selection;
  1276. autoKey = scaledetect::detect (currentPattern (song).notes, [this] (const Note& n) { return edits (n); },
  1277. [this] (int i) { return isSelected (i); });
  1278. }
  1279. int PianoRollComponent::snapKey (int key) const
  1280. {
  1281. return scalesnap::drawKey (snapScale(), key);
  1282. }
  1283. scalesnap::Scale PianoRollComponent::snapScale() const
  1284. {
  1285. return { scaleRoot(), scaleIndex(), scaleSnap };
  1286. }
  1287. void PianoRollComponent::setScaleSnap (bool on)
  1288. {
  1289. scaleSnap = on;
  1290. scaleSnapButton.setToggleState (on, juce::dontSendNotification);
  1291. publishScale();
  1292. repaint();
  1293. }
  1294. // Issue #203 (round 190ll): the docked root / scale boxes show the scale box's choice (a root chosen while no scale is
  1295. // stays in the root box and goes with the scale picked next)
  1296. void PianoRollComponent::refreshScaleBoxes()
  1297. {
  1298. const auto scale = scaleIndex();
  1299. if (scale > 0)
  1300. splitRoot = scaleRoot();
  1301. scaleRootBox.setSelectedId (splitRoot + 1, juce::dontSendNotification);
  1302. scaleNameBox.setSelectedId (isAutoScale() ? autoScaleId : scale > 0 ? scale * 100 : 1, juce::dontSendNotification);
  1303. scaleRootBox.setEnabled (! isAutoScale()); // (Automatic guesses the root too)
  1304. }
  1305. void PianoRollComponent::publishScale()
  1306. {
  1307. engine.setInputScale (scaleSnap ? scaleIndex() : 0, scaleRoot());
  1308. }
  1309. bool PianoRollComponent::isSelected (int index) const
  1310. {
  1311. return std::binary_search (selection.begin(), selection.end(), index);
  1312. }
  1313. std::vector<int> PianoRollComponent::channelNotes() const
  1314. {
  1315. const auto& notes = currentPattern (engine.getSong()).notes;
  1316. std::vector<int> out;
  1317. for (int i = 0; i < (int) notes.size(); ++i)
  1318. if (edits (notes[(std::size_t) i]) && rows.shown (notes[(std::size_t) i].key)) // (folded-away notes are left alone)
  1319. out.push_back (i);
  1320. return out;
  1321. }
  1322. std::vector<int> PianoRollComponent::selectionOrAll() const
  1323. {
  1324. return selection.empty() ? channelNotes() : selection;
  1325. }
  1326. void PianoRollComponent::setSelection (std::vector<int> indices)
  1327. {
  1328. std::sort (indices.begin(), indices.end());
  1329. indices.erase (std::unique (indices.begin(), indices.end()), indices.end());
  1330. selection = std::move (indices);
  1331. repaint();
  1332. }
  1333. void PianoRollComponent::selectAll()
  1334. {
  1335. setSelection (channelNotes());
  1336. }
  1337. bool PianoRollComponent::refuseFrozenEdit()
  1338. {
  1339. const auto& song = engine.getSong();
  1340. const auto channel = engine.getSelectedChannel();
  1341. if (channel < 0 || channel >= (int) song.channels.size() || ! song.channels[(std::size_t) channel].freeze.on())
  1342. return false;
  1343. 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()) }), {} },
  1344. 3000);
  1345. return true;
  1346. }
  1347. void PianoRollComponent::editNotes (const std::function<void (Pattern&)>& edit, bool undoable)
  1348. {
  1349. if (refuseFrozenEdit())
  1350. return;
  1351. engine.editSong ([&edit] (Song& s) { edit (currentPattern (s)); }, undoable);
  1352. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  1353. }
  1354. void PianoRollComponent::sortNotes()
  1355. {
  1356. auto tracked = selection;
  1357. tracked.push_back (dragNote);
  1358. // only reorders: no undo step of its own needed
  1359. engine.editSong ([&tracked] (Song& s) { noteedit::sortTracking (currentPattern (s), tracked); }, false);
  1360. dragNote = tracked.back();
  1361. tracked.pop_back();
  1362. setSelection (tracked);
  1363. }
  1364. juce::Rectangle<float> PianoRollComponent::stretchHandle() const
  1365. {
  1366. // a tab on the right end of the selection, vertically centred on it (clamped into the grid)
  1367. const auto& notes = currentPattern (engine.getSong()).notes;
  1368. std::int64_t start = 0, end = 0;
  1369. int top = -1, bottom = 128;
  1370. bool any = false;
  1371. for (auto i : selection)
  1372. {
  1373. if (i < 0 || i >= (int) notes.size() || ! edits (notes[(std::size_t) i]))
  1374. continue;
  1375. const auto& n = notes[(std::size_t) i];
  1376. start = any ? juce::jmin (start, n.start) : n.start;
  1377. end = any ? juce::jmax (end, n.start + n.length) : n.start + n.length;
  1378. top = juce::jmax (top, n.key);
  1379. bottom = juce::jmin (bottom, n.key);
  1380. any = true;
  1381. }
  1382. if (! any || end <= start)
  1383. return {};
  1384. const auto grid = gridArea().toFloat();
  1385. const auto x = (float) tickToX ((double) end);
  1386. const auto y0 = (float) keyToY (top), y1 = (float) (keyToY (bottom) + rowHeight);
  1387. const auto cy = juce::jlimit (grid.getY() + 10.0f, juce::jmax (grid.getY() + 10.0f, grid.getBottom() - 10.0f), (y0 + y1) * 0.5f);
  1388. const auto r = juce::Rectangle<float> (x + 2.0f, cy - 9.0f, 9.0f, 18.0f);
  1389. return grid.intersects (r) ? r : juce::Rectangle<float>();
  1390. }
  1391. void PianoRollComponent::drumPaintAt (juce::Point<int> p, bool snapOn)
  1392. {
  1393. // one short hit per grid cell and key, on whatever key is under the mouse (FL's drum painting)
  1394. const auto cell = juce::jmax<std::int64_t> (1, snapOn ? gridTicks() : ticksPerStep);
  1395. const auto start = juce::jmax<std::int64_t> (0, snapOn ? snap (xToTick (p.x), true) : noteedit::snapDown (xToTick (p.x), cell));
  1396. const auto key = snapKey (yToKey (p.y));
  1397. if (start == lastDrumCell && key == lastDrumKey)
  1398. return;
  1399. lastDrumCell = start;
  1400. lastDrumKey = key;
  1401. const auto channel = engine.getSelectedChannel();
  1402. if (polish::hasNoteInCell (currentPattern (engine.getSong()), channel, key, start, cell))
  1403. return;
  1404. Note n;
  1405. noteTemplate.applyTo (n);
  1406. n.start = start;
  1407. n.length = cell;
  1408. n.key = key;
  1409. n.channel = channel;
  1410. n.colour = noteColour;
  1411. editNotes ([&n] (Pattern& pat) { noteedit::paste (pat, { n }, 0); });
  1412. if (key != previewKey)
  1413. previewEdit (key, n.velocity);
  1414. }
  1415. // --- painting ------------------------------------------------------------------
  1416. void PianoRollComponent::paintOverview (juce::Graphics& g, juce::Rectangle<float> area, double total)
  1417. {
  1418. // the channel's notes across the whole view length, pitch mapped onto the strip's height; the part past
  1419. // the pattern's end is darker; bar lines every bar (every 4 when they get dense)
  1420. using namespace theme::colour;
  1421. const auto& song = engine.getSong();
  1422. const auto& pattern = currentPattern (song);
  1423. const auto channel = engine.getSelectedChannel();
  1424. const auto scale = area.getWidth() / juce::jmax (1.0, total);
  1425. const auto bar = (double) song.barTicks();
  1426. const auto end = (float) (pattern.effectiveLength (song.meter()) * scale);
  1427. g.setColour (bg2);
  1428. g.fillRect (area.withWidth (juce::jmin (area.getWidth(), end)));
  1429. const auto every = bar * scale < 6.0 ? 4 : 1;
  1430. g.setColour (gridBar.withAlpha (0.6f));
  1431. for (int b = every; b * bar < total; b += every)
  1432. g.fillRect ((float) (area.getX() + b * bar * scale), area.getY(), 1.0f, area.getHeight());
  1433. int low = 128, high = -1;
  1434. for (const auto& n : pattern.notes)
  1435. if (edits (n))
  1436. {
  1437. low = juce::jmin (low, n.key);
  1438. high = juce::jmax (high, n.key);
  1439. }
  1440. if (high < 0)
  1441. return;
  1442. const auto span = (float) juce::jmax (12, high - low + 1);
  1443. const auto mid = (low + high) / 2.0f;
  1444. const auto inner = area.reduced (0.0f, 2.0f);
  1445. auto colour = accent;
  1446. if (channel < (int) song.channels.size() && song.channels[(std::size_t) channel].colour != 0)
  1447. colour = theme::tame (juce::Colour (song.channels[(std::size_t) channel].colour));
  1448. colour = colour.interpolatedWith (textPrimary, 0.35f); // reads on the dark strip at any channel colour
  1449. for (const auto& n : pattern.notes)
  1450. {
  1451. if (! edits (n))
  1452. continue;
  1453. const auto y = inner.getCentreY() - ((float) n.key - mid) / span * inner.getHeight();
  1454. const auto x = area.getX() + (float) (n.start * scale);
  1455. g.setColour (n.muted ? colour.withAlpha (0.35f) : colour);
  1456. g.fillRect (x, juce::jlimit (inner.getY(), inner.getBottom() - 2.0f, y - 1.0f),
  1457. juce::jmax (1.0f, (float) (n.length * scale) - 0.5f), 2.0f);
  1458. }
  1459. }
  1460. bool PianoRollComponent::liveNotes() const { return fitKeysToNotes && ! liveNoteColour.isTransparent() && theme::livelook::active(); }
  1461. void PianoRollComponent::paint (juce::Graphics& g)
  1462. {
  1463. const uitrace::Scope trace ("PianoRollComponent paint", true, g.getClipBounds());
  1464. const auto& song = engine.getSong();
  1465. const auto& pattern = currentPattern (song);
  1466. const auto channel = engine.getSelectedChannel();
  1467. const auto grid = gridArea();
  1468. const auto patternLength = pattern.effectiveLength (song.meter());
  1469. const auto bar = song.barTicks();
  1470. const auto snapGrid = gridTicks();
  1471. updateAutoKey(); // (round 190jv: View › Scale highlighting › Automatic)
  1472. // the overview follows the notes (edits, undo, another channel or pattern) and the view
  1473. {
  1474. // (round 190gp: hashed again only when the song, the pattern or the channel changed since the last paint;
  1475. // LYNX_PAINT_SAVINGS=0 hashes on every paint, as before)
  1476. const auto stamp = engine.getSongStamp();
  1477. if (! ui::paintSavings() || stamp != overviewStamp || song.currentPattern != overviewPattern || channel != overviewChannel)
  1478. {
  1479. overviewStamp = stamp;
  1480. overviewPattern = song.currentPattern;
  1481. overviewChannel = channel;
  1482. auto signature = (std::size_t) song.currentPattern * 1000003u + (std::size_t) channel * 7919u + pattern.notes.size();
  1483. for (const auto& n : pattern.notes)
  1484. signature = signature * 31u + (std::size_t) (n.start * 131 + n.length * 7 + n.key + n.channel * 257 + (n.muted ? 1 : 0));
  1485. if (signature != overviewSignature)
  1486. {
  1487. overviewSignature = signature;
  1488. overview.repaint();
  1489. }
  1490. }
  1491. overview.setRange ((double) viewLengthTicks(), scrollTicks, grid.getWidth() / pixelsPerTick);
  1492. }
  1493. using namespace theme::colour;
  1494. g.fillAll (bg1);
  1495. g.setColour (bg3);
  1496. g.fillRect (0, 0, getWidth(), toolbarHeight);
  1497. g.setColour (border);
  1498. g.fillRect (0, toolbarHeight - 1, getWidth(), 1);
  1499. // 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
  1500. // users ask for a readable grid), derived from the theme's tokens so a theme still applies; the Playlist keeps its own
  1501. const auto lift = [] (juce::Colour c, float amount) { return c.interpolatedWith (textPrimary, amount); };
  1502. const auto prBar = lift (gridBar, 0.06f), prBeat = lift (gridBeat, 0.05f), prStep = lift (gridStep, 0.035f);
  1503. const auto prRowBlack = rowBlack.interpolatedWith (juce::Colours::black, 0.1f);
  1504. // 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
  1505. // (key regions, a chosen scale, Automatic) is the white-key row lifted above the 1 px row line, as FL's in-scale rows
  1506. // 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
  1507. // 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
  1508. const auto prRowIn = rowWhite.interpolatedWith (textPrimary, 0.07f);
  1509. // issue #205 (round 190lw): a selected note's row band (FL 2026 capture: BANDNOTE)
  1510. const auto rowBand = [] (juce::Colour row, bool live) { return row.interpolatedWith (textPrimary, live ? 0.10f : 0.10f); };
  1511. auto drawVerticalGrid = [&] (juce::Rectangle<int> area) {
  1512. // grid lines: bar > beat > snap (unless too dense)
  1513. const auto step = snapGrid * pixelsPerTick >= 6.0 ? snapGrid : (std::int64_t) ppq;
  1514. const auto first = (std::int64_t) std::floor (scrollTicks / (double) step);
  1515. const auto last = (std::int64_t) std::ceil (xToTick (area.getRight()) / (double) step);
  1516. for (auto i = first; i <= last; ++i)
  1517. {
  1518. const auto tick = i * step;
  1519. const auto x = (float) tickToX ((double) tick);
  1520. g.setColour (tick % bar == 0 ? prBar : tick % ppq == 0 ? prBeat : prStep);
  1521. g.drawVerticalLine ((int) x, (float) area.getY(), (float) area.getBottom());
  1522. }
  1523. };
  1524. // round 190ge: what this paint may change. A moving playhead repaints a 14-pixel column many times a second, and
  1525. // every note drawn outside it (a rounded rectangle is a path to build and fill) was work for no pixel: the notes,
  1526. // ghosts and velocity markers whose drawing lies wholly outside are skipped (the pixels stay the same)
  1527. const auto dirtyArea = g.getClipBounds();
  1528. const auto cull = ui::paintSavings(); // (LYNX_PAINT_SAVINGS=0: everything drawn, as before)
  1529. const auto outside = [&dirtyArea, cull] (const juce::Rectangle<float>& r, float margin) {
  1530. return cull && ! r.expanded (margin).getSmallestIntegerContainer().intersects (dirtyArea);
  1531. };
  1532. const auto liveLookNotes = liveNotes(); // (round 190jn: docked in the Clip View's Live look)
  1533. // --- grid ------------------------------------------------------------
  1534. {
  1535. juce::Graphics::ScopedSaveState state (g);
  1536. g.reduceClipRegion (grid);
  1537. const auto autoRows = isAutoScale();
  1538. const auto chosenScale = scaleIndex() > 0; // (round 190kd: read once per paint, not per row)
  1539. // issue #205 (round 190lw): FL's row bands — the rows of the selected notes lit across the whole grid, and while a
  1540. // note is pressed or dragged, the rows of the notes that follow the mouse (the hover band no longer goes away)
  1541. const auto noteDrag = drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft;
  1542. auto bandRows = rowbands::of (pattern.notes, selection);
  1543. if (noteDrag)
  1544. bandRows |= rowbands::of (pattern.notes, dragIndices);
  1545. // round 190nu (core/KeyRegions.h): FL's key markers shade each region's rows for its own key (before the first one,
  1546. // and after a Default one, the editor's own scale as before); only the regions in view, none without key markers
  1547. struct RegionRows
  1548. {
  1549. int x0, x1;
  1550. keyregions::State state;
  1551. keyregions::Degrees degrees;
  1552. };
  1553. std::vector<RegionRows> regionRows;
  1554. // round 190pf (P13): the Chord lane's chord at the song position lights its notes' rows (the scale's shade, the
  1555. // rows out of the chord the black-key shade); it wins over the scale and the key regions while it shows
  1556. const auto chordRows = gridHighlights && ! liveLookNotes && shownChord.root >= 0;
  1557. if (gridHighlights && ! liveLookNotes && ! chordRows && keyregions::hasKeyMarkers (pattern))
  1558. {
  1559. const auto rightTick = (std::int64_t) xToTick (grid.getRight()) + 1;
  1560. for (const auto& span : keyregions::spans (pattern, std::max<std::int64_t> (rightTick, 1)))
  1561. {
  1562. auto x0 = (int) std::floor (tickToX ((double) span.from)), x1 = (int) std::ceil (tickToX ((double) span.to));
  1563. x0 = std::max (x0, grid.getX());
  1564. x1 = std::min (x1, grid.getRight());
  1565. if (x1 > x0)
  1566. regionRows.push_back ({ x0, x1, span.state, span.state.kind == keyregions::State::key ? keyregions::degreesOf (span.state.value) : keyregions::Degrees {} });
  1567. }
  1568. if (! regionRows.empty()) // (the last region goes on past the right edge)
  1569. regionRows.back().x1 = grid.getRight();
  1570. }
  1571. for (int key = 0; key < 128; ++key)
  1572. {
  1573. const auto y = keyToY (key);
  1574. if (! rows.shown (key) || y > grid.getBottom() || y + rowHeight < grid.getY())
  1575. continue;
  1576. // Note grid highlights (Alt+B, round 168g): off, every row looks the same (FL's "BlackKeys" option)
  1577. auto row = gridHighlights && blackKeyRows && isBlackKey (key) ? prRowBlack : rowWhite; // (FL's Default: none, #212)
  1578. if (gridHighlights && autoRows) // FL's Automatic (round 190jv): the rows out of the guessed key dark; no guess, none
  1579. row = autoKey < 0 ? rowWhite : scaledetect::inScale (autoKey, key) ? prRowIn : prRowBlack;
  1580. else if (gridHighlights && chosenScale)
  1581. // a chosen scale as FL shades it (round 190kd, owner's decision; FL 2026 shot: the rows out of the scale
  1582. // take the black-key shade, the rows in it the white-key one, black keys or not; rollup step 6: 190jo's
  1583. // black-key shade `prRowBlack`, as step 5 did for Automatic)
  1584. row = inScale (key) ? prRowIn : prRowBlack;
  1585. if (chordRows)
  1586. row = (shownChord.mask & (1 << (key % 12))) != 0 ? prRowIn : prRowBlack;
  1587. if (liveLookNotes) // (round 190jn: Live's note editor, one grey with a darker line under each row)
  1588. row = juce::Colour (0xff464f53);
  1589. if (bandRows.test ((std::size_t) key))
  1590. row = rowBand (row, liveLookNotes);
  1591. else if (key == hover.key && drag == Drag::none)
  1592. row = row.interpolatedWith (textPrimary, 0.04f); // the row under the mouse
  1593. if (regionRows.empty())
  1594. {
  1595. g.setColour (row);
  1596. g.fillRect (grid.getX(), y, grid.getWidth(), rowHeight);
  1597. }
  1598. else
  1599. for (const auto& r : regionRows)
  1600. {
  1601. auto shade = row; // (the editor's own scale)
  1602. if (r.state.kind != keyregions::State::editor)
  1603. {
  1604. shade = r.state.kind == keyregions::State::key ? (r.degrees.contains (key) ? prRowIn : prRowBlack)
  1605. : (blackKeyRows && isBlackKey (key) ? prRowBlack : rowWhite);
  1606. if (bandRows.test ((std::size_t) key))
  1607. shade = rowBand (shade, false);
  1608. else if (key == hover.key && drag == Drag::none)
  1609. shade = shade.interpolatedWith (textPrimary, 0.04f);
  1610. }
  1611. g.setColour (shade);
  1612. g.fillRect (r.x0, y, r.x1 - r.x0, rowHeight);
  1613. }
  1614. // (round 190jn: Live's darker line under each row; round 190jo FM-15: FL's 1 px line under every row, the note
  1615. // sits above it)
  1616. if (liveLookNotes || rowHeight >= 10)
  1617. {
  1618. g.setColour (liveLookNotes ? juce::Colour (0xff3d4548) : prStep);
  1619. g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
  1620. }
  1621. if (! padRows.empty() || key % 12 == (folded() ? scaleRoot() : 0)) // folded: the octave line under each root (pads: each row)
  1622. {
  1623. g.setColour (prBeat);
  1624. g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
  1625. }
  1626. }
  1627. drawVerticalGrid (grid);
  1628. paintBackgroundWave (g, grid);
  1629. // the time selection (Ctrl+drag on the ruler): Insert / Delete space, Trim
  1630. if (timeFrom >= 0 && timeTo > timeFrom)
  1631. {
  1632. g.setColour (selectionFill.withMultipliedAlpha (0.45f));
  1633. g.fillRect (juce::Rectangle<float> ((float) tickToX ((double) timeFrom), (float) grid.getY(),
  1634. (float) ((double) (timeTo - timeFrom) * pixelsPerTick), (float) grid.getHeight()));
  1635. }
  1636. // outside the pattern is darkened
  1637. const auto endX = (float) tickToX ((double) patternLength);
  1638. g.setColour (bg0.withAlpha (0.55f));
  1639. g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
  1640. // ghost notes (Alt+V). This channel's notes in the other clips that play at the same time in the
  1641. // Playlist: hollow outlines. The other channels of this pattern: solid grey (a bit brighter, with
  1642. // their channel colour on the edge, when Ctrl+Alt+V makes them editable)
  1643. if (showGhosts)
  1644. {
  1645. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, channel))
  1646. {
  1647. if (! rows.shown (n.key))
  1648. continue;
  1649. const auto r = noteRect (n.start, n.length, n.key);
  1650. if (r.getRight() < (float) grid.getX() || r.getX() > (float) grid.getRight() || outside (r, 2.0f))
  1651. continue;
  1652. g.setColour (textPrimary.withAlpha (0.30f));
  1653. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1654. }
  1655. }
  1656. for (const auto& n : pattern.notes)
  1657. {
  1658. if (edits (n) || ! showGhosts || ! ghostShown (n.channel) || ! rows.shown (n.key))
  1659. continue;
  1660. const auto r = noteRect (n.start, n.length, n.key);
  1661. if (outside (r, 2.0f))
  1662. continue;
  1663. const auto hovered = &n - pattern.notes.data() == hover.ghost;
  1664. // (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
  1665. // light text at 14 % with a 22 % edge reads the same on LYNX's dark rows)
  1666. g.setColour (textPrimary.withAlpha (hovered ? 0.20f : editGhosts ? 0.17f : 0.14f));
  1667. g.fillRoundedRectangle (r, 2.0f);
  1668. g.setColour (textPrimary.withAlpha (hovered ? 0.40f : editGhosts ? 0.30f : 0.22f));
  1669. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1670. if (editGhosts && n.channel >= 0 && n.channel < (int) song.channels.size() && song.channels[(std::size_t) n.channel].colour != 0)
  1671. {
  1672. g.setColour (theme::tame (juce::Colour (song.channels[(std::size_t) n.channel].colour)).withAlpha (0.7f));
  1673. g.fillRect (r.withWidth (2.0f).reduced (0.0f, 1.0f));
  1674. }
  1675. }
  1676. for (int i = 0; i < (int) pattern.notes.size(); ++i)
  1677. {
  1678. const auto& n = pattern.notes[(std::size_t) i];
  1679. if (! edits (n) || ! rows.shown (n.key))
  1680. continue;
  1681. const auto r = noteRect (n.start, n.length, n.key);
  1682. if (outside (r, 2.0f)) // (its outline, grips, marks and label all lie inside r)
  1683. continue;
  1684. const auto selected = isSelected (i);
  1685. const auto hovered = i == hover.note && drag == Drag::none;
  1686. // a selected muted note keeps a muted look (round 167k: Alt+M on a selection showed no change)
  1687. auto fill = selected ? (n.muted ? accentHover.interpolatedWith (noteMuted, 0.6f) : accentHover.brighter (0.15f))
  1688. : n.muted ? noteMuted : theme::noteGroupColour (n.colour, n.velocity);
  1689. if (liveLookNotes && ! selected && ! n.muted) // Live: the clip's colour × 0.86 with a black edge, square
  1690. {
  1691. fill = theme::liveShade (liveNoteColour, 0.86f).withAlpha (1.0f);
  1692. if (hovered)
  1693. fill = fill.brighter (0.18f);
  1694. g.setColour (fill);
  1695. g.fillRect (r);
  1696. g.setColour (juce::Colours::black);
  1697. g.drawRect (r, 1.0f);
  1698. }
  1699. else
  1700. {
  1701. if (hovered)
  1702. fill = fill.brighter (0.18f);
  1703. paintNoteBody (g, r, fill, selected ? textPrimary : hovered ? textPrimary.withAlpha (0.75f) : juce::Colour());
  1704. }
  1705. // "All" channels: whose note it is, by the channel's colour on its left edge (issue #12)
  1706. if (allChannels && n.channel >= 0 && n.channel < (int) song.channels.size() && r.getWidth() > 5.0f)
  1707. {
  1708. const auto c = song.channels[(std::size_t) n.channel].colour;
  1709. g.setColour ((c != 0 ? theme::tame (juce::Colour (c)) : textPrimary.withAlpha (0.5f)).withAlpha (0.9f));
  1710. g.fillRect (r.withWidth (2.5f).reduced (0.0f, 1.5f).translated (1.0f, 0.0f));
  1711. }
  1712. // the edge under the mouse shows its grip
  1713. if (hovered && (hover.zone == gesture::Zone::rightEdge || hover.zone == gesture::Zone::leftEdge))
  1714. {
  1715. const auto gripX = hover.zone == gesture::Zone::rightEdge ? r.getRight() - 3.0f : r.getX() + 1.0f;
  1716. g.setColour (textPrimary);
  1717. g.fillRoundedRectangle (gripX, r.getY() + 2.0f, 2.0f, juce::jmax (2.0f, r.getHeight() - 4.0f), 1.0f);
  1718. }
  1719. if (n.group != 0 && r.getWidth() > 10.0f) // grouped: a small link mark at the top right
  1720. {
  1721. g.setColour (bg0.withAlpha (0.7f));
  1722. g.fillEllipse (r.getRight() - 6.0f, r.getY() + 1.5f, 3.5f, 3.5f);
  1723. }
  1724. // a Chance below 100 % (round 187c): a small triangle in the top-left corner, as Live 12 marks it ("A small
  1725. // triangle is displayed in the upper-left corner of notes with probability values less than 100%")
  1726. if ((n.chance < 1.0f || n.chanceGroup != 0) && r.getWidth() > 6.0f && r.getHeight() > 5.0f)
  1727. {
  1728. juce::Path corner;
  1729. const auto size = juce::jmin (6.0f, r.getHeight() - 2.0f);
  1730. 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);
  1731. g.setColour (bg0.withAlpha (0.75f));
  1732. g.fillPath (corner);
  1733. }
  1734. if (n.porta) // porta (round 190oa, DE-81, capture 190oa fl-pr-porta-mark: FL's "/" ~10 × 7 px near the note's right
  1735. { // end, 3 px in, centred, in the note's label colour)
  1736. const auto w = juce::jmin (10.0f, juce::jmax (3.0f, r.getWidth() - 6.0f)), h = juce::jmin (7.0f, r.getHeight() - 4.0f);
  1737. const auto x1 = r.getRight() - 3.0f, cy = r.getCentreY();
  1738. g.setColour (bg0.withAlpha (0.65f));
  1739. g.drawLine (x1 - w, cy + h * 0.5f, x1, cy - h * 0.5f, 2.0f);
  1740. }
  1741. if (n.slide) // slide mark: FL's manual (Piano roll): "slide notes have a small triangle on the right" (round 190kn, DE-80)
  1742. {
  1743. juce::Path arrow;
  1744. const auto w = juce::jmin (7.0f, juce::jmax (3.0f, r.getWidth() - 4.0f));
  1745. arrow.addTriangle (r.getRight() - 2.0f - w, r.getBottom() - 2.0f, r.getRight() - 2.0f - w, r.getY() + 2.0f, r.getRight() - 2.0f, r.getCentreY());
  1746. g.setColour (bg0.withAlpha (0.65f));
  1747. g.fillPath (arrow);
  1748. }
  1749. if (gesture::noteLabelFits (r.getWidth(), rowHeight)) // the note's name, readable on its colour
  1750. {
  1751. // (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
  1752. // 2.3:1; bold, 3 px in from the left as FL's)
  1753. g.setColour (noteLabelColour (fill));
  1754. g.setFont (noteLabelFont (rowHeight));
  1755. 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);
  1756. }
  1757. }
  1758. // round 177d: the notes being played into a take grow with the playhead until they are released (then the
  1759. // recorded note takes their place); FL 2026 draws them so, as ordinary notes (REA_rodada177d §1.3, g03)
  1760. if (engine.isLiveRecording())
  1761. for (const auto& n : engine.liveRecording().held)
  1762. {
  1763. if (! edits (n) || ! rows.shown (n.key))
  1764. continue;
  1765. const auto r = noteRect (n.start, n.length, n.key);
  1766. const auto fill = theme::noteGroupColour (n.colour, n.velocity);
  1767. paintNoteBody (g, r, fill, {});
  1768. if (gesture::noteLabelFits (r.getWidth(), rowHeight))
  1769. {
  1770. g.setColour (noteLabelColour (fill));
  1771. g.setFont (noteLabelFont (rowHeight));
  1772. textcache::drawText (g, keyName (n.key), r.reduced (3.0f, 0.0f), juce::Justification::centredLeft, true);
  1773. }
  1774. }
  1775. // the selection's stretch handle: a tab at its right end with two grips
  1776. if (const auto handle = stretchHandle(); ! handle.isEmpty() && (drag == Drag::none || drag == Drag::stretch))
  1777. {
  1778. const auto lit = hover.stretch || drag == Drag::stretch;
  1779. g.setColour (lit ? accentHover : accent.withAlpha (0.85f));
  1780. g.fillRoundedRectangle (handle, 3.0f);
  1781. g.setColour (onAccent.withAlpha (0.9f));
  1782. g.fillRect (handle.getCentreX() - 2.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  1783. g.fillRect (handle.getCentreX() + 1.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  1784. if (lit) // the stretched span, from the anchor to the handle
  1785. {
  1786. g.setColour (accent.withAlpha (0.5f));
  1787. const auto x0 = (float) tickToX ((double) (drag == Drag::stretch ? stretchAnchor : 0));
  1788. if (drag == Drag::stretch)
  1789. g.drawVerticalLine ((int) x0, (float) grid.getY(), (float) grid.getBottom());
  1790. g.drawVerticalLine ((int) handle.getX() - 2, (float) grid.getY(), (float) grid.getBottom());
  1791. }
  1792. }
  1793. if (! mpeLaneAreas().empty()) // (round 190hy: as Live's MPE view, each note's pitch curve over it)
  1794. paintMpePitchOnNotes (g, grid);
  1795. // round 190nu: the Scale degree chord a click would write, as outlines with its numeral and name (LYNX's look: the
  1796. // accent outline, a faint fill; only while the degree stamp is chosen and the mouse rests on the empty grid)
  1797. if (degreeGhost.tick >= 0 && ! degreeGhost.keys.empty())
  1798. {
  1799. const auto x = (float) tickToX ((double) degreeGhost.tick);
  1800. const auto w = juce::jmax (6.0f, (float) ((double) degreeGhost.length * pixelsPerTick) - 1.0f);
  1801. float top = (float) grid.getBottom(), bottom = (float) grid.getY();
  1802. for (const auto k : degreeGhost.keys)
  1803. if (rows.shown (k))
  1804. {
  1805. const auto r = juce::Rectangle<float> (x, (float) keyToY (k) + 1.0f, w, (float) rowHeight - 2.0f);
  1806. g.setColour (accent.withAlpha (0.16f));
  1807. g.fillRoundedRectangle (r, 2.0f);
  1808. g.setColour (accent.withAlpha (0.85f));
  1809. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  1810. top = juce::jmin (top, r.getY());
  1811. bottom = juce::jmax (bottom, r.getBottom());
  1812. }
  1813. if (top - 20.0f < (float) grid.getY()) // (no room above the chord: the label goes under it)
  1814. top = bottom + 20.0f;
  1815. if (degreeGhost.label.isNotEmpty())
  1816. {
  1817. g.setFont (theme::font (theme::type::caption, true));
  1818. const auto tw = juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), degreeGhost.label) + 10;
  1819. const auto tag = juce::Rectangle<float> (x, top - 18.0f, (float) tw, 16.0f);
  1820. g.setColour (bg4.withAlpha (0.94f));
  1821. g.fillRoundedRectangle (tag, 3.0f);
  1822. g.setColour (accent.withAlpha (0.8f));
  1823. g.drawRoundedRectangle (tag.reduced (0.5f), 3.0f, 1.0f);
  1824. g.setColour (textPrimary);
  1825. g.drawText (degreeGhost.label, tag.toNearestInt(), juce::Justification::centred, false);
  1826. }
  1827. }
  1828. if (! rubberBand.isEmpty())
  1829. {
  1830. g.setColour (selectionFill);
  1831. g.fillRect (rubberBand);
  1832. g.setColour (theme::colour::selection);
  1833. g.drawRect (rubberBand);
  1834. }
  1835. if (drag == Drag::knife)
  1836. {
  1837. juce::Path cut;
  1838. cut.startNewSubPath (knifeFrom.toFloat());
  1839. cut.lineTo (knifeTo.toFloat());
  1840. juce::Path dashed;
  1841. const float dash[] = { 5.0f, 3.0f };
  1842. juce::PathStrokeType (1.5f).createDashedStroke (dashed, cut, dash, 2);
  1843. g.setColour (textPrimary);
  1844. g.fillPath (dashed);
  1845. }
  1846. if (playheadTick >= 0.0 && ! gpuPlayhead.isShowing()) // (round 190ip: the GPU moves it while playing)
  1847. {
  1848. g.setColour (playhead);
  1849. g.drawVerticalLine ((int) tickToX (playheadTick), (float) grid.getY(), (float) grid.getBottom());
  1850. }
  1851. }
  1852. // --- velocity lane -----------------------------------------------------
  1853. // (round 190on, P10: once for each stacked lane, top to bottom, then the bottom lane; with none, once as before)
  1854. for (int laneIndex = 0; laneIndex <= (int) stacked.size(); ++laneIndex)
  1855. {
  1856. const LaneScope laneScope (*this, laneIndex < (int) stacked.size() ? laneIndex : -1);
  1857. {
  1858. const auto lane = velocityArea();
  1859. g.setColour (rowWhite); // (round 190jo FM-19: FL's lane is the roll's field with its beat lines, not a darker well)
  1860. g.fillRect (lane);
  1861. juce::Graphics::ScopedSaveState state (g);
  1862. g.reduceClipRegion (lane);
  1863. drawVerticalGrid (lane);
  1864. g.setColour (border);
  1865. g.drawHorizontalLine (lane.getY(), (float) lane.getX(), (float) lane.getRight());
  1866. const auto usable = (float) lane.getHeight() - 8.0f;
  1867. const auto bipolar = laneIsBipolar();
  1868. const auto base = bipolar ? (float) lane.getBottom() - 2.0f - usable * 0.5f : (float) lane.getBottom();
  1869. if (bipolar)
  1870. {
  1871. g.setColour (textPrimary.withAlpha (0.15f));
  1872. g.drawHorizontalLine ((int) base, (float) lane.getX(), (float) lane.getRight());
  1873. }
  1874. if (const auto target = eventLaneTarget()) // pattern events: held values, a dot on each event
  1875. {
  1876. const auto* events = eventedit::findLane (pattern, *target);
  1877. if (events != nullptr && ! events->events.empty())
  1878. {
  1879. juce::Path held;
  1880. const auto yOf = [&] (float v) { return (float) lane.getBottom() - 2.0f - usable * v; };
  1881. auto x = (float) tickToX (0.0);
  1882. auto y = yOf (events->events.front().value);
  1883. held.startNewSubPath (x, y);
  1884. for (const auto& ev : events->events)
  1885. {
  1886. const auto ex = (float) tickToX ((double) ev.tick);
  1887. held.lineTo (ex, y);
  1888. y = yOf (ev.value);
  1889. held.lineTo (ex, y);
  1890. }
  1891. held.lineTo ((float) lane.getRight(), y);
  1892. g.setColour (accent.withAlpha (0.85f));
  1893. g.strokePath (held, juce::PathStrokeType (1.5f));
  1894. for (const auto& ev : events->events)
  1895. g.fillEllipse ((float) tickToX ((double) ev.tick) - 2.5f, yOf (ev.value) - 2.5f, 5.0f, 5.0f);
  1896. }
  1897. else
  1898. {
  1899. g.setColour (textDisabled);
  1900. g.setFont (theme::font (theme::type::small));
  1901. textcache::drawText (g, tr ("No events yet: draw them here"), lane.reduced (8, 4), juce::Justification::centredLeft, true);
  1902. }
  1903. }
  1904. const auto mpeLanes = mpeLaneAreas(); // (round 190hy: the notes' MPE curves instead of their stems)
  1905. if (! mpeLanes.empty())
  1906. {
  1907. const auto range = drag == Drag::mpePoint || drag == Drag::mpeDraw ? mpeDragRange : mpePitchRange();
  1908. for (const auto& [area, id] : mpeLanes)
  1909. if (isMpeLane (id))
  1910. paintMpeLane (g, area, id, range);
  1911. else
  1912. paintMpeValueLane (g, area, id); // (round 190jd: the MPE tab's Velocity / Release Velocity lanes)
  1913. }
  1914. else
  1915. {
  1916. // the lane's name in it, as FL writes it next to "Control" (round 149: the box on the left is narrow)
  1917. g.setColour (theme::colour::textSecondary.withAlpha (0.8f));
  1918. g.setFont (theme::font (theme::type::caption, true));
  1919. textcache::drawText (g, laneName(), lane.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  1920. }
  1921. // round 190mf (DL-80, capture 190mf B2): in the Clip View's Live look the hovered note's velocity marker and its
  1922. // stem turn Live's blue (91,140,255); while a velocity is dragged the selected markers are Live's light cyan
  1923. // (176,221,235), and the lane header shows the value at the marker's height (paint's lane label below)
  1924. const auto liveVelocity = liveNotes() && laneId() == laneVelocity;
  1925. liveVelocityReadout = {};
  1926. for (int i = 0; i < (int) pattern.notes.size() && ! eventLaneTarget() && mpeLanes.empty(); ++i)
  1927. {
  1928. const auto& n = pattern.notes[(std::size_t) i];
  1929. if (! edits (n) || ! rows.shown (n.key))
  1930. continue;
  1931. const auto x = (float) tickToX ((double) n.start);
  1932. // (round 190ge: outside the repainted area — the marker's ±6 pixels, the Velocity Range box over the note's
  1933. // length — nothing to draw; a probability group's line reaches another note, so those are always drawn)
  1934. if (! (laneIsChance() && n.chanceGroup != 0)
  1935. && 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))
  1936. continue;
  1937. const auto top = (float) lane.getBottom() - 2.0f - usable * laneValue (n);
  1938. auto colour = isSelected (i) ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  1939. if (n.muted)
  1940. colour = noteMuted;
  1941. const auto hovered = i == hover.note && drag == Drag::none;
  1942. if (liveVelocity && hovered)
  1943. colour = juce::Colour (91, 140, 255);
  1944. else if (liveVelocity && drag == Drag::velocity && isSelected (i))
  1945. colour = juce::Colour (176, 221, 235);
  1946. if (liveVelocity && ((hovered && lane.contains (lastMouse)) || (drag == Drag::velocity && isSelected (i) && liveVelocityReadout.note < 0)))
  1947. liveVelocityReadout = { i, top, juce::roundToInt (n.velocity * 127.0f) };
  1948. // the velocity lane shows a note's Velocity Range (round 187c) as a shaded box over the note's length, from
  1949. // its velocity to where the range reaches, as Live 12 draws it [LIVE 12.4 shot, live-02]
  1950. if (laneId() == laneVelocity && n.velocityRange != 0.0f)
  1951. {
  1952. const auto reach = juce::jlimit (1.0f / 127.0f, 1.0f, n.velocity + n.velocityRange);
  1953. const auto y2 = (float) lane.getBottom() - 2.0f - usable * reach;
  1954. const auto w = juce::jmax (3.0f, (float) (n.length * pixelsPerTick) - 1.0f);
  1955. g.setColour (colour.withAlpha (0.22f));
  1956. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, y2), w, std::abs (y2 - top)));
  1957. g.setColour (colour.withAlpha (0.5f));
  1958. g.drawHorizontalLine ((int) y2, x, x + w);
  1959. }
  1960. // a probability group (round 187c): its members' Chance markers joined by a line (the group has one Chance)
  1961. if (laneIsChance() && n.chanceGroup != 0)
  1962. for (int j = i + 1; j < (int) pattern.notes.size(); ++j)
  1963. if (const auto& m = pattern.notes[(std::size_t) j]; m.chanceGroup == n.chanceGroup && edits (m) && rows.shown (m.key))
  1964. {
  1965. g.setColour (colour.withAlpha (0.5f));
  1966. const auto dash = std::array<float, 2> { 3.0f, 3.0f };
  1967. g.drawDashedLine (juce::Line<float> (x, top, (float) tickToX ((double) m.start), top), dash.data(), 2, n.chanceOne ? 1.0f : 2.0f);
  1968. break;
  1969. }
  1970. g.setColour (hovered ? colour.brighter (0.3f) : colour.withAlpha (0.8f));
  1971. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, base), hovered ? 3.0f : 2.0f, std::abs (base - top)));
  1972. // round 190oj: FL's event mark in the Pattern layout — a line along the note's length at its value and a ring
  1973. // head (two fills: cheaper than a stroked ellipse); Live's look keeps its filled dot
  1974. if (! liveVelocity)
  1975. g.fillRect (juce::Rectangle<float> (x, std::round (top), juce::jmax (0.0f, (float) (n.length * pixelsPerTick) - 1.0f), 1.0f));
  1976. g.fillEllipse (x - 3.0f, top - 3.0f, 7.0f, 7.0f);
  1977. if (! liveVelocity)
  1978. {
  1979. g.setColour (colour.withMultipliedBrightness (0.45f));
  1980. g.fillEllipse (x - 1.5f, top - 1.5f, 4.0f, 4.0f);
  1981. g.setColour (colour.brighter (0.3f)); // (the hover ring below)
  1982. }
  1983. if (hovered)
  1984. g.drawEllipse (x - 5.0f, top - 5.0f, 11.0f, 11.0f, 1.0f);
  1985. }
  1986. if (drag == Drag::velocityLine && paintingLane == heldLane) // the line being drawn (in the lane it is drawn in)
  1987. {
  1988. g.setColour (textPrimary.withAlpha (0.8f));
  1989. g.drawLine (juce::Line<int> (knifeFrom, knifeTo).toFloat(), 1.5f);
  1990. }
  1991. }
  1992. }
  1993. // --- time ruler --------------------------------------------------------
  1994. {
  1995. const auto ruler = juce::Rectangle<int> (keyboardWidth, rulerTop, grid.getWidth(), timelineHeight);
  1996. g.setColour (bg2);
  1997. g.fillRect (ruler);
  1998. g.setColour (border);
  1999. g.fillRect (ruler.withTop (ruler.getBottom() - 1));
  2000. juce::Graphics::ScopedSaveState state (g);
  2001. g.reduceClipRegion (ruler);
  2002. g.setFont (theme::font (theme::type::caption));
  2003. const auto firstBar = (std::int64_t) std::floor (scrollTicks / (double) bar);
  2004. const auto lastBar = (std::int64_t) std::ceil (xToTick (grid.getRight()) / (double) bar);
  2005. if (timeFrom >= 0 && timeTo > timeFrom) // the time selection on the ruler
  2006. {
  2007. const auto x0 = (float) tickToX ((double) timeFrom), x1 = (float) tickToX ((double) timeTo);
  2008. g.setColour (accent.withAlpha (0.35f));
  2009. g.fillRect (juce::Rectangle<float> (x0, (float) rulerTop, x1 - x0, (float) timelineHeight - 1.0f));
  2010. g.setColour (accent);
  2011. g.fillRect (juce::Rectangle<float> (x0, (float) rulerTop, x1 - x0, 2.0f));
  2012. }
  2013. // View › "Ruler: song bars" (round 177d, LYNX's own; off = FL's pattern bars): the bar numbers the Playlist shows
  2014. // where the pattern's first clip plays
  2015. const auto songOrigin = songBarsRuler ? polish::patternSongOrigin (song, song.currentPattern) : std::nullopt;
  2016. for (auto b = firstBar; b <= lastBar; ++b)
  2017. {
  2018. const auto x = (int) tickToX ((double) (b * bar));
  2019. g.setColour (textSecondary);
  2020. g.drawVerticalLine (x, (float) rulerTop + 10.0f, (float) headerHeight);
  2021. const std::int64_t number = songOrigin.has_value() ? polish::songBarNumber (*songOrigin, b, bar) : (std::int64_t) b + 1;
  2022. 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)
  2023. textcache::drawText (g, juce::String (number), x + 3, rulerTop, 40, 11, juce::Justification::centredLeft);
  2024. }
  2025. // the pattern's time markers (round 168g): a flag and the name in the ruler's lower half, like the Playlist's
  2026. for (const auto& m : currentPattern (song).markers)
  2027. {
  2028. const auto x = (float) tickToX ((double) m.tick);
  2029. if (x < (float) keyboardWidth - 120.0f || x > (float) ruler.getRight())
  2030. continue;
  2031. const auto colour = m.isSignature() ? textPrimary : accent;
  2032. g.setColour (colour);
  2033. g.fillRect (juce::Rectangle<float> (x, (float) rulerTop + 11.0f, 1.5f, (float) timelineHeight - 11.0f));
  2034. juce::Path flag;
  2035. flag.addTriangle (x, (float) rulerTop + 11.0f, x + 6.0f, (float) rulerTop + 14.0f, x, (float) rulerTop + 17.0f);
  2036. g.fillPath (flag);
  2037. auto label = juce::String::fromUTF8 (m.name.c_str());
  2038. if (label.isEmpty() && m.action != 0)
  2039. label = tr (markers::actionName (m.action));
  2040. auto textX = (int) x + 8;
  2041. if (keyregions::isKeyMarker (m)) // round 190nu: FL's key marker shows a note before its key ("♪ C Major (Ionian)")
  2042. {
  2043. const auto cy = (float) rulerTop + 10.0f + (float) (timelineHeight - 11) * 0.5f;
  2044. g.fillEllipse ((float) textX, cy + 1.0f, 4.5f, 3.5f);
  2045. g.fillRect ((float) textX + 3.5f, cy - 6.0f, 1.0f, 8.0f);
  2046. g.fillRect ((float) textX + 3.5f, cy - 6.0f, 3.0f, 1.0f);
  2047. textX += 9;
  2048. }
  2049. textcache::drawText (g, label, textX, rulerTop + 10, keyregions::isKeyMarker (m) ? 160 : 110, timelineHeight - 11, juce::Justification::centredLeft);
  2050. }
  2051. if (playheadTick >= 0.0 && ! gpuPlayhead.isShowing())
  2052. {
  2053. const auto x = (float) tickToX (playheadTick);
  2054. juce::Path tri;
  2055. tri.addTriangle (x - 5, (float) rulerTop, x + 5, (float) rulerTop, x, (float) rulerTop + 8);
  2056. g.setColour (playhead);
  2057. g.fillPath (tri);
  2058. }
  2059. }
  2060. // --- keyboard ------------------------------------------------------------
  2061. // flat keys; every C is labelled with its octave, the other white keys too when the rows are tall
  2062. // enough; the key under the mouse (and the one sounding) are lit
  2063. // (round 190ki, perf: all of it lies within `keys`; a playhead column elsewhere skips the 128 keys, their labels and
  2064. // the gradient)
  2065. if (const auto keys = juce::Rectangle<int> (0, headerHeight, keyboardWidth, grid.getHeight()); g.clipRegionIntersects (keys))
  2066. {
  2067. juce::Graphics::ScopedSaveState state (g);
  2068. g.reduceClipRegion (keys);
  2069. g.setColour (bg0);
  2070. g.fillRect (keys);
  2071. const auto fontHeight = gesture::labelHeight (rowHeight);
  2072. const auto blackWidth = blackKeyWidth;
  2073. // (round 190jo, perf: FL's white-key gradient is filled once over the column; the keys at rest draw nothing more)
  2074. if (! folded())
  2075. {
  2076. g.setGradientFill (juce::ColourGradient (keyWhite.withMultipliedBrightness (0.93f), 0.0f, 0.0f,
  2077. keyWhite.interpolatedWith (juce::Colours::white, 0.33f), (float) keyboardWidth, 0.0f, false));
  2078. g.fillRect (keys.withWidth (keyboardWidth - 1));
  2079. }
  2080. static const std::map<int, std::string> noLabels;
  2081. const auto selectedChannel = engine.getSelectedChannel();
  2082. const auto& ownLabels = selectedChannel >= 0 && selectedChannel < (int) song.channels.size()
  2083. ? song.channels[(std::size_t) selectedChannel].keyLabels : noLabels;
  2084. // a Drum Rack's pad names on its keys (round 190ec, Live's note editor); a key label of the user's wins
  2085. std::map<int, std::string> padLabels;
  2086. if (selectedChannel >= 0 && selectedChannel < (int) song.channels.size() && rack::isDrumRack (song.channels[(std::size_t) selectedChannel]))
  2087. {
  2088. padLabels = rack::padNames (*rack::rackOf (song.channels[(std::size_t) selectedChannel].patcher));
  2089. for (const auto& [key, label] : ownLabels)
  2090. padLabels[key] = label;
  2091. }
  2092. const auto& labels = padLabels.empty() ? ownLabels : padLabels;
  2093. // folded to the scale (round 166d) the keys no longer alternate like a piano: one full-width named row each
  2094. const auto list = folded();
  2095. const auto piano = pianokeys::whiteKeysMeet (keyStyle) && ! list;
  2096. const auto flKeys = keyStyle == pianokeys::Style::fl && ! list; // (round 190oo O-2: FL 2026's keyboard, the default)
  2097. // round 190jo (design190ia FM-17): FL's white keys shade from a light grey at the left to near-white at the right
  2098. // (the column's gradient above); its C keys are a step darker (FL: #B0B4BB against #D0D4DB-#E9EDF4)
  2099. const auto fillKey = [&] (int key, juce::Colour colour, juce::Rectangle<int> r) {
  2100. const auto isC = key % 12 == 0 && ! (isBlackKey (key) && ! list);
  2101. if (colour == keyWhite && ! list)
  2102. {
  2103. if (! isC)
  2104. return; // (the gradient is there)
  2105. g.setColour (juce::Colours::black.withAlpha (0.10f));
  2106. }
  2107. else
  2108. g.setColour (isC && colour != accent ? colour.withMultipliedBrightness (0.9f) : colour);
  2109. g.fillRect (r);
  2110. };
  2111. const auto fillBlack = [&] (juce::Colour colour, juce::Rectangle<int> r) {
  2112. g.setColour (colour);
  2113. g.fillRect (r);
  2114. };
  2115. const auto keyColour = [&] (int key) {
  2116. const auto black = isBlackKey (key) && ! list;
  2117. const auto pressed = key == previewKey || isLit (key);
  2118. auto colour = black ? keyBlack : keyWhite; // (no scale tint on the keys: FL draws the piano as it is, round 190kd)
  2119. if (key == hover.key && ! pressed)
  2120. colour = colour.interpolatedWith (accent, black ? 0.35f : 0.22f);
  2121. return pressed ? accent : colour;
  2122. };
  2123. const auto labelClass = scaleIndex() > 0 ? scaleRoot() : 0; // (once per paint)
  2124. // FL's black keys at rest (round 190oo O-2): dark at the left to lighter at the tip (FL 2026: #2a2b2d -> #4e4f51),
  2125. // six solid steps of the shade per key (a gradient fill, or one rectangle list per step, cost +1.7 % of the
  2126. // Piano roll's frame, --paintbench); a lit (hovered, pressed) black key is filled in its own colour
  2127. constexpr int shadeSteps = 6;
  2128. juce::Colour shade[shadeSteps];
  2129. for (int k = 0; k < shadeSteps; ++k)
  2130. shade[k] = keyBlack.interpolatedWith (keyWhite, 0.18f * ((float) k + 0.5f) / (float) shadeSteps);
  2131. for (int key = 0; key < 128; ++key)
  2132. {
  2133. const auto y = keyToY (key);
  2134. if (! rows.shown (key) || y > keys.getBottom() || y + rowHeight < keys.getY())
  2135. continue;
  2136. const auto black = isBlackKey (key) && ! list;
  2137. const auto pressed = key == previewKey || isLit (key);
  2138. const auto hovered = key == hover.key && ! pressed;
  2139. const auto colour = keyColour (key);
  2140. const auto width = black ? blackWidth : keyboardWidth - 1;
  2141. if (piano)
  2142. {
  2143. // "Piano keys" (round 190j, discussion #136): the white keys meet behind the black key, each in its own
  2144. // colour (hover, pressed, scale), with a dark line between every two white keys
  2145. // (FL's keys, round 190oo O-2: no line through the black keys' rows, and a faint one, FL's #c6cad0 on
  2146. // #e3e7ee, between B / C and E / F)
  2147. const auto line = flKeys ? juce::Colours::black.withAlpha (0.13f) : bg0.withAlpha (0.85f);
  2148. if (black)
  2149. {
  2150. const auto upper = pianokeys::upperPart (rowHeight);
  2151. // (FL's keys: the white keys only right of the black key, which the gradient above already filled)
  2152. const auto whiteX = flKeys ? blackWidth : 0;
  2153. fillKey (juce::jmin (127, key + 1), keyColour (juce::jmin (127, key + 1)), { whiteX, y, keyboardWidth - 1 - whiteX, upper });
  2154. fillKey (juce::jmax (0, key - 1), keyColour (juce::jmax (0, key - 1)), { whiteX, y + upper, keyboardWidth - 1 - whiteX, rowHeight - upper });
  2155. // the black key: a little shorter than its row when there is room, so the white shows around it
  2156. const auto inset = rowHeight >= 12 ? 1 : 0;
  2157. if (flKeys)
  2158. {
  2159. if (colour != keyBlack)
  2160. fillBlack (colour, { 0, y + inset, blackWidth, rowHeight - 2 * inset });
  2161. else
  2162. for (int k = 0; k < shadeSteps; ++k)
  2163. {
  2164. const auto x0 = blackWidth * k / shadeSteps, x1 = blackWidth * (k + 1) / shadeSteps;
  2165. g.setColour (shade[k]);
  2166. g.fillRect (x0, y + inset, x1 - x0, rowHeight - 2 * inset);
  2167. }
  2168. }
  2169. else
  2170. {
  2171. g.setColour (line);
  2172. g.drawHorizontalLine (y + upper, (float) blackWidth, (float) (keyboardWidth - 1));
  2173. g.setColour (bg0);
  2174. g.fillRect (0, y + inset, blackWidth + 1, rowHeight - 2 * inset);
  2175. fillBlack (colour, { 0, y + inset, blackWidth, rowHeight - 2 * inset });
  2176. if (! pressed && rowHeight >= 12) // a light edge along the top, as on a real black key
  2177. {
  2178. g.setColour (keyWhite.withAlpha (0.14f));
  2179. g.drawHorizontalLine (y + inset, 0.0f, (float) blackWidth);
  2180. }
  2181. }
  2182. }
  2183. else
  2184. {
  2185. fillKey (key, colour, { 0, y, width, rowHeight });
  2186. if (pianokeys::lineBelow (key))
  2187. {
  2188. g.setColour (line);
  2189. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  2190. }
  2191. }
  2192. }
  2193. else
  2194. {
  2195. if (black)
  2196. {
  2197. g.setColour (bg0); // (the row right of the black key stays dark, over the column's white gradient)
  2198. g.fillRect (width, y, keyboardWidth - 1 - width, rowHeight);
  2199. fillBlack (colour, { 0, y, width, rowHeight });
  2200. }
  2201. else
  2202. fillKey (key, colour, { 0, y, width, rowHeight });
  2203. g.setColour (black ? bg0 : keyWhite.darker (0.3f));
  2204. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  2205. }
  2206. // the octave name on each C; with a chosen scale on each root, as FL labels it (round 190kd: "A3", "A4" in A minor)
  2207. const auto isC = key % 12 == labelClass;
  2208. // every key named (LYNX, on by default: notenames::everyKey) once the rows are tall enough to read
  2209. const auto everyKey = notenames::everyKey.load (std::memory_order_relaxed) && rowHeight >= 8;
  2210. // (round 190jo FM-17: as FL, only the Cs are named on the piano by default, larger and bold; "Note names on
  2211. // every key" names the others; a folded list names each row)
  2212. if (isC || hovered || pressed || everyKey || (list && rowHeight >= 8))
  2213. {
  2214. g.setFont (isC && ! list ? theme::font (juce::jmin (theme::type::body, fontHeight + 1.0f), true) : theme::font (fontHeight, isC));
  2215. // (round 190oo PAT-15: the hovered white key's name in the C keys' full ink, 11.9:1; it was at 55 %)
  2216. g.setColour (pressed ? onAccent : black ? textPrimary.withAlpha (hovered ? 1.0f : 0.85f) : isC || hovered ? bg0 : bg0.withAlpha (everyKey ? 0.72f : 0.55f));
  2217. const auto area = black ? juce::Rectangle<int> (2, y, blackWidth - 4, rowHeight)
  2218. : isC ? juce::Rectangle<int> (8, y, keyboardWidth - 13, rowHeight)
  2219. : juce::Rectangle<int> (blackWidth, y, keyboardWidth - blackWidth - 5, rowHeight);
  2220. textcache::drawText (g, keyName (key), area, black ? juce::Justification::centredLeft : juce::Justification::centredRight, false);
  2221. }
  2222. // a key label (FL 2026's custom key labels) replaces the name on the white part of the key
  2223. if (const auto label = labels.find (key); label != labels.end() && rowHeight >= 8)
  2224. {
  2225. const auto area = juce::Rectangle<int> (black ? blackWidth + 2 : 3, y, keyboardWidth - (black ? blackWidth + 2 : 3) - 4, rowHeight);
  2226. g.setColour (black ? keyWhite : colour);
  2227. g.fillRect (area);
  2228. g.setFont (theme::font (fontHeight, false));
  2229. g.setColour (pressed ? onAccent : bg0);
  2230. g.drawFittedText (juce::String::fromUTF8 (label->second.c_str()), area.reduced (1, 0), juce::Justification::centredLeft, 1, 0.8f);
  2231. }
  2232. if (! padRows.empty()) // (a Drum Rack's pad rows: a strip at the right in the key's piano colour, as Live's list)
  2233. {
  2234. g.setColour (isBlackKey (key) ? keyBlack : keyWhite.darker (0.25f));
  2235. g.fillRect (keyboardWidth - 12, y, 11, rowHeight - 1);
  2236. }
  2237. }
  2238. g.setColour (border);
  2239. g.fillRect (keyboardWidth - 1, keys.getY(), 1, keys.getHeight());
  2240. }
  2241. // velocity lane label
  2242. for (int laneIndex = 0; laneIndex <= (int) stacked.size(); ++laneIndex) // (round 190on: each stacked lane too)
  2243. {
  2244. const LaneScope laneScope (*this, laneIndex < (int) stacked.size() ? laneIndex : -1);
  2245. {
  2246. const auto lane = velocityArea();
  2247. g.setColour (bg2);
  2248. g.fillRect (0, lane.getY(), keyboardWidth, lane.getHeight());
  2249. // the property combo sits here; round 190mf (DL-80): Live's value at the hovered / dragged marker's height
  2250. if (liveVelocityReadout.note >= 0)
  2251. {
  2252. g.setColour (juce::Colour (181, 181, 181));
  2253. g.setFont (theme::font (theme::type::caption, true));
  2254. const auto low = (float) lane.getBottom() - 12.0f, high = juce::jmin (low, (float) lane.getY() + 24.0f); // (under the lane's combo)
  2255. const auto y = juce::jlimit (high, low, liveVelocityReadout.y - 6.0f);
  2256. textcache::drawText (g, juce::String (liveVelocityReadout.value), juce::Rectangle<float> (4.0f, y, (float) keyboardWidth - 10.0f, 12.0f),
  2257. juce::Justification::centredRight, false);
  2258. }
  2259. }
  2260. }
  2261. if (mpeStacked) // round 190jd: the MPE tab's left column (icons, scales), its footer and the hovered value
  2262. paintMpeTabFrame (g);
  2263. // the event editor's divider (round 190fz): FL's 10 px bar, a dark line at its top and bottom, lighter than the
  2264. // grid, with a grip of five 2 px dots 4 px apart in its middle (FL's SplitterPaint: darker than the bar at rest,
  2265. // lighter when a pane is folded away, the highlight colour while it is dragged; FL shot: triage190j/FL-pianoroll.png)
  2266. if (const auto divider = eventPaneBarArea(); ! divider.isEmpty() && g.clipRegionIntersects (divider))
  2267. {
  2268. g.setColour (bg3);
  2269. g.fillRect (divider);
  2270. g.setColour (bg0);
  2271. g.fillRect (divider.getX(), divider.getY(), divider.getWidth(), 1);
  2272. g.fillRect (divider.getX(), divider.getBottom() - 1, divider.getWidth(), 1);
  2273. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  2274. const auto atEnd = eventPaneBarTop <= top || eventPaneBarTop >= bottom;
  2275. g.setColour (drag == Drag::eventPaneBar && ! atEnd ? accent : atEnd ? textSecondary : bg1);
  2276. const auto centre = divider.getCentre();
  2277. for (int i = -2; i <= 2; ++i)
  2278. g.fillRect (centre.x + i * 4 - 1, centre.y - 1, 2, 2);
  2279. }
  2280. // the zoom wheel (round 190j): FL's small square with a mark in its middle, at the end of the time scroll bar
  2281. {
  2282. const auto wheel = zoomWheelArea().toFloat().reduced (1.0f);
  2283. const auto over = drag == Drag::keyZoom || zoomWheelHover;
  2284. g.setColour (bg2);
  2285. g.fillRect (zoomWheelArea());
  2286. g.setColour (over ? bg5 : bg4);
  2287. g.fillRoundedRectangle (wheel, 2.0f);
  2288. g.setColour (over ? textPrimary : textSecondary);
  2289. g.fillRect (juce::Rectangle<float> (4.0f, 5.0f).withCentre (wheel.getCentre()));
  2290. }
  2291. // top-left corner: channel name
  2292. g.setColour (bg3);
  2293. g.fillRect (0, 0, keyboardWidth, toolbarHeight);
  2294. g.setColour (bg2);
  2295. g.fillRect (0, toolbarHeight, keyboardWidth, headerHeight - toolbarHeight);
  2296. g.setColour (border);
  2297. g.fillRect (0, headerHeight - 1, keyboardWidth, 1);
  2298. g.fillRect (keyboardWidth - 1, 0, 1, headerHeight);
  2299. if (channel < (int) song.channels.size())
  2300. {
  2301. const auto& ch = song.channels[(std::size_t) channel];
  2302. g.setColour (ch.colour != 0 ? theme::tame (juce::Colour (ch.colour)) : accent);
  2303. g.fillRoundedRectangle (4.0f, (float) toolbarHeight + 6.0f, 3.0f, (float) (headerHeight - toolbarHeight) - 12.0f, 1.0f);
  2304. g.setColour (textPrimary);
  2305. g.setFont (theme::font (theme::type::caption, true));
  2306. textcache::drawFittedText (g, juce::String::fromUTF8 (ch.name.c_str()), 11, toolbarHeight, keyboardWidth - 14, headerHeight - toolbarHeight,
  2307. juce::Justification::centredLeft, 2, 0.8f);
  2308. // Freeze (round 190ay): the frozen mark over the notes' top right corner, with what to do
  2309. if (ch.freeze.on())
  2310. {
  2311. const auto text = tr ("Frozen: Unfreeze to edit");
  2312. g.setFont (theme::font (theme::type::caption, true));
  2313. const auto grid = gridArea();
  2314. const auto width = juce::jmin (grid.getWidth() - 8, 34 + juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), text));
  2315. if (width > 40)
  2316. {
  2317. const auto pill = juce::Rectangle<float> ((float) grid.getRight() - (float) width - 6.0f, (float) grid.getY() + 6.0f, (float) width, 20.0f);
  2318. theme::fillRoundRect (g, pill, theme::radius::md, bg1.withAlpha (0.88f));
  2319. theme::drawFrozenTag (g, juce::Rectangle<float> (pill.getX() + 4.0f, pill.getCentreY() - 6.5f, 14.0f, 13.0f), info.withAlpha (0.85f), bg1);
  2320. g.setColour (textSecondary);
  2321. g.drawText (text, pill.withTrimmedLeft (24.0f).withTrimmedRight (6.0f), juce::Justification::centredLeft, true);
  2322. }
  2323. }
  2324. }
  2325. // round gap190og (detail-047): Live's footer under the lanes (its Velocity Controls are child buttons): a 1 px #242424
  2326. // line, then #363636 [SHOT live-01-velocity-lane.png y 977…994]
  2327. if (const auto footer = liveFooterHeight(); footer > 0)
  2328. {
  2329. const auto top = getHeight() - footer;
  2330. g.setColour (juce::Colour (0xff242424));
  2331. g.fillRect (0, top, getWidth(), 1);
  2332. g.setColour (theme::livelook::surface);
  2333. g.fillRect (0, top + 1, getWidth(), footer - 1);
  2334. }
  2335. // round 190mr (DE-63, capture 190mr prhold): FL's hold ring, a thin light arc at the mouse growing clockwise from 12
  2336. // o'clock between 390 and 750 ms of a still press
  2337. if (holdRing && hold != Hold::none)
  2338. {
  2339. const auto elapsed = (int) (juce::Time::getMillisecondCounter() - holdSince);
  2340. const auto t = juce::jlimit (0.0f, 1.0f, (float) (elapsed - holdRingFromMs) / (float) (holdMs - holdRingFromMs));
  2341. if (t > 0.0f)
  2342. {
  2343. juce::Path arc;
  2344. const auto c = holdRingAt.toFloat();
  2345. arc.addCentredArc (c.x, c.y, 6.5f, 6.5f, 0.0f, 0.0f, juce::MathConstants<float>::twoPi * t, true);
  2346. g.setColour (juce::Colour (0xffdfe6e6));
  2347. g.strokePath (arc, juce::PathStrokeType (1.5f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  2348. }
  2349. }
  2350. }
  2351. // --- mouse -------------------------------------------------------------------
  2352. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge) const
  2353. {
  2354. bool left = false;
  2355. return noteAt (x, y, onRightEdge, left);
  2356. }
  2357. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge, bool& onLeftEdge) const
  2358. {
  2359. // the same hit test as the hover (cursor and highlight), so a click does what the cursor showed
  2360. const auto h = hoverAt ({ x, y });
  2361. onRightEdge = h.zone == gesture::Zone::rightEdge;
  2362. onLeftEdge = h.zone == gesture::Zone::leftEdge;
  2363. return gridArea().contains (x, y) ? h.note : -1;
  2364. }
  2365. int PianoRollComponent::ghostAt (int x, int y) const
  2366. {
  2367. if (! showGhosts)
  2368. return -1;
  2369. const auto& notes = currentPattern (engine.getSong()).notes;
  2370. const auto key = yToKey (y);
  2371. for (int i = (int) notes.size() - 1; i >= 0; --i)
  2372. {
  2373. const auto& n = notes[(std::size_t) i];
  2374. if (! edits (n) && n.key == key && ghostShown (n.channel) && x >= tickToX ((double) n.start) && x < tickToX ((double) (n.start + n.length)))
  2375. return i;
  2376. }
  2377. return -1;
  2378. }
  2379. float PianoRollComponent::keyVelocityAt (int x, int key) const
  2380. {
  2381. // FL: a click near the left of a key plays it softly, at its right end at full velocity (black keys are shorter)
  2382. return gesture::keyClickVelocity ((double) x, (double) (isBlackKey (key) ? keyboardWidth * 3 / 5 : keyboardWidth - 1));
  2383. }
  2384. void PianoRollComponent::previewOn (int key, float velocity)
  2385. {
  2386. // one preview note at a time; it remembers its channel, so a channel switch meanwhile can't strand it
  2387. previewNotes.releaseAll();
  2388. previewKey = key;
  2389. previewNotes.press (engine.getSelectedChannel(), key, velocity);
  2390. repaint (0, headerHeight, keyboardWidth, getHeight());
  2391. }
  2392. void PianoRollComponent::previewEdit (int key, float velocity)
  2393. {
  2394. if (gesture::previewsEditedNote (engine.getTransport().playing.load(), previewWhilePlaying))
  2395. previewOn (key, velocity);
  2396. }
  2397. void PianoRollComponent::previewOff()
  2398. {
  2399. previewNotes.releaseAll();
  2400. if (previewKey >= 0)
  2401. {
  2402. previewKey = -1;
  2403. repaint (0, headerHeight, keyboardWidth, getHeight());
  2404. }
  2405. }
  2406. void PianoRollComponent::visibilityChanged()
  2407. {
  2408. if (! isShowing()) // hidden mid-gesture (window closed, tab switched): nothing keeps sounding
  2409. {
  2410. previewOff();
  2411. stopListening();
  2412. }
  2413. }
  2414. // The note properties the bottom lane edits: FL's (velocity, pan, fine pitch, release, Mod X / Y: its "Control" list,
  2415. // FLEngine strings "Note release", "Note modulation X / Y"), then Live 12's Chance and Velocity Range (round 187c, LYNX
  2416. // additions marked "(LYNX)")
  2417. void PianoRollComponent::addNoteLanes()
  2418. {
  2419. laneBox.addItem (tr ("Velocity"), laneVelocity);
  2420. laneBox.addItem (tr ("Pan"), lanePan);
  2421. laneBox.addItem (tr ("Fine pitch"), laneFinePitch);
  2422. laneBox.addItem (tr ("Release"), laneRelease);
  2423. laneBox.addItem (tr ("Mod X"), laneModX);
  2424. laneBox.addItem (tr ("Mod Y"), laneModY);
  2425. laneBox.addItem (tr ("Chance"), laneChance);
  2426. laneBox.addItem (tr ("Velocity range (LYNX)"), laneVelocityRange);
  2427. // MPE stage 2 (round 190hy, issue #108): each note's own pitch bend / slide (CC 74) / pressure curve, as Live 11+'s
  2428. // note expression lanes (LYNX additions: FL 2026 has no per-note curves)
  2429. laneBox.addItem (tr ("MPE pitch bend"), laneMpePitch);
  2430. laneBox.addItem (tr ("MPE slide"), laneMpeSlide);
  2431. laneBox.addItem (tr ("MPE pressure"), laneMpePressure);
  2432. }
  2433. float PianoRollComponent::laneValue (const Note& n) const
  2434. {
  2435. switch (laneId())
  2436. {
  2437. case lanePan: return (n.pan + 1.0f) * 0.5f;
  2438. case laneFinePitch: return (n.finePitch + 120.0f) / 240.0f;
  2439. case laneRelease: return n.release;
  2440. case laneModX: return n.modX;
  2441. case laneModY: return n.modY;
  2442. case laneChance: return n.chance;
  2443. case laneVelocityRange: return (n.velocityRange + 1.0f) * 0.5f;
  2444. case laneMpePitch: return 0.5f; // (the MPE lanes edit curves, not one value: round 190hy)
  2445. case laneMpeSlide: return n.modX;
  2446. case laneMpePressure: return mpe::pressureOfModY (n.modY);
  2447. default: return n.velocity;
  2448. }
  2449. }
  2450. void PianoRollComponent::setLaneValue (Note& n, float v) const
  2451. {
  2452. v = juce::jlimit (0.0f, 1.0f, v);
  2453. switch (laneId())
  2454. {
  2455. case lanePan: n.pan = std::abs (v - 0.5f) < 0.02f ? 0.0f : v * 2.0f - 1.0f; break; // snaps to center
  2456. case laneFinePitch: n.finePitch = std::round (v * 240.0f - 120.0f); break;
  2457. case laneRelease: n.release = v; break;
  2458. case laneModX: n.modX = v; break;
  2459. case laneModY: n.modY = v; break;
  2460. case laneChance: n.chance = std::round (v * 100.0f) / 100.0f; break; // whole percents, as Live shows them
  2461. case laneVelocityRange: // whole Live velocity steps (1/127); snaps to none
  2462. n.velocityRange = std::abs (v - 0.5f) < 0.02f ? 0.0f : std::round ((v * 2.0f - 1.0f) * 127.0f) / 127.0f;
  2463. break;
  2464. case laneMpePitch:
  2465. case laneMpeSlide:
  2466. case laneMpePressure: break; // (curves: the MPE lanes' own gestures edit them)
  2467. default: n.velocity = v; break;
  2468. }
  2469. }
  2470. bool PianoRollComponent::laneIsBipolar() const
  2471. {
  2472. const auto id = laneId();
  2473. return id == lanePan || id == laneFinePitch || id == laneVelocityRange || id == laneMpePitch || id >= eventLaneIdBase;
  2474. }
  2475. bool PianoRollComponent::laneIsChance() const { return laneId() == laneChance; }
  2476. void PianoRollComponent::applyVelocity (int fromX, int toX, int y)
  2477. {
  2478. const auto lane = velocityArea();
  2479. applyLaneValue (toX, juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8)), fromX);
  2480. }
  2481. void PianoRollComponent::applyLaneValue (int toX, float value, int fromX)
  2482. {
  2483. const auto lo = juce::jmin (fromX, toX) - 3, hi = juce::jmax (fromX, toX) + 3;
  2484. const auto& notes = currentPattern (engine.getSong()).notes;
  2485. std::vector<int> hits;
  2486. for (auto i : selectionOrAll())
  2487. {
  2488. const auto x = (int) tickToX ((double) notes[(std::size_t) i].start);
  2489. if (x >= lo && x <= hi)
  2490. hits.push_back (i);
  2491. }
  2492. if (! hits.empty())
  2493. editNotes ([this, &hits, value] (Pattern& p) {
  2494. for (auto i : hits)
  2495. setLaneValue (p.notes[(std::size_t) i], value);
  2496. if (laneIsChance())
  2497. notetools::spreadGroupChance (p, hits); // a probability group has one Chance
  2498. });
  2499. }
  2500. void PianoRollComponent::togglePorta()
  2501. {
  2502. const auto target = selectionOrAll();
  2503. if (target.empty())
  2504. return;
  2505. // like mute: if any note lacks porta, enable it on all; otherwise disable
  2506. const auto& notes = currentPattern (engine.getSong()).notes;
  2507. const auto porta = std::any_of (target.begin(), target.end(), [&notes] (int i) { return ! notes[(std::size_t) i].porta; });
  2508. editNotes ([&target, porta] (Pattern& p) {
  2509. for (auto i : target)
  2510. p.notes[(std::size_t) i].porta = porta;
  2511. });
  2512. }
  2513. void PianoRollComponent::setNotesMuted (bool mute)
  2514. {
  2515. const auto target = selectionOrAll();
  2516. if (target.empty())
  2517. return;
  2518. editNotes ([&target, mute] (Pattern& p) {
  2519. for (auto i : target)
  2520. p.notes[(std::size_t) i].muted = mute;
  2521. });
  2522. }
  2523. void PianoRollComponent::paintNoteAt (std::int64_t start, int key, bool monophonic)
  2524. {
  2525. // a brush stroke lays single notes (or the chosen chord) at the default length
  2526. Note n;
  2527. noteTemplate.applyTo (n);
  2528. n.start = juce::jmax<std::int64_t> (0, start);
  2529. n.length = paintLength;
  2530. n.key = key;
  2531. n.channel = engine.getSelectedChannel();
  2532. n.slide = slideButton.getToggleState();
  2533. n.colour = noteColour;
  2534. std::vector<Note> stamp;
  2535. for (const auto k : stampKeys (n.key, n.start)) // (the chord stamp; round 190nu: or the Scale degree chord)
  2536. {
  2537. auto chordNote = n;
  2538. chordNote.key = k;
  2539. stamp.push_back (chordNote);
  2540. }
  2541. editNotes ([&] (Pattern& p) {
  2542. if (monophonic) // Shift (or no Shift with "Monophonic painting"): the new note replaces what this channel plays then
  2543. {
  2544. std::vector<int> overlapping;
  2545. for (int i = 0; i < (int) p.notes.size(); ++i)
  2546. {
  2547. const auto& o = p.notes[(std::size_t) i];
  2548. if (o.channel == n.channel && o.start < n.start + n.length && o.start + o.length > n.start)
  2549. overlapping.push_back (i);
  2550. }
  2551. noteedit::remove (p, overlapping);
  2552. }
  2553. noteedit::paste (p, stamp, 0);
  2554. });
  2555. }
  2556. juce::Rectangle<int> PianoRollComponent::zoomWheelArea() const
  2557. {
  2558. // FL's VZoomSelect: the small square at the right end of the time scroll bar, over the vertical scroll bar
  2559. return { getWidth() - zoomWheelSize, toolbarHeight, zoomWheelSize, overviewHeight };
  2560. }
  2561. int PianoRollComponent::zoomAnchorKey() const
  2562. {
  2563. // FL (FUN_00e83850, REA round 167t): the middle of the notes in view, or the middle of the view
  2564. const auto grid = gridArea();
  2565. const auto top = yToKey (grid.getY()), bottom = yToKey (grid.getBottom() - 1);
  2566. const auto& notes = currentPattern (engine.getSong()).notes;
  2567. std::vector<int> keys;
  2568. for (auto i : channelNotes())
  2569. if (const auto key = notes[(std::size_t) i].key; key <= top && key >= bottom)
  2570. keys.push_back (key);
  2571. return gesture::zoomWheelAnchor (keys, top, bottom);
  2572. }
  2573. void PianoRollComponent::setRowHeightAround (int height, int key, int centreY)
  2574. {
  2575. rowHeight = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, height);
  2576. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), rowFor (key) * rowHeight + rowHeight / 2 - (centreY - headerHeight));
  2577. updateScrollBars();
  2578. repaint();
  2579. }
  2580. void PianoRollComponent::beginKeyZoom (const juce::MouseEvent& e)
  2581. {
  2582. drag = Drag::keyZoom;
  2583. keyZoomKey = zoomWheelArea().contains (e.getPosition()) ? zoomAnchorKey() : yToKey (e.y);
  2584. keyZoomStartRow = rowHeight;
  2585. keyZoomCentreY = keyToY (keyZoomKey) + rowHeight / 2;
  2586. keyZoomDrag.begin (e.y);
  2587. e.source.enableUnboundedMouseMovement (true); // FL hides the pointer while the zoom follows the travel
  2588. }
  2589. void PianoRollComponent::beginTimeZoom (const juce::MouseEvent& e)
  2590. {
  2591. drag = Drag::timeZoom;
  2592. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  2593. timeZoomDrag.begin (width / pixelsPerTick, scrollTicks + width * 0.5 / pixelsPerTick, e.x, e.y);
  2594. e.source.enableUnboundedMouseMovement (true);
  2595. }
  2596. void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
  2597. {
  2598. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::begin); // (round 190jv: one undo step per gesture)
  2599. followEditStamp = engine.getPublishCount(); // (round 190im, R15)
  2600. if (engine.getSong().channels.empty())
  2601. return;
  2602. // round 190on (P10): the line between two stacked lanes drags their heights; a press in a stacked lane works on that
  2603. // lane until the release (velocityArea() and the lane's id are that lane's meanwhile)
  2604. heldLane = boundaryDrag = -1;
  2605. enterLane (-1);
  2606. if (! stacked.empty())
  2607. {
  2608. if (const auto k = laneBoundaryAt (e.getPosition()); k >= 0 && e.mods.isLeftButtonDown())
  2609. {
  2610. boundaryDrag = k;
  2611. boundaryLastY = e.y;
  2612. return;
  2613. }
  2614. if (const auto i = stackedLaneAt (e.getPosition()); i >= 0)
  2615. {
  2616. heldLane = i;
  2617. enterLane (i);
  2618. }
  2619. }
  2620. downMods = e.mods;
  2621. startedOnEmpty = erasedSomething = holdExpired = false;
  2622. // FL's middle + right click (round 190mp, DE-62; capture 190mp A3.2): the second button's press opens the main menu at
  2623. // the mouse with the tools' "Mode" column on its left; whatever the first press began stops
  2624. if (e.mods.isMiddleButtonDown() && e.mods.isRightButtonDown())
  2625. {
  2626. showToolModeMenu();
  2627. return;
  2628. }
  2629. const auto onKeyboard = e.x < keyboardWidth && e.y >= headerHeight && e.y < gridArea().getBottom();
  2630. hover = {};
  2631. gliding = false;
  2632. // the zoom wheel (round 190j, discussion #10; FL's VZoomSelect): drag up = taller keys, one level (2 px) per 4 px of
  2633. // travel, per 16 px with Ctrl
  2634. if (zoomWheelArea().contains (e.getPosition()))
  2635. {
  2636. if (e.mods.isLeftButtonDown() || e.mods.isMiddleButtonDown())
  2637. beginKeyZoom (e);
  2638. return;
  2639. }
  2640. // the event editor's divider (round 190fz, FL's TQuickSplitter): left-drag moves it, a double-click or a right-click
  2641. // (swapped on release) gives the alternate size, a middle-click the default place
  2642. if (eventPaneBarArea().contains (e.getPosition()))
  2643. {
  2644. if (e.mods.isMiddleButtonDown())
  2645. resetEventPane();
  2646. else if (e.mods.isRightButtonDown())
  2647. drag = Drag::eventPaneAlternate;
  2648. else if (e.mods.isLeftButtonDown() && e.getNumberOfClicks() >= 2)
  2649. toggleEventPaneAlternate();
  2650. else if (e.mods.isLeftButtonDown())
  2651. {
  2652. drag = Drag::eventPaneBar;
  2653. eventPaneGrab = e.y - eventPaneBarTop;
  2654. repaint (eventPaneBarArea());
  2655. }
  2656. return;
  2657. }
  2658. // FL (TLEventPanelDblClick): a double-click on the event target panel, left of the event editor, swaps it too
  2659. if (! fitKeysToNotes && e.mods.isLeftButtonDown() && e.getNumberOfClicks() >= 2 && e.x < keyboardWidth && e.y >= velocityArea().getY())
  2660. {
  2661. toggleEventPaneAlternate();
  2662. return;
  2663. }
  2664. if (e.mods.isMiddleButtonDown())
  2665. {
  2666. // FL 2026 (round 167t, issue #26): middle-drag on the keyboard and Ctrl+middle-drag on the notes zoom
  2667. // vertically around the key under the mouse; middle-drag on the ruler and Alt+middle-drag on the notes
  2668. // zoom the time (drag up = zoom in, sideways = scroll)
  2669. const auto onNotes = gridArea().contains (e.getPosition());
  2670. const auto onRuler = e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth;
  2671. if (onKeyboard || (onNotes && flmods::ctrl (e.mods) && ! e.mods.isAltDown()))
  2672. {
  2673. beginKeyZoom (e);
  2674. return;
  2675. }
  2676. if (onRuler || (onNotes && e.mods.isAltDown()))
  2677. {
  2678. beginTimeZoom (e);
  2679. return;
  2680. }
  2681. drag = Drag::pan; // elsewhere it pans both ways, in every tool
  2682. panStartTicks = scrollTicks;
  2683. panStartY = scrollY;
  2684. setMouseCursor (editorCursor (gesture::Cursor::pan));
  2685. return;
  2686. }
  2687. if (onKeyboard)
  2688. {
  2689. if (flmods::ctrl (e.mods)) // Ctrl+click / drag: selects the notes of a key (range)
  2690. {
  2691. drag = Drag::keySelect;
  2692. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  2693. mouseDrag (e);
  2694. return;
  2695. }
  2696. if (e.mods.isRightButtonDown()) // key labels (FL 2026: right-click a key > Rename)
  2697. {
  2698. showKeyMenu (keyboardKeyAt (e.x, e.y));
  2699. return;
  2700. }
  2701. if (e.mods.isLeftButtonDown())
  2702. {
  2703. drag = Drag::keyboard;
  2704. previewOn (keyboardKeyAt (e.x, e.y), keyVelocityAt (e.x, keyboardKeyAt (e.x, e.y)));
  2705. }
  2706. return;
  2707. }
  2708. // ruler: a right press on a pattern marker opens its menu (FL's TimePanelMouseDown: the marker menu when the press
  2709. // is on the marker lane, REA_rodada168t.md table); the Time markers items are also in the More menu (round 168g)
  2710. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))
  2711. if (const auto mk = markerAtX (e.x); mk >= 0)
  2712. {
  2713. showPatternMarkerMenu (mk);
  2714. return;
  2715. }
  2716. // ruler: a time-range drag selects the notes in it. FL 2026 (one ruler handler for the Piano roll and the Playlist,
  2717. // TimePanelMouseDown 0xe56bf0, REA_rodada168t.md): Ctrl+drag, a double click held and dragged, the Select tool, or
  2718. // a right-drag (on a Mac Cmd or Control: core/ModifierMap.h)
  2719. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth
  2720. && ((e.mods.isLeftButtonDown() && (flmods::ctrl (e.mods) || e.getNumberOfClicks() >= 2 || (tools.getTool() == EditTool::lasso && ! ruler::seekWithAnyTool()))) // (#227: LYNX extra)
  2721. || (e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))))
  2722. {
  2723. drag = Drag::rulerSelect;
  2724. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  2725. return;
  2726. }
  2727. // ruler: click or drag = position (FL), Alt = off the grid
  2728. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isLeftButtonDown() && ! e.mods.isShiftDown())
  2729. {
  2730. drag = Drag::seek;
  2731. 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)
  2732. seekAt (e.x, ! e.mods.isAltDown());
  2733. return;
  2734. }
  2735. // round 190jd: the MPE tab's ▾ "Show Lane:" button and the focused lane's name, under the key column (Live 12.4)
  2736. if (mpeStacked && e.mods.isLeftButtonDown() && e.x < keyboardWidth && mpeFooterArea().contains (e.getPosition()))
  2737. {
  2738. mpeLaneMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this)
  2739. .withTargetScreenArea (localAreaToGlobal (mpeFooterArea().withWidth (keyboardWidth))));
  2740. return;
  2741. }
  2742. // Freeze (round 190ay): a frozen channel's notes and their lane are read-only (the keyboard, the ruler and the
  2743. // view gestures above still work)
  2744. if ((velocityArea().contains (e.getPosition()) || gridArea().contains (e.getPosition())) && refuseFrozenEdit())
  2745. return;
  2746. if (velocityArea().contains (e.getPosition()) && mpeMouseDown (e))
  2747. return;
  2748. if (velocityArea().contains (e.getPosition()) && eventLaneTarget())
  2749. {
  2750. // pattern events: drag draws one event per grid step, right-drag erases
  2751. lastVelocityX = e.x;
  2752. drag = e.mods.isRightButtonDown() ? Drag::eventErase : Drag::eventDraw;
  2753. drawEvents (e.x, e.x, e.y, drag == Drag::eventErase);
  2754. return;
  2755. }
  2756. if (velocityArea().contains (e.getPosition()))
  2757. {
  2758. const auto lane = velocityArea();
  2759. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  2760. lastVelocityX = e.x;
  2761. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click resets the notes under the mouse
  2762. {
  2763. drag = Drag::velocity;
  2764. applyLaneValue (e.x, laneValue (Note()), e.x); // (each property's default)
  2765. drag = Drag::none;
  2766. return;
  2767. }
  2768. laneOriginals = currentPattern (engine.getSong()).notes;
  2769. if (e.mods.isRightButtonDown()) // right-drag draws a straight line of values
  2770. {
  2771. drag = Drag::velocityLine;
  2772. laneSetValue = value;
  2773. return;
  2774. }
  2775. if (e.mods.isShiftDown()) // Shift+drag: every note crossed gets the value of the press
  2776. {
  2777. drag = Drag::velocitySet;
  2778. laneSetValue = value;
  2779. applyLaneValue (e.x, value, e.x);
  2780. return;
  2781. }
  2782. drag = Drag::velocity;
  2783. applyVelocity (e.x, e.x, e.y);
  2784. return;
  2785. }
  2786. if (! gridArea().contains (e.getPosition()))
  2787. return;
  2788. // the selection's stretch handle: drag scales the selected notes in time from the selection's start
  2789. if (e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods) && stretchHandle().expanded (2.0f).contains (e.position))
  2790. {
  2791. const auto& notes = currentPattern (engine.getSong()).notes;
  2792. dragIndices.clear();
  2793. dragOriginals.clear();
  2794. for (auto i : selection)
  2795. if (i >= 0 && i < (int) notes.size() && edits (notes[(std::size_t) i]))
  2796. {
  2797. dragIndices.push_back (i);
  2798. dragOriginals.push_back (notes[(std::size_t) i]);
  2799. }
  2800. noteedit::span (dragOriginals, stretchAnchor, stretchEnd);
  2801. dragNote = dragIndices.empty() ? -1 : dragIndices.front();
  2802. drag = Drag::stretch;
  2803. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  2804. return;
  2805. }
  2806. bool rightEdge = false, leftEdge = false;
  2807. const auto hit = noteAt (e.x, e.y, rightEdge, leftEdge);
  2808. const auto tool = tools.getTool();
  2809. // 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)
  2810. if (mpeStacked && e.mods.isLeftButtonDown() && mpePitchMouseDown (e, hit, rightEdge || leftEdge))
  2811. return;
  2812. // editable ghost notes (Ctrl+Alt+V): a left press on one switches to its channel and grabs the note there
  2813. if (hit < 0 && editGhosts && e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods))
  2814. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  2815. {
  2816. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  2817. if (noteAt (e.x, e.y, rightEdge, leftEdge) >= 0) // now it is one of this channel's notes
  2818. mouseDown (e);
  2819. return;
  2820. }
  2821. // Zoom tool: right-click zooms out around the point (a click zooms in, a drag zooms to the range)
  2822. if (tool == EditTool::zoom && e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))
  2823. {
  2824. zoomOut (e.x);
  2825. return;
  2826. }
  2827. // every tool: right click deletes (double right-click on a ghost note switches to its channel; with
  2828. // editable ghost notes a right-click deletes the ghost note itself)
  2829. if (e.mods.isRightButtonDown())
  2830. {
  2831. if (hit < 0 && editGhosts)
  2832. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  2833. {
  2834. setSelection ({});
  2835. editNotes ([ghost] (Pattern& p) { noteedit::remove (p, { ghost }); });
  2836. return;
  2837. }
  2838. if (hit < 0 && e.getNumberOfClicks() >= 2)
  2839. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  2840. {
  2841. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  2842. return;
  2843. }
  2844. drag = Drag::erase;
  2845. startedOnEmpty = hit < 0;
  2846. setSelection ({}); // indices change while deleting
  2847. if (hit >= 0)
  2848. {
  2849. erasedSomething = true;
  2850. fadeOut ({ hit }); // (issue #250)
  2851. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  2852. }
  2853. return;
  2854. }
  2855. // every tool: Ctrl+click on a note adds/removes it from the selection; Ctrl+drag selects (Shift adds)
  2856. if (hit >= 0 && flmods::ctrl (e.mods))
  2857. {
  2858. auto s = selection;
  2859. if (isSelected (hit))
  2860. s.erase (std::find (s.begin(), s.end(), hit));
  2861. else
  2862. s.push_back (hit);
  2863. setSelection (s);
  2864. return;
  2865. }
  2866. if ((hit < 0 && flmods::ctrl (e.mods)) || tool == EditTool::lasso
  2867. || (hit < 0 && e.mods.isShiftDown() && tool != EditTool::brush && tool != EditTool::drumPaint && tool != EditTool::pencil))
  2868. {
  2869. drag = Drag::select;
  2870. dragNote = hit; // a click without dragging selects this note (Lasso)
  2871. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  2872. rubberBand = {};
  2873. setSelection (selectionBefore);
  2874. return;
  2875. }
  2876. const auto snapOn = ! e.mods.isAltDown();
  2877. switch (tool)
  2878. {
  2879. case EditTool::eraser:
  2880. drag = Drag::erase;
  2881. setSelection ({});
  2882. if (hit >= 0)
  2883. {
  2884. fadeOut ({ hit }); // (issue #250)
  2885. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  2886. }
  2887. return;
  2888. case EditTool::mute:
  2889. drag = Drag::muting;
  2890. touchedNotes.clear();
  2891. if (hit >= 0)
  2892. {
  2893. muteTarget = ! currentPattern (engine.getSong()).notes[(std::size_t) hit].muted;
  2894. touchedNotes.push_back (hit);
  2895. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  2896. }
  2897. else
  2898. muteTarget = true;
  2899. return;
  2900. case EditTool::knife:
  2901. drag = Drag::knife;
  2902. knifeFrom = knifeTo = e.getPosition();
  2903. repaint();
  2904. return;
  2905. case EditTool::zoom:
  2906. drag = Drag::zoomRange;
  2907. rubberBand = {};
  2908. return;
  2909. case EditTool::listen:
  2910. drag = Drag::listen;
  2911. listenAt (e.x);
  2912. return;
  2913. case EditTool::pencil:
  2914. case EditTool::brush:
  2915. case EditTool::drumPaint:
  2916. case EditTool::lasso:
  2917. case EditTool::slip:
  2918. break;
  2919. }
  2920. // Pencil (and Brush on an existing note): Shift+drag on a note drags a copy
  2921. if (hit >= 0 && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  2922. {
  2923. const auto sources = isSelected (hit) ? selection : notetools::groupOf (currentPattern (engine.getSong()), hit);
  2924. const auto grabbedAt = (std::size_t) (std::find (sources.begin(), sources.end(), hit) - sources.begin());
  2925. std::vector<int> added;
  2926. // the copy comes out in the same order as the originals (copy sorts by start)
  2927. std::vector<Note> ordered;
  2928. for (auto i : sources)
  2929. ordered.push_back (currentPattern (engine.getSong()).notes[(std::size_t) i]);
  2930. editNotes ([&] (Pattern& p) {
  2931. added = noteedit::paste (p, ordered, 0);
  2932. notetools::regroup (p, added);
  2933. });
  2934. setSelection (added);
  2935. dragIndices = added;
  2936. dragOriginals = ordered;
  2937. lastScaleDragKeys = -1000;
  2938. dragNote = added[grabbedAt];
  2939. drag = Drag::move;
  2940. grabOffset = ordered[grabbedAt].start - snap (xToTick (e.x), snapOn);
  2941. previewEdit (ordered[grabbedAt].key, ordered[grabbedAt].velocity);
  2942. return;
  2943. }
  2944. if (hit >= 0)
  2945. {
  2946. const auto wasSelected = isSelected (hit);
  2947. if (! wasSelected) // a grouped note brings its group along (FL's note groups)
  2948. {
  2949. const auto members = notetools::groupOf (currentPattern (engine.getSong()), hit);
  2950. setSelection (members.size() > 1 ? members : std::vector<int> {});
  2951. }
  2952. const auto& notes = currentPattern (engine.getSong()).notes;
  2953. const auto& n = notes[(std::size_t) hit];
  2954. dragNote = hit;
  2955. dragIndices = selection.empty() ? std::vector<int> { hit } : selection;
  2956. dragOriginals.clear();
  2957. for (auto i : dragIndices)
  2958. dragOriginals.push_back (notes[(std::size_t) i]);
  2959. drag = rightEdge ? Drag::resize : leftEdge ? Drag::resizeLeft : Drag::move;
  2960. lastScaleDragKeys = 0; // (no scale step made yet)
  2961. // round 190mr (DE-63): FL's click-and-hold on a note (copy) or at the resize cursor between two touching notes (glue)
  2962. if (! e.mods.isShiftDown() && ! e.mods.isAltDown() && (tool == EditTool::pencil || tool == EditTool::brush))
  2963. {
  2964. if (drag == Drag::move && flsettings::options().clickHold.load())
  2965. armHold (Hold::copy, e.getScreenPosition());
  2966. else if (drag != Drag::move && flsettings::options().clickHold.load())
  2967. {
  2968. const auto& pat = currentPattern (engine.getSong());
  2969. const auto other = details190mr::touchingNeighbour (pat, hit, rightEdge);
  2970. if (other >= 0)
  2971. {
  2972. glueA = rightEdge ? hit : other;
  2973. glueB = rightEdge ? other : hit;
  2974. armHold (Hold::glue, e.getScreenPosition());
  2975. }
  2976. }
  2977. }
  2978. grabOffset = n.start - snap (xToTick (e.x), snapOn);
  2979. lastLength = n.length;
  2980. noteTemplate.takeFrom (n); // FL: new notes get the clicked note's properties (round 166e)
  2981. if (gesture::previewsGrabbedNote (rightEdge || leftEdge, wasSelected)) // FL: no sound on a resize or a selected grab
  2982. previewEdit (n.key, n.velocity);
  2983. return;
  2984. }
  2985. // new note (or the chosen chord, with the clicked note as the root)
  2986. setSelection ({});
  2987. createdAt = juce::Time::getMillisecondCounter();
  2988. if (tool == EditTool::drumPaint)
  2989. {
  2990. drag = Drag::drumPaint;
  2991. lastDrumCell = -1;
  2992. lastDrumKey = -1;
  2993. drumPaintAt (e.getPosition(), snapOn);
  2994. return;
  2995. }
  2996. if (tool == EditTool::brush)
  2997. {
  2998. drag = Drag::paint;
  2999. paintLength = juce::jmax<std::int64_t> (1, newNoteLength());
  3000. const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  3001. paintNoteAt (start, snapKey (yToKey (e.y)), noteedit::monophonicPaint (e.mods.isShiftDown(), monophonicPainting));
  3002. nextPaintTick = start + paintLength;
  3003. previewEdit (snapKey (yToKey (e.y)), noteTemplate.velocity);
  3004. return;
  3005. }
  3006. Note n;
  3007. noteTemplate.applyTo (n);
  3008. n.start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  3009. n.length = newNoteLength();
  3010. n.channel = engine.getSelectedChannel();
  3011. n.slide = slideButton.getToggleState();
  3012. n.colour = noteColour;
  3013. // the chord stamp's notes on the clicked key (round 190nu: or the Scale degree chord in the key of the click's region);
  3014. // the first one leads the drag
  3015. std::vector<Note> stamp;
  3016. for (const auto k : stampKeys (isDegreeStamp() ? yToKey (e.y) : snapKey (yToKey (e.y)), n.start))
  3017. {
  3018. auto chordNote = n;
  3019. chordNote.key = k;
  3020. stamp.push_back (chordNote);
  3021. }
  3022. n.key = stamp.empty() ? snapKey (yToKey (e.y)) : stamp.front().key;
  3023. clearDegreeGhost();
  3024. std::vector<int> added;
  3025. editNotes ([&] (Pattern& p) { added = noteedit::paste (p, stamp, 0); });
  3026. dragNote = added.front(); // the root leads the drag
  3027. dragIndices = added;
  3028. dragOriginals = stamp;
  3029. lastScaleDragKeys = -1000;
  3030. if (added.size() > 1)
  3031. setSelection (added);
  3032. drag = Drag::move;
  3033. // round 190mv (DE-69): FL's Draw tool "(Shift) add in stretch mode" (capture 190mv A3: Shift+press on the empty grid
  3034. // adds the note at the snapped spot and the drag stretches its end, the start stays; plain Draw moves it)
  3035. if (tool == EditTool::pencil && e.mods.isShiftDown())
  3036. drag = Drag::resize;
  3037. grabOffset = 0;
  3038. previewEdit (n.key, n.velocity);
  3039. holdStep = n.porta ? 2 : n.slide ? 1 : 0;
  3040. if (! e.mods.isShiftDown() && ! e.mods.isAltDown() && flsettings::options().clickHold.load())
  3041. armHold (Hold::cycle, e.getScreenPosition()); // round 190mr (DE-63): hold = slide, porta, plain…
  3042. }
  3043. void PianoRollComponent::pressForSnapshot (juce::Point<int> at, juce::ModifierKeys mods)
  3044. {
  3045. auto source = juce::Desktop::getInstance().getMainMouseSource();
  3046. const auto now = juce::Time::getCurrentTime();
  3047. 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));
  3048. holdRingAt = at; // (off screen, the screen point of the press is not this view's)
  3049. }
  3050. void PianoRollComponent::dragForSnapshot (juce::Point<int> at, juce::ModifierKeys mods)
  3051. {
  3052. auto source = juce::Desktop::getInstance().getMainMouseSource();
  3053. const auto now = juce::Time::getCurrentTime();
  3054. 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));
  3055. }
  3056. void PianoRollComponent::releaseForSnapshot (juce::Point<int> at)
  3057. {
  3058. auto source = juce::Desktop::getInstance().getMainMouseSource();
  3059. const auto now = juce::Time::getCurrentTime();
  3060. mouseUp (juce::MouseEvent (source, at.toFloat(), {}, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, this, this, now, at.toFloat(), now, 1, false));
  3061. }
  3062. void PianoRollComponent::armHold (Hold kind, juce::Point<int> screenAt, bool ring)
  3063. {
  3064. hold = kind;
  3065. holdDownAt = screenAt;
  3066. holdSince = juce::Time::getMillisecondCounter();
  3067. holdRing = ring; // (the cycle's later steps run without it)
  3068. holdRingAt = getLocalPoint (nullptr, screenAt);
  3069. const auto serial = ++holdSerial;
  3070. juce::Timer::callAfterDelay (holdMs, [safe = juce::Component::SafePointer<PianoRollComponent> (this), serial] {
  3071. if (safe != nullptr)
  3072. safe->holdFired (serial);
  3073. });
  3074. }
  3075. void PianoRollComponent::holdFired (int serial)
  3076. {
  3077. if (serial != holdSerial || hold == Hold::none)
  3078. return;
  3079. const auto& mouse = juce::Desktop::getInstance().getMainMouseSource();
  3080. // (a hold is a press that stays where it was: a drag, a release or another button ends it)
  3081. if (holdReadsMouse && ! mouse.isDragging() && ! juce::ModifierKeys::currentModifiers.isLeftButtonDown())
  3082. return void (hold = Hold::none);
  3083. if (holdReadsMouse && (mouse.getScreenPosition().roundToInt().getDistanceFrom (holdDownAt) > 3 || juce::ModifierKeys::currentModifiers.isRightButtonDown()))
  3084. return void (hold = Hold::none);
  3085. const auto kind = std::exchange (hold, Hold::none);
  3086. if (std::exchange (holdRing, false))
  3087. repaint (holdRingArea());
  3088. const auto& notes = currentPattern (engine.getSong()).notes;
  3089. if (kind == Hold::copy && drag == Drag::move && ! dragIndices.empty())
  3090. {
  3091. // the copy is what the mouse drags from here on; the originals stay (as Shift+drag)
  3092. std::vector<Note> ordered;
  3093. for (auto i : dragIndices)
  3094. if (i >= 0 && i < (int) notes.size())
  3095. ordered.push_back (notes[(std::size_t) i]);
  3096. const auto grabbedAt = (std::size_t) juce::jmax<std::ptrdiff_t> (0, std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin());
  3097. // FL's "clone note": the clone lands one grid step later and is the one dragged from here on
  3098. const auto step = juce::jmax<std::int64_t> (1, gridTicks());
  3099. for (auto& n : ordered)
  3100. n.start += step;
  3101. std::vector<int> added;
  3102. editNotes ([&] (Pattern& p) {
  3103. added = noteedit::paste (p, ordered, 0);
  3104. notetools::regroup (p, added);
  3105. });
  3106. if (added.empty())
  3107. return;
  3108. setSelection (added);
  3109. dragIndices = added;
  3110. dragOriginals = ordered;
  3111. lastScaleDragKeys = -1000;
  3112. grabOffset += step;
  3113. dragNote = added[juce::jmin (grabbedAt, added.size() - 1)];
  3114. ui::postHint ({ tr ("Note cloned: drag it where it goes"), {}, false, false }, 1500);
  3115. repaint();
  3116. return;
  3117. }
  3118. if (kind == Hold::cycle && drag == Drag::move && ! dragIndices.empty())
  3119. {
  3120. holdStep = (holdStep + 1) % 3;
  3121. editNotes ([this] (Pattern& p) {
  3122. for (auto i : dragIndices)
  3123. if (i >= 0 && i < (int) p.notes.size())
  3124. details190mr::setHoldCycle (p.notes[(std::size_t) i], holdStep);
  3125. });
  3126. static const char* const names[] = { TR_NOOP ("Plain note"), TR_NOOP ("Slide note"), TR_NOOP ("Porta note") };
  3127. ui::postHint ({ tr (names[holdStep]) + " " + tr ("(keep holding to change it)"), {}, false, false }, holdMs + 400);
  3128. repaint();
  3129. armHold (Hold::cycle, holdDownAt, false); // (the next step, while the button stays down)
  3130. return;
  3131. }
  3132. if (kind == Hold::glue && (drag == Drag::resize || drag == Drag::resizeLeft) && glueA >= 0 && glueB >= 0)
  3133. {
  3134. const auto keep = juce::jmin (glueA, glueB);
  3135. editNotes ([a = glueA, b = glueB] (Pattern& p) { noteedit::join (p, { a, b }); });
  3136. drag = Drag::none;
  3137. dragIndices.clear();
  3138. dragOriginals.clear();
  3139. dragNote = -1;
  3140. setSelection ({ keep }); // (FL: the glued note is selected; join keeps the earlier index)
  3141. ui::postHint ({ tr ("Notes glued"), {}, false, false }, 1500);
  3142. repaint();
  3143. }
  3144. }
  3145. void PianoRollComponent::mouseDrag (const juce::MouseEvent& e)
  3146. {
  3147. if (boundaryDrag >= 0) // round 190on (P10): two stacked lanes' heights
  3148. {
  3149. std::vector<float> weights;
  3150. for (const auto& l : stacked)
  3151. weights.push_back (l->spec.weight);
  3152. weights.push_back (bottomWeight);
  3153. stackedlanes::dragBoundary (weights, eventPaneArea().getHeight(), boundaryDrag, e.y - boundaryLastY);
  3154. boundaryLastY = e.y;
  3155. for (std::size_t i = 0; i < stacked.size(); ++i)
  3156. stacked[i]->spec.weight = weights[i];
  3157. bottomWeight = weights.back();
  3158. resized();
  3159. repaint (eventPaneArea().withX (0).withWidth (getWidth()));
  3160. return;
  3161. }
  3162. const auto snapOn = ! e.mods.isAltDown();
  3163. // after the step below, the hint bar says what the gesture is doing
  3164. const struct PostAfter
  3165. {
  3166. PianoRollComponent& roll;
  3167. const juce::MouseEvent& event;
  3168. ~PostAfter() { roll.postDragHint (event); }
  3169. } postAfter { *this, e };
  3170. switch (drag)
  3171. {
  3172. case Drag::none:
  3173. return;
  3174. case Drag::mpePoint: // round 190hy: the notes' MPE curves
  3175. case Drag::mpeDraw:
  3176. case Drag::mpeErase:
  3177. case Drag::mpeBend: // round 190jd: a pitch point on a note, a Velocity / Release Velocity lane
  3178. case Drag::mpeValue:
  3179. mpeMouseDrag (e);
  3180. return;
  3181. case Drag::eventPaneBar: // round 190fz: the divider follows the mouse (FL's SplitterChanging rule)
  3182. moveEventPaneBar (e.y - eventPaneGrab);
  3183. return;
  3184. case Drag::eventPaneAlternate: // (swapped when the right button is released)
  3185. return;
  3186. case Drag::pan:
  3187. scrollTicks = juce::jmax (0.0, panStartTicks - e.getDistanceFromDragStartX() / pixelsPerTick);
  3188. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), panStartY - e.getDistanceFromDragStartY());
  3189. updateScrollBars();
  3190. repaint();
  3191. return;
  3192. case Drag::keyboard:
  3193. {
  3194. const auto key = keyboardKeyAt (e.x, e.y);
  3195. if (key != previewKey)
  3196. previewOn (key, keyVelocityAt (e.x, key));
  3197. return;
  3198. }
  3199. case Drag::keyZoom:
  3200. {
  3201. // up = taller keys (Ctrl: fine); the centre of the clicked key stays where it was
  3202. keyZoomDrag.move (e.y, flmods::ctrl (e.mods));
  3203. rowHeight = keyZoomDrag.height (keyZoomStartRow);
  3204. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()),
  3205. rowFor (keyZoomKey) * rowHeight + rowHeight / 2 - (keyZoomCentreY - headerHeight));
  3206. updateScrollBars();
  3207. repaint();
  3208. return;
  3209. }
  3210. case Drag::timeZoom:
  3211. {
  3212. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  3213. timeZoomDrag.move (e.x, e.y, flmods::ctrl (e.mods));
  3214. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, width / timeZoomDrag.span);
  3215. scrollTicks = juce::jmax (0.0, timeZoomDrag.centre - width * 0.5 / pixelsPerTick);
  3216. updateScrollBars();
  3217. repaint();
  3218. return;
  3219. }
  3220. case Drag::keySelect:
  3221. {
  3222. const auto k0 = yToKey (e.getMouseDownY()), k1 = yToKey (e.y);
  3223. const auto& notes = currentPattern (engine.getSong()).notes;
  3224. auto s = selectionBefore;
  3225. for (auto i : channelNotes())
  3226. if (const auto k = notes[(std::size_t) i].key; k >= juce::jmin (k0, k1) && k <= juce::jmax (k0, k1))
  3227. s.push_back (i);
  3228. setSelection (s);
  3229. return;
  3230. }
  3231. case Drag::rulerSelect:
  3232. {
  3233. const auto t0 = (double) snap (xToTick (juce::jmin (e.getMouseDownX(), e.x)), snapOn);
  3234. const auto t1 = (double) snap (xToTick (juce::jmax (e.getMouseDownX(), e.x)) + (snapOn ? (double) gridTicks() : 0.0), snapOn);
  3235. const auto& notes = currentPattern (engine.getSong()).notes;
  3236. auto s = selectionBefore;
  3237. for (auto i : channelNotes())
  3238. if (const auto& n = notes[(std::size_t) i]; (double) n.start >= t0 && (double) n.start < t1)
  3239. s.push_back (i);
  3240. rubberBand = juce::Rectangle<int>::leftTopRightBottom ((int) tickToX (t0), gridArea().getY(), (int) tickToX (t1), gridArea().getBottom());
  3241. timeFrom = (std::int64_t) t0; // (round 168g: the range stays as the time selection)
  3242. timeTo = (std::int64_t) t1;
  3243. setSelection (s);
  3244. return;
  3245. }
  3246. case Drag::velocity:
  3247. applyVelocity (lastVelocityX, e.x, e.y);
  3248. lastVelocityX = e.x;
  3249. if (liveNotes()) // (round 190mf, DL-80: Live's value in the lane header follows the drag)
  3250. repaint (0, velocityArea().getY(), keyboardWidth, velocityArea().getHeight());
  3251. return;
  3252. case Drag::eventDraw:
  3253. case Drag::eventErase:
  3254. drawEvents (lastVelocityX, e.x, e.y, drag == Drag::eventErase);
  3255. lastVelocityX = e.x;
  3256. return;
  3257. case Drag::velocitySet:
  3258. applyLaneValue (e.x, laneSetValue, lastVelocityX);
  3259. lastVelocityX = e.x;
  3260. return;
  3261. case Drag::velocityLine:
  3262. {
  3263. // from the press to the mouse: notes in between follow the line, the others keep their value
  3264. const auto lane = velocityArea();
  3265. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  3266. const auto x0 = e.getMouseDownX(), x1 = e.x;
  3267. const auto lo = juce::jmin (x0, x1) - 3, hi = juce::jmax (x0, x1) + 3;
  3268. const auto targets = selectionOrAll();
  3269. knifeFrom = { x0, juce::roundToInt ((float) lane.getBottom() - 2.0f - laneSetValue * (float) (lane.getHeight() - 8)) };
  3270. knifeTo = e.getPosition();
  3271. editNotes ([&] (Pattern& p) {
  3272. for (auto i : targets)
  3273. {
  3274. if ((std::size_t) i >= laneOriginals.size() || (std::size_t) i >= p.notes.size())
  3275. continue;
  3276. auto& n = p.notes[(std::size_t) i];
  3277. n = laneOriginals[(std::size_t) i];
  3278. const auto x = (int) tickToX ((double) n.start);
  3279. if (x >= lo && x <= hi)
  3280. setLaneValue (n, (float) gesture::lineValue (x0, laneSetValue, x1, value, x));
  3281. }
  3282. if (laneIsChance())
  3283. notetools::spreadGroupChance (p, targets);
  3284. });
  3285. repaint();
  3286. return;
  3287. }
  3288. case Drag::select:
  3289. case Drag::zoomRange:
  3290. {
  3291. if (e.getDistanceFromDragStart() < 3 && rubberBand.isEmpty())
  3292. return;
  3293. const auto area = gridArea();
  3294. rubberBand = juce::Rectangle<int> (e.getMouseDownPosition(), e.getPosition()).getIntersection (area);
  3295. if (drag == Drag::zoomRange)
  3296. {
  3297. rubberBand = rubberBand.withY (area.getY()).withHeight (area.getHeight());
  3298. repaint();
  3299. return;
  3300. }
  3301. const auto t0 = xToTick (rubberBand.getX()), t1 = xToTick (rubberBand.getRight());
  3302. const auto kTop = yToKey (rubberBand.getY()), kBottom = yToKey (rubberBand.getBottom());
  3303. const auto& notes = currentPattern (engine.getSong()).notes;
  3304. auto s = selectionBefore;
  3305. for (auto i : channelNotes())
  3306. {
  3307. const auto& n = notes[(std::size_t) i];
  3308. if ((double) (n.start + n.length) > t0 && (double) n.start < t1 && n.key <= kTop && n.key >= kBottom)
  3309. s.push_back (i);
  3310. }
  3311. setSelection (s);
  3312. return;
  3313. }
  3314. case Drag::erase:
  3315. {
  3316. // right press-and-hold on empty grid, then drag: a temporary Knife
  3317. if (e.mods.isRightButtonDown() && startedOnEmpty && ! erasedSomething && ! holdExpired)
  3318. {
  3319. if (e.getLengthOfMousePress() >= 350)
  3320. {
  3321. drag = Drag::knife;
  3322. knifeFrom = e.getMouseDownPosition();
  3323. knifeTo = e.getPosition();
  3324. repaint();
  3325. return;
  3326. }
  3327. if (e.getDistanceFromDragStart() > 3)
  3328. holdExpired = true; // moved right away: it is an erase stroke
  3329. }
  3330. bool edge = false;
  3331. const auto hit = noteAt (e.x, e.y, edge);
  3332. if (hit >= 0)
  3333. {
  3334. erasedSomething = true;
  3335. fadeOut ({ hit }); // (issue #250)
  3336. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  3337. }
  3338. return;
  3339. }
  3340. case Drag::muting:
  3341. {
  3342. bool edge = false;
  3343. const auto hit = noteAt (e.x, e.y, edge);
  3344. if (hit >= 0 && std::find (touchedNotes.begin(), touchedNotes.end(), hit) == touchedNotes.end())
  3345. {
  3346. touchedNotes.push_back (hit);
  3347. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  3348. }
  3349. return;
  3350. }
  3351. case Drag::knife:
  3352. knifeTo = e.getPosition();
  3353. repaint();
  3354. return;
  3355. case Drag::listen:
  3356. listenAt (e.x);
  3357. return;
  3358. case Drag::seek:
  3359. seekAt (e.x, snapOn);
  3360. rulerMark = juce::jmax<std::int64_t> (0, snapOn ? snap (xToTick (e.x), true) : (std::int64_t) xToTick (e.x));
  3361. return;
  3362. case Drag::drumPaint:
  3363. drumPaintAt (e.getPosition(), snapOn);
  3364. return;
  3365. case Drag::stretch:
  3366. {
  3367. if (dragOriginals.empty() || stretchEnd <= stretchAnchor)
  3368. return;
  3369. // the new end of the selection: on the grid (the nearest line), or free with Alt
  3370. const auto minimum = snapOn ? juce::jmax<std::int64_t> (1, gridTicks()) : (std::int64_t) 10;
  3371. auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  3372. end = juce::jmax (stretchAnchor + minimum, end);
  3373. const auto stretched = polish::stretchNotes (dragOriginals, stretchAnchor, stretchEnd, end);
  3374. editNotes ([this, &stretched] (Pattern& p) {
  3375. for (std::size_t j = 0; j < dragIndices.size() && j < stretched.size(); ++j)
  3376. if ((std::size_t) dragIndices[j] < p.notes.size())
  3377. p.notes[(std::size_t) dragIndices[j]] = stretched[j];
  3378. });
  3379. repaint();
  3380. return;
  3381. }
  3382. case Drag::paint:
  3383. {
  3384. // lays notes to the right, one per default length, at the pitch under the mouse
  3385. const auto tick = snap (xToTick (e.x), snapOn);
  3386. for (int guard = 0; tick >= nextPaintTick && guard < 64; ++guard)
  3387. {
  3388. paintNoteAt (nextPaintTick, snapKey (yToKey (e.y)), noteedit::monophonicPaint (e.mods.isShiftDown(), monophonicPainting));
  3389. nextPaintTick += paintLength;
  3390. }
  3391. if (snapKey (yToKey (e.y)) != previewKey)
  3392. previewEdit (snapKey (yToKey (e.y)), noteTemplate.velocity);
  3393. return;
  3394. }
  3395. case Drag::move:
  3396. {
  3397. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  3398. auto deltaTicks = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset) - grabbed.start;
  3399. auto deltaKeys = snapKey (yToKey (e.y)) - grabbed.key;
  3400. auto rawKeys = yToKey (e.y) - grabbed.key; // (the mouse's own row, before any snap)
  3401. // locks: Shift pressed after the click keeps the pitch, Ctrl keeps the time
  3402. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  3403. deltaKeys = rawKeys = 0;
  3404. if (flmods::ctrl (e.mods) && ! flmods::ctrl (downMods))
  3405. deltaTicks = 0;
  3406. const auto& current = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  3407. // snap to scale (core/ScaleSnap.h, round 190an): the grabbed note follows the mouse onto the scale and the
  3408. // whole group moves that many scale steps; on the note's own row the pitch is left alone, also off the scale
  3409. const auto scale = snapScale();
  3410. const auto onScale = scale.active() && ! folded();
  3411. const auto scaleSteps = onScale ? scalesnap::dragSteps (scale, grabbed.key, grabbed.key + rawKeys) : 0;
  3412. if (current.start == grabbed.start + deltaTicks
  3413. && (onScale ? scaleSteps == lastScaleDragKeys : current.key == grabbed.key + deltaKeys))
  3414. return;
  3415. lastScaleDragKeys = scaleSteps;
  3416. const auto oldKey = current.key;
  3417. // from the original positions: the group keeps its shape even when hitting the limits
  3418. // folded to the scale (round 166d): the notes move by rows (scale degrees), so they stay on shown keys
  3419. const auto deltaRows = folded() ? rowFor (grabbed.key) - rowFor (grabbed.key + deltaKeys) : 0;
  3420. editNotes ([this, &deltaTicks, &deltaKeys, scale, scaleSteps, onScale, deltaRows] (Pattern& p) {
  3421. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3422. p.notes[(std::size_t) dragIndices[j]] = dragOriginals[j];
  3423. if (folded())
  3424. {
  3425. auto noKeys = 0;
  3426. noteedit::move (p, dragIndices, deltaTicks, noKeys);
  3427. if (deltaRows != 0)
  3428. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3429. p.notes[(std::size_t) dragIndices[j]].key = rows.step (dragOriginals[j].key, deltaRows);
  3430. return;
  3431. }
  3432. if (! onScale)
  3433. {
  3434. noteedit::move (p, dragIndices, deltaTicks, deltaKeys);
  3435. return;
  3436. }
  3437. // snap to scale: the time moves as a group, the pitch by scale steps (a chord stays a chord of the scale)
  3438. auto noKeys = 0;
  3439. noteedit::move (p, dragIndices, deltaTicks, noKeys);
  3440. scalesnap::moveBySteps (p, dragIndices, scaleSteps, scale);
  3441. });
  3442. const auto& moved = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  3443. if (moved.key != oldKey)
  3444. previewEdit (moved.key, moved.velocity);
  3445. return;
  3446. }
  3447. case Drag::resize:
  3448. {
  3449. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  3450. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  3451. const auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  3452. const auto delta = juce::jmax (minimum, end - grabbed.start) - grabbed.length;
  3453. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].length == grabbed.length + delta)
  3454. return;
  3455. lastLength = grabbed.length + delta;
  3456. editNotes ([this, delta, minimum] (Pattern& p) {
  3457. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3458. p.notes[(std::size_t) dragIndices[j]].length = juce::jmax (minimum, dragOriginals[j].length + delta);
  3459. });
  3460. return;
  3461. }
  3462. case Drag::resizeLeft:
  3463. {
  3464. // the start moves, the end stays (selected notes together)
  3465. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  3466. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  3467. auto delta = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn)) - grabbed.start;
  3468. for (const auto& o : dragOriginals)
  3469. delta = juce::jlimit (-o.start, o.length - juce::jmin (minimum, o.length), delta);
  3470. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].start == grabbed.start + delta)
  3471. return;
  3472. editNotes ([this, delta] (Pattern& p) {
  3473. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  3474. {
  3475. auto& n = p.notes[(std::size_t) dragIndices[j]];
  3476. n.start = dragOriginals[j].start + delta;
  3477. n.length = dragOriginals[j].length - delta;
  3478. }
  3479. });
  3480. lastLength = grabbed.length - delta;
  3481. return;
  3482. }
  3483. }
  3484. }
  3485. void PianoRollComponent::postDragHint (const juce::MouseEvent& e)
  3486. {
  3487. const auto& notes = currentPattern (engine.getSong()).notes;
  3488. const auto count = juce::String ((int) std::max<std::size_t> (1, dragIndices.size()));
  3489. auto steps = [] (std::int64_t ticks) {
  3490. const auto value = (double) ticks / ticksPerStep;
  3491. return (value > 0 ? "+" : "") + juce::String (value, std::abs (value - std::round (value)) < 1e-9 ? 0 : 2);
  3492. };
  3493. ui::Hint hint;
  3494. switch (drag)
  3495. {
  3496. case Drag::move:
  3497. {
  3498. const auto at = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin());
  3499. if (dragNote < 0 || dragNote >= (int) notes.size() || at >= dragOriginals.size())
  3500. return;
  3501. const auto& now = notes[(std::size_t) dragNote];
  3502. const auto& was = dragOriginals[at];
  3503. hint.text = tr ("Moving {0} note(s): then [Shift] keeps the pitch [Ctrl] keeps the time [Alt] no snap", { count });
  3504. hint.value = keyName (now.key) + " " + juce::String (now.key - was.key >= 0 ? "+" : "") + juce::String (now.key - was.key) + " st "
  3505. + steps (now.start - was.start) + " " + tr ("steps");
  3506. break;
  3507. }
  3508. case Drag::resize:
  3509. case Drag::resizeLeft:
  3510. if (dragNote < 0 || dragNote >= (int) notes.size())
  3511. return;
  3512. hint.text = tr ("Resizing {0} note(s) [Alt] no snap", { count });
  3513. hint.value = juce::String ((double) notes[(std::size_t) dragNote].length / ticksPerStep, 2) + " " + tr ("steps");
  3514. break;
  3515. case Drag::eventDraw:
  3516. case Drag::eventErase:
  3517. {
  3518. const auto lane = velocityArea();
  3519. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  3520. hint.text = drag == Drag::eventErase ? tr ("Deleting events") : tr ("Drawing events: {0}", { laneName() });
  3521. const auto target = eventLaneTarget();
  3522. hint.value = target && target->kind == AutomationTargetKind::tempo ? juce::String (tempoFromValue (value), 3) + " BPM" // (issue #86: as FL's hint)
  3523. : juce::String (juce::roundToInt (value * 100.0f)) + "%";
  3524. break;
  3525. }
  3526. case Drag::mpePoint:
  3527. case Drag::mpeDraw:
  3528. case Drag::mpeErase:
  3529. {
  3530. juce::Rectangle<int> area;
  3531. const auto id = mpeDragLane;
  3532. mpeLaneAt ({ lastMpeX, lastMpeY }, &area);
  3533. hint.text = drag == Drag::mpeErase ? tr ("Erasing the curve's points") : drag == Drag::mpePoint ? tr ("Moving the curve's point")
  3534. : tr ("Drawing the note's curve");
  3535. if (drag != Drag::mpeErase && ! area.isEmpty())
  3536. {
  3537. const auto norm = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - 2 - lastMpeY) / (float) juce::jmax (1, area.getHeight() - 8));
  3538. const auto v = mpeValue (id, norm, mpeDragRange);
  3539. hint.value = id == laneMpePitch ? tr ("{0} st", { juce::String (v / 100.0f, 2) })
  3540. : juce::String (juce::roundToInt (id == laneMpeSlide ? (float) mpe::timbreOfModX (v) : v * 127.0f));
  3541. }
  3542. break;
  3543. }
  3544. case Drag::mpeBend: // round 190jd: Live's tooltip on a pitch point ("0 st")
  3545. {
  3546. const auto& notes = currentPattern (engine.getSong()).notes;
  3547. hint.text = tr ("Bending the note's pitch [Shift] fine");
  3548. if (mpeDragNote >= 0 && mpeDragNote < (int) notes.size() && notes[(std::size_t) mpeDragNote].curves.has())
  3549. {
  3550. const auto& points = notes[(std::size_t) mpeDragNote].curves->lane (NoteCurveLane::pitch);
  3551. if (mpeDragPoint >= 0 && mpeDragPoint < (int) points.size())
  3552. {
  3553. const auto st = points[(std::size_t) mpeDragPoint].value / 100.0f;
  3554. hint.value = tr ("{0} st", { std::abs (st - std::round (st)) < 0.001f ? juce::String (juce::roundToInt (st)) : juce::String (st, 2) });
  3555. }
  3556. }
  3557. break;
  3558. }
  3559. case Drag::mpeValue:
  3560. {
  3561. const auto& notes = currentPattern (engine.getSong()).notes;
  3562. hint.text = tr ("Setting {0}", { mpeDragLane == laneRelease ? tr ("Release Velocity") : tr ("Velocity") });
  3563. if (mpeDragNote >= 0 && mpeDragNote < (int) notes.size())
  3564. hint.value = juce::String (juce::roundToInt (mpeValueLaneValue (mpeDragLane, notes[(std::size_t) mpeDragNote]) * 127.0f));
  3565. break;
  3566. }
  3567. case Drag::velocity:
  3568. case Drag::velocitySet:
  3569. case Drag::velocityLine:
  3570. {
  3571. const auto lane = velocityArea();
  3572. const auto value = drag == Drag::velocitySet ? laneSetValue
  3573. : juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  3574. hint.text = tr ("Setting {0}", { laneName() });
  3575. hint.value = juce::String (juce::roundToInt (value * 100.0f)) + "%";
  3576. break;
  3577. }
  3578. case Drag::select:
  3579. case Drag::keySelect:
  3580. case Drag::rulerSelect:
  3581. hint.text = tr ("Selecting [Shift] adds to the selection");
  3582. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  3583. break;
  3584. case Drag::erase: hint.text = tr ("Deleting what the mouse crosses"); break;
  3585. case Drag::muting: hint.text = tr ("Muting / unmuting what the mouse crosses"); break;
  3586. case Drag::knife: hint.text = tr ("Cutting along the line [Alt] no snap"); break;
  3587. case Drag::paint: hint.text = tr ("Painting notes [Alt] no snap"); break;
  3588. case Drag::drumPaint: hint.text = tr ("Drum brush: one hit per grid cell, on the key under the mouse [Alt] no snap"); break;
  3589. case Drag::stretch:
  3590. {
  3591. std::int64_t from = 0, to = 0;
  3592. std::vector<Note> now;
  3593. for (auto i : dragIndices)
  3594. if (i >= 0 && i < (int) notes.size())
  3595. now.push_back (notes[(std::size_t) i]);
  3596. noteedit::span (now, from, to);
  3597. hint.text = tr ("Stretching {0} note(s) in time [Alt] no snap", { count });
  3598. hint.value = "x" + juce::String ((double) (to - stretchAnchor) / (double) juce::jmax<std::int64_t> (1, stretchEnd - stretchAnchor), 2);
  3599. break;
  3600. }
  3601. case Drag::keyZoom: hint.text = tr ("Key height"); hint.value = tr ("Zoom level {0}", { juce::String (gesture::zoomLevel (rowHeight)) }) + " " + juce::String (rowHeight) + " px"; break;
  3602. case Drag::timeZoom: hint.text = tr ("Zooming: drag up = closer, sideways = scroll [Ctrl] zoom only"); break;
  3603. case Drag::keyboard:
  3604. hint.text = tr ("Hearing the key: further right on a key = louder");
  3605. hint.value = keyName (previewKey) + " " + tr ("vel {0}", { juce::String (juce::roundToInt (keyVelocityAt (e.x, previewKey) * 127.0f)) });
  3606. break;
  3607. case Drag::pan:
  3608. case Drag::seek: hint.text = tr ("Position [Alt] no snap"); break;
  3609. case Drag::listen:
  3610. case Drag::zoomRange:
  3611. case Drag::eventPaneBar: // (eventPaneChanged posts the percentage)
  3612. case Drag::eventPaneAlternate:
  3613. case Drag::none: return;
  3614. }
  3615. ui::postHint (hint);
  3616. }
  3617. void PianoRollComponent::mouseUp (const juce::MouseEvent& e)
  3618. {
  3619. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::end); // (closes when mouseUp returns)
  3620. if (boundaryDrag >= 0) // round 190on (P10): the heights are kept
  3621. {
  3622. boundaryDrag = -1;
  3623. saveStackedLanes();
  3624. return;
  3625. }
  3626. hold = Hold::none; // (round 190mr: a pending click-and-hold ends with the press)
  3627. ++holdSerial;
  3628. if (std::exchange (holdRing, false))
  3629. repaint (holdRingArea());
  3630. EditorGlobals::get().pauseFollowIfEdited (EditorGlobals::FollowView::pianoRoll, followEditStamp, engine.getPublishCount()); // (round 190im, R15)
  3631. ui::clearPostedHint();
  3632. if (drag == Drag::eventPaneBar) // round 190fz: remembered once the drag ends
  3633. saveEventPaneState();
  3634. if (drag == Drag::eventPaneAlternate)
  3635. {
  3636. drag = Drag::none;
  3637. toggleEventPaneAlternate();
  3638. }
  3639. if (drag == Drag::knife)
  3640. cutWithKnife (knifeFrom, knifeTo, ! e.mods.isAltDown());
  3641. if (drag == Drag::zoomRange)
  3642. {
  3643. if (rubberBand.getWidth() > 4)
  3644. zoomToTicks (xToTick (rubberBand.getX()), xToTick (rubberBand.getRight()));
  3645. else
  3646. zoomIn (e.x); // a click zooms in around the point (right-click zooms out)
  3647. }
  3648. if (drag == Drag::select && rubberBand.isEmpty() && dragNote >= 0)
  3649. {
  3650. // Lasso click on a note: selects it (Shift: adds / removes)
  3651. auto s = selectionBefore;
  3652. if (auto it = std::find (s.begin(), s.end(), dragNote); it != s.end())
  3653. s.erase (it);
  3654. else
  3655. s.push_back (dragNote);
  3656. setSelection (s);
  3657. }
  3658. // issue #213 (round 190mq): a double click (or a Ctrl+click) on the ruler released in place clears the time
  3659. // selection, as the Playlist's ruler does; FL 2026 also deselects the notes (capture f30 / f31) and drops the paste
  3660. // anchor (issue #211)
  3661. if (drag == Drag::rulerSelect && downMods.isLeftButtonDown() && e.getDistanceFromDragStart() < 3)
  3662. {
  3663. setTimeSelection (-1, -1);
  3664. rulerMark = -1;
  3665. if (! downMods.isShiftDown())
  3666. setSelection ({});
  3667. }
  3668. if (drag == Drag::listen)
  3669. stopListening();
  3670. if (drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft || drag == Drag::paint || drag == Drag::drumPaint
  3671. || drag == Drag::stretch)
  3672. sortNotes();
  3673. previewOff();
  3674. drag = Drag::none;
  3675. dragNote = -1;
  3676. dragIndices.clear();
  3677. dragOriginals.clear();
  3678. touchedNotes.clear();
  3679. laneOriginals.clear();
  3680. rubberBand = {};
  3681. hover = {};
  3682. heldLane = -1; // (round 190on: the gesture's stacked lane ends with it)
  3683. enterLane (-1);
  3684. updateHover (e.getPosition(), e.mods); // the cursor of what is under the mouse now
  3685. repaint();
  3686. }
  3687. void PianoRollComponent::mouseMove (const juce::MouseEvent& e)
  3688. {
  3689. if (const auto over = zoomWheelArea().contains (e.getPosition()); over != zoomWheelHover)
  3690. {
  3691. zoomWheelHover = over;
  3692. repaint (zoomWheelArea());
  3693. }
  3694. if (mpeStacked) // round 190jd: the value ghost point on a lane's line
  3695. updateMpeGhost (e.getPosition());
  3696. updateHover (e.getPosition(), e.mods);
  3697. updateDegreeGhost (e.getPosition()); // (round 190nu: nothing unless the Scale degree chord is the stamp)
  3698. feedMagicLasso (e.getPosition(), false); // (round 190mp, DE-71: nothing while the option is off)
  3699. if (const auto inLane = velocityArea().contains (e.getPosition()); liveNotes() && inLane != liveLaneHover) // (round 190mf, DL-80)
  3700. {
  3701. liveLaneHover = inLane;
  3702. repaint (0, velocityArea().getY(), getWidth(), velocityArea().getHeight());
  3703. }
  3704. if (laneBoundaryAt (e.getPosition()) >= 0) // round 190on (P10): the line between two stacked lanes
  3705. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  3706. }
  3707. void PianoRollComponent::mouseExit (const juce::MouseEvent&)
  3708. {
  3709. lastMouse = { -1, -1 };
  3710. if (std::exchange (zoomWheelHover, false))
  3711. repaint (zoomWheelArea());
  3712. if (mpeGhost.x >= 0.0f)
  3713. updateMpeGhost ({ -1, -1 });
  3714. clearDegreeGhost();
  3715. if (! (hover == Hover {}))
  3716. {
  3717. hover = {};
  3718. repaint();
  3719. }
  3720. }
  3721. void PianoRollComponent::modifierKeysChanged (const juce::ModifierKeys& mods)
  3722. {
  3723. // Ctrl / Shift / Alt change what a click would do: the cursor follows without moving the mouse
  3724. if (drag == Drag::none && lastMouse.x >= 0)
  3725. updateCursor (mods);
  3726. }
  3727. PianoRollComponent::Hover PianoRollComponent::hoverAt (juce::Point<int> p) const
  3728. {
  3729. Hover h;
  3730. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  3731. {
  3732. h.key = keyboardKeyAt (p.x, p.y);
  3733. return h;
  3734. }
  3735. if (velocityArea().contains (p))
  3736. {
  3737. // the stem nearest to the mouse (within a few pixels)
  3738. const auto& notes = currentPattern (engine.getSong()).notes;
  3739. auto best = 5.0;
  3740. for (auto i : channelNotes())
  3741. if (const auto d = std::abs (tickToX ((double) notes[(std::size_t) i].start) - p.x); d < best)
  3742. {
  3743. best = d;
  3744. h.note = i;
  3745. }
  3746. return h;
  3747. }
  3748. if (! gridArea().contains (p))
  3749. return h;
  3750. h.key = yToKey (p.y);
  3751. if (stretchHandle().expanded (2.0f).contains (p.toFloat()))
  3752. {
  3753. h.stretch = true;
  3754. return h;
  3755. }
  3756. const auto& notes = currentPattern (engine.getSong()).notes;
  3757. gesture::EdgeRules rules;
  3758. rules.allowLeft = resizeFromLeft;
  3759. // back to front: the note drawn on top wins
  3760. for (int i = (int) notes.size() - 1; i >= 0; --i)
  3761. {
  3762. const auto& n = notes[(std::size_t) i];
  3763. if (! edits (n) || n.key != h.key)
  3764. continue;
  3765. if (const auto zone = gesture::zoneAt (p.x, tickToX ((double) n.start), tickToX ((double) (n.start + n.length)), rules);
  3766. zone != gesture::Zone::outside)
  3767. {
  3768. h.note = i;
  3769. h.zone = zone;
  3770. return h;
  3771. }
  3772. }
  3773. h.ghost = ghostAt (p.x, p.y);
  3774. return h;
  3775. }
  3776. gesture::Target PianoRollComponent::targetAt (const Hover& h) const
  3777. {
  3778. return h.note >= 0 ? gesture::targetFor (h.zone) : gesture::Target::empty;
  3779. }
  3780. void PianoRollComponent::updateHover (juce::Point<int> p, juce::ModifierKeys mods)
  3781. {
  3782. const LaneScope laneScope (*this, heldLane >= 0 ? heldLane : stackedLaneAt (p)); // (round 190on: the stacked lane under the mouse)
  3783. lastMouse = p;
  3784. const auto h = hoverAt (p);
  3785. if (! (h == hover))
  3786. {
  3787. // repaint only what changed: the old and new note rows, the keyboard, the lane
  3788. auto dirty = [this] (const Hover& o) {
  3789. if (o.key >= 0)
  3790. repaint (0, keyToY (o.key) - 1, getWidth(), rowHeight + 2);
  3791. const auto& notes = currentPattern (engine.getSong()).notes;
  3792. for (auto i : { o.note, o.ghost })
  3793. if (i >= 0 && i < (int) notes.size())
  3794. {
  3795. repaint (0, keyToY (notes[(std::size_t) i].key) - 1, getWidth(), rowHeight + 2);
  3796. repaint (velocityArea());
  3797. }
  3798. };
  3799. dirty (hover);
  3800. hover = h;
  3801. dirty (hover);
  3802. }
  3803. if (drag == Drag::none)
  3804. updateCursor (mods);
  3805. }
  3806. void PianoRollComponent::updateCursor (juce::ModifierKeys mods)
  3807. {
  3808. const auto p = lastMouse;
  3809. auto cursor = gesture::Cursor::normal;
  3810. if (eventPaneBarArea().contains (p)) // the event editor's divider (FL: crVSplit)
  3811. {
  3812. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  3813. return;
  3814. }
  3815. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  3816. cursor = flmods::ctrl (mods) ? gesture::Cursor::select : gesture::Cursor::point;
  3817. else if (velocityArea().contains (p))
  3818. cursor = mpeStacked && ! drawmode::isOn() ? gesture::Cursor::point : gesture::Cursor::draw; // (round 190jd: Live's pointer)
  3819. else if (gridArea().contains (p) && hover.stretch && ! flmods::ctrl (mods))
  3820. cursor = gesture::Cursor::resizeH;
  3821. else if (gridArea().contains (p) && editGhosts && hover.note < 0 && hover.ghost >= 0 && ! flmods::ctrl (mods))
  3822. cursor = gesture::Cursor::move;
  3823. else if (gridArea().contains (p))
  3824. {
  3825. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  3826. const auto tool = tools.getTool();
  3827. cursor = gesture::cursorFor (gesture::leftAction (tool, targetAt (hover), m, false), tool);
  3828. }
  3829. else if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth && flmods::ctrl (mods))
  3830. cursor = gesture::Cursor::select;
  3831. else if (zoomWheelArea().contains (p))
  3832. cursor = gesture::Cursor::resizeV; // (FL: crSizeNS)
  3833. setMouseCursor (editorCursor (cursor));
  3834. }
  3835. ui::Hint PianoRollComponent::hintAt (juce::Point<int> p)
  3836. {
  3837. ui::Hint hint;
  3838. const auto mods = juce::ModifierKeys::currentModifiers;
  3839. const auto& song = engine.getSong();
  3840. const auto& notes = currentPattern (song).notes;
  3841. if (zoomWheelArea().contains (p))
  3842. {
  3843. hint.text = tr ("Key height: drag up / down or turn the wheel [Ctrl] fine");
  3844. hint.value = tr ("Zoom level {0}", { juce::String (gesture::zoomLevel (rowHeight)) });
  3845. return hint;
  3846. }
  3847. if (eventPaneBarArea().contains (p)) // round 190fz: FL's hint is "Right-click / shift+enter for alternate size"
  3848. {
  3849. hint.text = tr ("Event editor size: drag [RMB] or [Shift][Enter] alternate size [MMB] default size");
  3850. hint.value = juce::String (evpane::percentOf (eventPaneState().aspect)) + "%";
  3851. return hint;
  3852. }
  3853. const auto h = hoverAt (p);
  3854. auto noteValue = [&] (int i) {
  3855. const auto& n = notes[(std::size_t) i];
  3856. return keyName (n.key) + " " + juce::String (juce::roundToInt (n.velocity * 100.0f)) + "%";
  3857. };
  3858. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  3859. {
  3860. hint.text = tr ("Keyboard: [LMB] hear the key (further right = louder) [Ctrl][LMB] select its notes [MMB] drag: taller / shorter keys");
  3861. hint.value = keyName (h.key) + " " + tr ("vel {0}", { juce::String (juce::roundToInt (keyVelocityAt (p.x, h.key) * 127.0f)) });
  3862. return hint;
  3863. }
  3864. if (mpeStacked && p.x < keyboardWidth && mpeFooterArea().contains (p))
  3865. {
  3866. hint.text = tr ("Show Lane:") + " " + tr ("Slide") + ", " + tr ("Pressure") + ", " + tr ("Velocity") + ", " + tr ("Release Velocity");
  3867. return hint;
  3868. }
  3869. if (mpeStacked && velocityArea().contains (p) && ! isMpeLane (mpeLaneAt (p)))
  3870. {
  3871. hint.text = tr ("{0} lane: [LMB] drag sets the note under the mouse", { mpeLaneAt (p) == laneRelease ? tr ("Release Velocity") : tr ("Velocity") });
  3872. if (const auto note = mpeNoteAt (p.x); note >= 0)
  3873. hint.value = noteValue (note);
  3874. return hint;
  3875. }
  3876. if (mpeStacked && velocityArea().contains (p) && mpeLaneAt (p) != 0) // round 190jd: Live 12.4's MPE tab gestures
  3877. {
  3878. 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")
  3879. : 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");
  3880. if (mpeGhost.x >= 0.0f)
  3881. hint.value = mpeGhostText;
  3882. else if (const auto note = mpeNoteAt (p.x); note >= 0)
  3883. hint.value = noteValue (note);
  3884. return hint;
  3885. }
  3886. if (velocityArea().contains (p) && mpeLaneAt (p) != 0)
  3887. {
  3888. 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");
  3889. if (const auto note = mpeNoteAt (p.x); note >= 0)
  3890. hint.value = noteValue (note);
  3891. return hint;
  3892. }
  3893. if (velocityArea().contains (p))
  3894. {
  3895. 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",
  3896. { laneName() });
  3897. if (h.note >= 0)
  3898. hint.value = noteValue (h.note);
  3899. return hint;
  3900. }
  3901. if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth)
  3902. {
  3903. 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");
  3904. return hint;
  3905. }
  3906. if (! gridArea().contains (p))
  3907. return hint;
  3908. if (h.stretch)
  3909. {
  3910. hint.text = tr ("Stretch handle: [LMB] drag stretches or squeezes the selected notes in time (from the selection's start) [Alt] no snap");
  3911. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  3912. return hint;
  3913. }
  3914. if (h.note < 0 && h.ghost >= 0)
  3915. {
  3916. const auto ghostChannel = notes[(std::size_t) h.ghost].channel;
  3917. const auto name = ghostChannel >= 0 && ghostChannel < (int) song.channels.size()
  3918. ? juce::String::fromUTF8 (song.channels[(std::size_t) ghostChannel].name.c_str())
  3919. : juce::String();
  3920. hint.text = editGhosts ? tr ("Ghost note of {0} (editable): [LMB] edit it (switches to {0}) [RMB] deletes it [Ctrl][Alt][V] read-only ghosts",
  3921. { name })
  3922. : tr ("Ghost note of {0}: double [RMB] edits that channel [Alt][V] hides ghost notes [Ctrl][Alt][V] makes them editable",
  3923. { name });
  3924. hint.value = keyName (notes[(std::size_t) h.ghost].key);
  3925. return hint;
  3926. }
  3927. if (mpeStacked && (mpePitchPointAt (p).first >= 0 || (h.note >= 0 && isSelected (h.note)))) // round 190jd: Live's pitch on the notes
  3928. {
  3929. 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");
  3930. hint.value = h.note >= 0 ? noteValue (h.note) : keyName (h.key);
  3931. return hint;
  3932. }
  3933. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  3934. hint.text = actionHint (gesture::leftAction (tools.getTool(), targetAt (h), m, false), false);
  3935. hint.value = h.note >= 0 ? noteValue (h.note) : keyName (h.key);
  3936. return hint;
  3937. }
  3938. void PianoRollComponent::mouseDoubleClick (const juce::MouseEvent& e)
  3939. {
  3940. const LaneScope laneScope (*this, stackedLaneAt (e.getPosition())); // (round 190on)
  3941. if (velocityArea().contains (e.getPosition()) && mpeDoubleClick (e))
  3942. return;
  3943. if (mpeStacked && gridArea().contains (e.getPosition()) && mpePitchDoubleClick (e)) // round 190jd
  3944. return;
  3945. if (! gridArea().contains (e.getPosition()) || e.mods.isRightButtonDown() || flmods::ctrl (e.mods))
  3946. return;
  3947. // the first click of this double click created the note: that was drawing, not opening it
  3948. if (juce::Time::getMillisecondCounter() - createdAt < 800)
  3949. return;
  3950. bool edge = false;
  3951. const auto hit = noteAt (e.x, e.y, edge);
  3952. if (hit < 0)
  3953. return;
  3954. const auto indices = isSelected (hit) ? selection : std::vector<int> { hit };
  3955. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) hit];
  3956. const auto area = juce::Rectangle<int> ((int) tickToX ((double) n.start), keyToY (n.key), juce::jmax (8, (int) (n.length * pixelsPerTick)), rowHeight);
  3957. showNoteInspector (engine, indices, hit, localAreaToGlobal (area));
  3958. }
  3959. std::unique_ptr<juce::Component> PianoRollComponent::makeNoteInspectorForSnapshot (bool singleNote)
  3960. {
  3961. if (selection.empty())
  3962. selectAll();
  3963. if (selection.empty())
  3964. return nullptr;
  3965. return makeNoteInspector (engine, singleNote ? std::vector<int> { selection.front() } : selection, selection.front());
  3966. }
  3967. int PianoRollComponent::liveVelocityHoverForSnapshot (bool dragging)
  3968. {
  3969. setDocked (true);
  3970. velocityHeight = defaultVelocityHeight; // (the lane enlarged by its divider, as in capture 190mf B2)
  3971. liveNoteColour = juce::Colour (0xff3fb7c9);
  3972. rowHeight = 18;
  3973. pixelsPerTick = 64.0 / ticksPerStep;
  3974. resized();
  3975. scrollToNotes (false);
  3976. const auto notes = channelNotes();
  3977. if (notes.empty())
  3978. return -1;
  3979. const auto pick = notes[juce::jmin ((std::size_t) 1, notes.size() - 1)]; // (the second note: clear of the lane's left edge)
  3980. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) pick];
  3981. const auto lane = velocityArea();
  3982. const auto at = juce::Point<int> ((int) tickToX ((double) n.start), lane.getBottom() - 2 - juce::roundToInt ((float) (lane.getHeight() - 8) * n.velocity));
  3983. lastMouse = at;
  3984. updateHover (at, {});
  3985. if (dragging)
  3986. {
  3987. selection = { pick };
  3988. drag = Drag::velocity;
  3989. }
  3990. repaint();
  3991. return juce::roundToInt (n.velocity * 127.0f);
  3992. }
  3993. ui::Hint PianoRollComponent::hoverForSnapshot()
  3994. {
  3995. rowHeight = 18;
  3996. pixelsPerTick = 64.0 / ticksPerStep;
  3997. scrollToNotes (false);
  3998. const auto notes = channelNotes();
  3999. if (notes.empty())
  4000. return {};
  4001. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) notes.front()];
  4002. const auto at = juce::Point<int> ((int) tickToX ((double) (n.start + n.length)) - 2, keyToY (n.key) + rowHeight / 2);
  4003. updateHover (at, {});
  4004. return hintAt (at);
  4005. }
  4006. // --- tools ---------------------------------------------------------------------------
  4007. void PianoRollComponent::cutWithKnife (juce::Point<int> from, juce::Point<int> to, bool snapOn)
  4008. {
  4009. const auto& notes = currentPattern (engine.getSong()).notes;
  4010. std::vector<std::pair<int, std::int64_t>> cuts;
  4011. if (from.getDistanceFrom (to) < 3)
  4012. {
  4013. // a click: cuts the note under the cursor
  4014. bool edge = false;
  4015. if (const auto hit = noteAt (from.x, from.y, edge); hit >= 0)
  4016. cuts.push_back ({ hit, snap (xToTick (from.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn) });
  4017. }
  4018. else
  4019. {
  4020. // a line: every note row it crosses is cut where the line passes
  4021. const auto top = juce::jmin (from.y, to.y), bottom = juce::jmax (from.y, to.y);
  4022. for (int i = 0; i < (int) notes.size(); ++i)
  4023. {
  4024. const auto& n = notes[(std::size_t) i];
  4025. if (! edits (n))
  4026. continue;
  4027. const auto rowY = keyToY (n.key) + rowHeight / 2;
  4028. if (rowY < top - rowHeight / 2 || rowY > bottom + rowHeight / 2)
  4029. continue;
  4030. const auto y = juce::jlimit (top, bottom, rowY);
  4031. 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);
  4032. const auto tick = snap (xToTick ((int) std::round (x)) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn);
  4033. if (tick > n.start && tick < n.start + n.length)
  4034. cuts.push_back ({ i, tick });
  4035. }
  4036. }
  4037. if (cuts.empty())
  4038. return;
  4039. setSelection ({});
  4040. editNotes ([&cuts] (Pattern& p) {
  4041. for (auto [index, tick] : cuts)
  4042. noteedit::split (p, index, tick);
  4043. });
  4044. sortNotes();
  4045. }
  4046. void PianoRollComponent::zoomToTicks (double from, double to)
  4047. {
  4048. if (to - from < 1.0)
  4049. return;
  4050. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, gridArea().getWidth() / (to - from));
  4051. scrollTicks = juce::jmax (0.0, from);
  4052. updateScrollBars();
  4053. repaint();
  4054. }
  4055. void PianoRollComponent::zoomIn (int anchorX)
  4056. {
  4057. const auto anchor = xToTick (anchorX);
  4058. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * 2.0);
  4059. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  4060. updateScrollBars();
  4061. repaint();
  4062. }
  4063. void PianoRollComponent::zoomOut (int anchorX)
  4064. {
  4065. const auto anchor = xToTick (anchorX);
  4066. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick / 2.0);
  4067. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  4068. updateScrollBars();
  4069. repaint();
  4070. }
  4071. void PianoRollComponent::seekAt (int x, bool snapOn)
  4072. {
  4073. const auto& song = engine.getSong();
  4074. const auto tick = snapOn ? (double) snap (xToTick (x), true) : xToTick (x);
  4075. const auto target = transportedit::patternSeekTarget (song, song.currentPattern, tick, engine.getTransport().positionTicks.load());
  4076. if (target < 0.0)
  4077. {
  4078. // Song mode and no clip of this pattern: play the pattern on its own from there
  4079. engine.editSong ([] (Song& s) { s.mode = PlayMode::pattern; }, false);
  4080. engine.seek (juce::jmax (0.0, tick));
  4081. EditorGlobals::get().markSeek ((std::int64_t) juce::jmax (0.0, tick), false); // FL: Stop goes back here (issue #169)
  4082. return;
  4083. }
  4084. engine.seek (target);
  4085. EditorGlobals::get().markSeek ((std::int64_t) target, song.mode == PlayMode::song);
  4086. }
  4087. void PianoRollComponent::listenAt (int x)
  4088. {
  4089. // plays the channel's notes that sound at the tick under the mouse
  4090. const auto tick = (std::int64_t) xToTick (x);
  4091. const auto& notes = currentPattern (engine.getSong()).notes;
  4092. const auto channel = engine.getSelectedChannel();
  4093. std::vector<int> keys;
  4094. std::vector<float> velocities;
  4095. for (const auto& n : notes)
  4096. if (n.channel == channel && ! n.muted && n.start <= tick && n.start + n.length > tick
  4097. && std::find (keys.begin(), keys.end(), n.key) == keys.end())
  4098. {
  4099. keys.push_back (n.key);
  4100. velocities.push_back (n.velocity);
  4101. }
  4102. for (auto k : listenKeys)
  4103. if (std::find (keys.begin(), keys.end(), k) == keys.end())
  4104. listenNotes.release (listenChannel, k);
  4105. if (channel != listenChannel)
  4106. listenNotes.releaseAll();
  4107. for (std::size_t i = 0; i < keys.size(); ++i)
  4108. if (! listenNotes.isHeld (channel, keys[i]))
  4109. listenNotes.press (channel, keys[i], velocities[i]);
  4110. listenKeys = keys;
  4111. listenChannel = channel;
  4112. }
  4113. void PianoRollComponent::stopListening()
  4114. {
  4115. listenNotes.releaseAll();
  4116. listenKeys.clear();
  4117. }
  4118. void PianoRollComponent::refreshChannelBox()
  4119. {
  4120. const auto& song = engine.getSong();
  4121. std::vector<bool> hasNotes (song.channels.size(), false);
  4122. for (const auto& n : currentPattern (song).notes)
  4123. if (n.channel >= 0 && n.channel < (int) hasNotes.size())
  4124. hasNotes[(std::size_t) n.channel] = true;
  4125. juce::StringArray names;
  4126. names.add (tr ("All")); // (issue #12: every channel's notes; drawn bold)
  4127. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4128. names.add ((hasNotes[c] ? juce::String::fromUTF8 ("\xe2\x97\x8f ") : juce::String (" ")) + juce::String::fromUTF8 (song.channels[c].name.c_str()));
  4129. // only rebuilds when something changed (rebuilding closes an open menu)
  4130. bool same = channelBox.getNumItems() == names.size();
  4131. for (int i = 0; same && i < names.size(); ++i)
  4132. same = channelBox.getItemText (i) == names[i];
  4133. if (! same)
  4134. {
  4135. // the bold "All" at the top, as a custom item (a ComboBox item has no font of its own)
  4136. struct BoldItem final : juce::PopupMenu::CustomComponent
  4137. {
  4138. explicit BoldItem (juce::String t) : text (std::move (t)) {}
  4139. void getIdealSize (int& w, int& h) override
  4140. {
  4141. w = 160;
  4142. h = 24;
  4143. }
  4144. void paint (juce::Graphics& g) override
  4145. {
  4146. if (isItemHighlighted())
  4147. {
  4148. g.setColour (theme::colour::accent.withAlpha (0.35f));
  4149. g.fillRect (getLocalBounds());
  4150. }
  4151. g.setColour (theme::colour::textPrimary);
  4152. g.setFont (theme::font (theme::type::body, true));
  4153. g.drawText (text, getLocalBounds().withTrimmedLeft (12), juce::Justification::centredLeft, true);
  4154. }
  4155. juce::String text;
  4156. };
  4157. channelBox.clear (juce::dontSendNotification);
  4158. juce::PopupMenu::Item all (names[0]);
  4159. all.itemID = allChannelsId;
  4160. all.customComponent = new BoldItem (names[0]);
  4161. channelBox.getRootMenu()->addItem (std::move (all));
  4162. channelBox.getRootMenu()->addSeparator();
  4163. for (int i = 1; i < names.size(); ++i)
  4164. channelBox.addItem (names[i], i);
  4165. }
  4166. channelBox.setSelectedId (allChannels ? allChannelsId : engine.getSelectedChannel() + 1, juce::dontSendNotification);
  4167. }
  4168. void PianoRollComponent::setAllChannels (bool on)
  4169. {
  4170. if (allChannels == on)
  4171. return;
  4172. allChannels = on;
  4173. selection.clear();
  4174. stopListening();
  4175. refreshChannelBox();
  4176. repaint();
  4177. }
  4178. void PianoRollComponent::stepChannel (int direction, bool withNotesOnly)
  4179. {
  4180. const auto& song = engine.getSong();
  4181. const auto count = (int) song.channels.size();
  4182. if (count == 0)
  4183. return;
  4184. std::vector<bool> hasNotes ((std::size_t) count, false);
  4185. for (const auto& n : currentPattern (song).notes)
  4186. if (n.channel >= 0 && n.channel < count)
  4187. hasNotes[(std::size_t) n.channel] = true;
  4188. auto channel = engine.getSelectedChannel();
  4189. for (int step = 0; step < count; ++step)
  4190. {
  4191. channel += direction;
  4192. if (channel < 0 || channel >= count)
  4193. return; // stops at the ends
  4194. if (! withNotesOnly || hasNotes[(std::size_t) channel])
  4195. {
  4196. engine.setSelectedChannel (channel);
  4197. return;
  4198. }
  4199. }
  4200. }
  4201. void PianoRollComponent::runOperation (const std::function<std::vector<int> (Pattern&, const std::vector<int>&)>& op)
  4202. {
  4203. const auto target = selectionOrAll();
  4204. if (target.empty())
  4205. return;
  4206. const auto hadSelection = ! selection.empty();
  4207. std::vector<int> result;
  4208. editNotes ([&] (Pattern& p) { result = op (p, target); });
  4209. setSelection (hadSelection ? result : std::vector<int> {});
  4210. sortNotes();
  4211. }
  4212. void PianoRollComponent::showMoreMenu()
  4213. {
  4214. moreMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&moreButton));
  4215. }
  4216. juce::PopupMenu PianoRollComponent::moreMenu()
  4217. {
  4218. const auto grid = gridTicks();
  4219. const auto bar = engine.getSong().barTicks();
  4220. juce::PopupMenu menu;
  4221. menu.addSubMenu (theme::mnemonic (tr ("File"), 'F'), fileMenu());
  4222. menu.addSubMenu (theme::mnemonic (tr ("Edit"), 'E'), editMenu());
  4223. menu.addSubMenu (theme::mnemonic (tr ("View"), 'V'), viewMenu());
  4224. menu.addSubMenu (tr ("Time markers"), markersMenu());
  4225. menu.addSeparator();
  4226. menu.addSectionHeader (tr ("Note operations (selection, or all notes)"));
  4227. 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); }); });
  4228. 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> {}; }); });
  4229. menu.addItem (tr ("Make legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  4230. 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; }); });
  4231. menu.addItem (tr ("Quantise starts") + keyText ("pianoRoll.quantizeStarts"), [this] { quantizeOperation (0); });
  4232. menu.addItem (tr ("Quantise starts 50% (halfway to the grid)") + keyText ("pianoRoll.quantizeHalf"), [this] { quantizeOperation (2); });
  4233. menu.addItem (tr ("Quantise starts and lengths") + keyText ("pianoRoll.quickQuantize"), [this] { quantizeOperation (1); });
  4234. 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; }); });
  4235. 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; }); });
  4236. menu.addSeparator();
  4237. menu.addSubMenu (theme::mnemonic (tr ("Tools"), 'T'), toolsMenu());
  4238. menu.addSubMenu (theme::mnemonic (tr ("Select"), 'S'), selectMenu());
  4239. {
  4240. juce::PopupMenu zoom;
  4241. zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("pianoRoll.zoomIn"); });
  4242. zoom.addItem (tr ("Zoom out") + "\tPageDown", [this] { runAction ("pianoRoll.zoomOut"); });
  4243. zoom.addItem (tr ("Zoom: one bar") + "\tShift+1", [this] { runAction ("pianoRoll.zoom1"); });
  4244. zoom.addItem (tr ("Zoom: four bars") + "\tShift+2", [this] { runAction ("pianoRoll.zoom2"); });
  4245. zoom.addItem (tr ("Zoom: sixteen bars") + "\tShift+3", [this] { runAction ("pianoRoll.zoom3"); });
  4246. zoom.addItem (tr ("Zoom to show everything") + "\tShift+4", [this] { runAction ("pianoRoll.zoomAll"); });
  4247. zoom.addItem (tr ("Zoom to the selection") + "\tShift+5", [this] { runAction ("pianoRoll.zoomSelection"); });
  4248. zoom.addItem (tr ("Centre the view on the playhead") + "\tShift+0", [this] { runAction ("pianoRoll.centrePlayhead"); });
  4249. zoom.addSeparator();
  4250. zoom.addItem (tr ("Taller keys") + "\tCtrl+Alt+Wheel", [this] { rowHeight = juce::jmin (gesture::maxKeyHeight, rowHeight + 2); updateScrollBars(); repaint(); });
  4251. zoom.addItem (tr ("Shorter keys"), [this] { rowHeight = juce::jmax (gesture::minKeyHeight, rowHeight - 2); updateScrollBars(); repaint(); });
  4252. menu.addSubMenu (tr ("Zoom"), zoom);
  4253. }
  4254. menu.addSeparator();
  4255. menu.addItem (tr ("Snap notes to the scale") + keyText ("pianoRoll.scaleSnap"), scaleIndex() > 0, scaleSnap, [this] { setScaleSnap (! scaleSnap); });
  4256. menu.addItem (tr ("Fold to the scale (hide the other keys and their notes)"), scaleIndex() > 0, foldToScale,
  4257. [this] { setFoldToScale (! foldToScale); });
  4258. menu.addItem (tr ("Chord stamp: the clicked key is the top note"), true, chordTopDown, [this] { chordTopDown = ! chordTopDown; });
  4259. // the chord stamp's list (round 190j, discussion #10): the toolbar's chord box is hidden in a narrow window, so
  4260. // the stamp is always in this menu too
  4261. menu.addSubMenu (tr ("Chord stamp"), stampMenu(), true, juce::Image(), chordBox.getSelectedId() > 1);
  4262. menu.addItem (tr ("Stamp: none (single notes)") + keyText ("pianoRoll.stampNone"), chordBox.getSelectedId() != 1, false,
  4263. [this] { runAction ("pianoRoll.stampNone"); });
  4264. menu.addItem (tr ("Move the notes onto the scale"), scaleIndex() > 0, false, [this] {
  4265. const auto root = scaleRoot(), scale = scaleIndex();
  4266. runOperation ([root, scale] (Pattern& p, const std::vector<int>& t) { notetools::snapNotesToScale (p, t, root, scale); return t; });
  4267. });
  4268. menu.addSeparator();
  4269. menu.addItem (tr ("Note names on every key"), true, notenames::everyKey.load(), [this] {
  4270. notenames::everyKey.store (! notenames::everyKey.load());
  4271. if (onNoteNamesChanged != nullptr)
  4272. onNoteNamesChanged(); // (saved with the settings)
  4273. repaint();
  4274. });
  4275. menu.addItem (tr ("Resize notes from the left edge too") + "\tCtrl+Alt+Home", true, resizeFromLeft, [this] { resizeFromLeft = ! resizeFromLeft; });
  4276. // issue #183: FL keeps placed and dragged notes silent while the song / pattern plays; this hears them anyway
  4277. menu.addItem (tr ("Preview notes while playing"), true, previewWhilePlaying, [] {
  4278. previewWhilePlaying = ! previewWhilePlaying;
  4279. if (EditorGlobals::get().onOptionsChanged)
  4280. EditorGlobals::get().onOptionsChanged(); // (saved with the UI settings)
  4281. });
  4282. menu.addItem (tr ("Show ghost notes") + "\tAlt+V", true, showGhosts,
  4283. [this] { ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync); });
  4284. menu.addItem (tr ("Ghost notes are editable") + "\tCtrl+Alt+V", true, editGhosts, [this] {
  4285. editGhosts = ! editGhosts;
  4286. if (editGhosts && ! showGhosts)
  4287. ghostButton.setToggleState (true, juce::sendNotificationSync);
  4288. repaint();
  4289. });
  4290. menu.addSubMenu (tr ("Ghost channels"), ghostChannelsMenu());
  4291. menu.addSeparator();
  4292. menu.addSubMenu ("MIDI", midiMenu());
  4293. return menu;
  4294. }
  4295. bool PianoRollComponent::ghostShown (int channel) const noexcept
  4296. {
  4297. const auto& channels = engine.getSong().channels;
  4298. return channel < 0 || channel >= (int) channels.size() || ! channels[(std::size_t) channel].ghostHidden;
  4299. }
  4300. void PianoRollComponent::setGhostChannels (const std::function<bool (int channel, bool shown)>& show)
  4301. {
  4302. engine.editSong ([&show] (Song& s) {
  4303. for (int c = 0; c < (int) s.channels.size(); ++c)
  4304. s.channels[(std::size_t) c].ghostHidden = ! show (c, ! s.channels[(std::size_t) c].ghostHidden);
  4305. }, false);
  4306. engine.markModified();
  4307. if (! showGhosts) // choosing what to ghost shows the ghosts
  4308. ghostButton.setToggleState (true, juce::sendNotificationSync);
  4309. repaint();
  4310. }
  4311. juce::PopupMenu PianoRollComponent::ghostChannelsMenu()
  4312. {
  4313. // FL 2026's ghost notes button menu (round 166d [SHOT], right-click on it): "Ghost channels", All, None, then every
  4314. // channel with a check mark (the edited one in bold); a click toggles that channel's ghost notes
  4315. struct ChannelItem final : juce::PopupMenu::CustomComponent
  4316. {
  4317. ChannelItem (juce::String t, bool tick, bool bold) : text (std::move (t)), ticked (tick), strong (bold) {}
  4318. void getIdealSize (int& w, int& h) override
  4319. {
  4320. w = juce::jlimit (140, 420, 40 + juce::GlyphArrangement::getStringWidthInt (theme::font (theme::type::body, true), text));
  4321. h = 22;
  4322. }
  4323. void paint (juce::Graphics& g) override
  4324. {
  4325. if (isItemHighlighted())
  4326. {
  4327. g.setColour (theme::colour::accent.withAlpha (0.35f));
  4328. g.fillRect (getLocalBounds());
  4329. }
  4330. auto area = getLocalBounds();
  4331. const auto tickArea = area.removeFromLeft (24).toFloat();
  4332. if (ticked)
  4333. icons::draw (g, Icon::check, tickArea.withSizeKeepingCentre (12.0f, 12.0f), theme::colour::textPrimary);
  4334. g.setColour (ticked ? theme::colour::textPrimary : theme::colour::textSecondary);
  4335. g.setFont (theme::font (theme::type::body, strong));
  4336. g.drawText (text, area.withTrimmedRight (8), juce::Justification::centredLeft, true);
  4337. }
  4338. juce::String text;
  4339. bool ticked, strong;
  4340. };
  4341. juce::PopupMenu menu;
  4342. menu.addSectionHeader (tr ("Ghost channels"));
  4343. menu.addItem (tr ("All"), [this] { setGhostChannels ([] (int, bool) { return true; }); });
  4344. menu.addItem (tr ("None"), [this] { setGhostChannels ([] (int, bool) { return false; }); });
  4345. menu.addSeparator();
  4346. const auto& song = engine.getSong();
  4347. const auto current = engine.getSelectedChannel();
  4348. for (int c = 0; c < (int) song.channels.size(); ++c)
  4349. {
  4350. const auto name = juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str());
  4351. juce::PopupMenu::Item item (name);
  4352. item.customComponent = new ChannelItem (name, ghostShown (c), c == current);
  4353. item.action = [this, c] { setGhostChannels ([c] (int k, bool shown) { return k == c ? ! shown : shown; }); };
  4354. menu.addItem (std::move (item));
  4355. }
  4356. return menu;
  4357. }
  4358. void PianoRollComponent::openMidiTools()
  4359. {
  4360. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  4361. auto panel = std::make_unique<MidiToolsPanel> (
  4362. engine,
  4363. [safe] {
  4364. MidiToolsPanel::Target t;
  4365. if (safe != nullptr)
  4366. {
  4367. t.pattern = safe->engine.getSong().currentPattern;
  4368. t.indices = safe->midiToolNotes (t.selected);
  4369. t.grid = safe->midiToolGrid();
  4370. t.from = safe->timeSelectionFrom(); // round 190fm: Generate writes into the time selection
  4371. t.to = safe->timeSelectionTo();
  4372. t.channel = safe->engine.getSelectedChannel();
  4373. }
  4374. return t;
  4375. },
  4376. [safe] (const std::vector<int>& indices) {
  4377. if (safe != nullptr)
  4378. safe->selectMidiToolResult (indices);
  4379. });
  4380. struct Padded final : juce::Component // (the panel with a margin, on the window's background)
  4381. {
  4382. explicit Padded (std::unique_ptr<MidiToolsPanel> p) : panel (std::move (p))
  4383. {
  4384. addAndMakeVisible (*panel);
  4385. setSize (MidiToolsPanel::panelWidth + 16, MidiToolsPanel::panelHeight + 12);
  4386. }
  4387. void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
  4388. void resized() override { panel->setBounds (getLocalBounds().reduced (8, 6)); }
  4389. std::unique_ptr<MidiToolsPanel> panel;
  4390. };
  4391. openToolWindow (std::make_unique<Padded> (std::move (panel)), tr ("MIDI Tools"), "midiTools");
  4392. }
  4393. void PianoRollComponent::openChordHelper()
  4394. {
  4395. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  4396. const auto look = ChordHelperPanel::lookNow();
  4397. auto panel = std::make_unique<ChordHelperPanel> (
  4398. engine,
  4399. [safe] {
  4400. ChordHelperPanel::Target t;
  4401. if (safe != nullptr)
  4402. {
  4403. t.pattern = safe->engine.getSong().currentPattern;
  4404. t.channel = safe->engine.getSelectedChannel();
  4405. t.selected = safe->selection;
  4406. }
  4407. return t;
  4408. },
  4409. [safe] (const std::vector<int>& indices) {
  4410. if (safe != nullptr)
  4411. safe->selectOwnNewNotes (indices);
  4412. },
  4413. look);
  4414. auto* raw = panel.get();
  4415. openToolWindow (std::move (panel), tr ("Chord helper"), "chordHelper");
  4416. chordHelper = raw;
  4417. }
  4418. void PianoRollComponent::selectOwnNewNotes (std::vector<int> indices)
  4419. {
  4420. const auto& song = engine.getSong();
  4421. if (song.currentPattern == knownPattern && engine.getSelectedChannel() == knownChannel)
  4422. knownNoteCount = currentPattern (song).notes.size();
  4423. setSelection (std::move (indices));
  4424. chordPanelSelection = selection; // (the helper already read it)
  4425. }
  4426. ChordHelperPanel* PianoRollComponent::chordHelperForTests() const noexcept { return dynamic_cast<ChordHelperPanel*> (chordHelper.getComponent()); }
  4427. juce::PopupMenu PianoRollComponent::toolsMenu()
  4428. {
  4429. // FL's piano roll Tools menu (REA round 143, EXEC capture): its groups and keys, in its order
  4430. juce::PopupMenu menu;
  4431. const auto grid = gridTicks();
  4432. auto tool = [this, &menu] (NoteTool t, const char* key) {
  4433. menu.addItem (tr (noteToolTitle (t)) + "..." + (key != nullptr ? juce::String ("\t") + key : juce::String()), [this, t] { openNoteTool (t); });
  4434. };
  4435. menu.addSectionHeader (tr ("Built-in"));
  4436. tool (NoteTool::riffMachine, "Alt+E");
  4437. menu.addItem (tr ("Generate chord progression...") + "\tAlt+P", [this] { openNoteTool (NoteTool::chordProgression); });
  4438. menu.addSeparator();
  4439. menu.addItem (tr ("Quick legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  4440. tool (NoteTool::articulate, "Alt+L");
  4441. menu.addSeparator();
  4442. menu.addItem (tr ("Quick quantize") + keyText ("pianoRoll.quickQuantize"), [this] { quantizeOperation (1); });
  4443. menu.addItem (tr ("Quick quantize start times") + keyText ("pianoRoll.quantizeStarts"), [this] { quantizeOperation (0); });
  4444. menu.addItem (tr ("Quick quantize 50% (halfway to the grid)") + keyText ("pianoRoll.quantizeHalf"), [this] { quantizeOperation (2); });
  4445. tool (NoteTool::quantize, "Alt+Q");
  4446. menu.addSeparator();
  4447. menu.addItem (tr ("Quick chop") + "\tCtrl+U", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); }); });
  4448. tool (NoteTool::chop, "Alt+U");
  4449. menu.addSeparator();
  4450. menu.addItem (tr ("Glue notes") + "\tCtrl+G", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; }); });
  4451. menu.addSeparator();
  4452. tool (NoteTool::arpeggiate, "Alt+A");
  4453. tool (NoteTool::strum, "Alt+S");
  4454. tool (NoteTool::flam, "Alt+F");
  4455. tool (NoteTool::claw, "Alt+W");
  4456. tool (NoteTool::limit, "Alt+K");
  4457. tool (NoteTool::flip, "Alt+Y");
  4458. tool (NoteTool::randomise, "Alt+R");
  4459. menu.addSeparator();
  4460. tool (NoteTool::scaleLevels, "Alt+X");
  4461. tool (NoteTool::lfo, "Alt+O");
  4462. // FL's second column ("Scripts": Python tools shipped with FL); LYNX has its own built-in versions
  4463. menu.addSectionHeader (tr ("More tools"));
  4464. tool (NoteTool::euclidean, nullptr);
  4465. tool (NoteTool::humanize, nullptr);
  4466. tool (NoteTool::noteRepeat, nullptr);
  4467. // Live 12's MIDI Transformations as a docked-style panel (round 190s; LYNX addition beside FL's tools above)
  4468. menu.addItem (tr ("MIDI Tools") + "...", [this] { openMidiTools(); });
  4469. // LYNX's Chord helper (round 190mc, discussion #105): modal interchange from the selected chord
  4470. menu.addItem (tr ("Chord helper") + "..." + keyText ("pianoRoll.chordHelper"), [this] { openChordHelper(); });
  4471. {
  4472. juce::PopupMenu velocity;
  4473. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  4474. const auto& song = engine.getSong();
  4475. setSelection (pick (song.activePattern(), channelNotes()));
  4476. };
  4477. velocity.addItem (tr ("Loudest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, true); }); });
  4478. velocity.addItem (tr ("Quietest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, false); }); });
  4479. velocity.addSeparator();
  4480. 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 } })
  4481. velocity.addItem (tr ("Velocity {0}", { juce::String (label) }), [choose, lo = lo, hi = hi] {
  4482. choose ([lo, hi] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, lo, hi); });
  4483. });
  4484. if (! selection.empty())
  4485. {
  4486. const auto& notes = engine.getSong().activePattern().notes;
  4487. const auto v = selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].velocity : 0.0f;
  4488. velocity.addSeparator();
  4489. velocity.addItem (tr ("Same velocity as the selected note ({0}%)", { juce::String (juce::roundToInt (v * 100.0f)) }), [choose, v] {
  4490. choose ([v] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, v - 0.005f, v + 0.005f); });
  4491. });
  4492. }
  4493. menu.addSubMenu (tr ("Select by velocity"), velocity);
  4494. }
  4495. {
  4496. // Live 12's note Chance (round 187c, LYNX additions): probability groups, a reset and a new draw for the project
  4497. juce::PopupMenu chance;
  4498. const auto several = selection.size() > 1;
  4499. chance.addItem (tr ("Group the selected notes: play all"), several, false, [this] {
  4500. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::groupChance (p, t, false); return t; });
  4501. });
  4502. chance.addItem (tr ("Group the selected notes: play one"), several, false, [this] {
  4503. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::groupChance (p, t, true); return t; });
  4504. });
  4505. chance.addItem (tr ("Ungroup the chance of the selected notes"), [this] {
  4506. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::ungroupChance (p, t); return t; });
  4507. });
  4508. chance.addSeparator();
  4509. chance.addItem (tr ("Reset chance and velocity range"), [this] {
  4510. runOperation ([] (Pattern& p, const std::vector<int>& t) {
  4511. notetools::ungroupChance (p, t);
  4512. for (auto i : t)
  4513. if (i >= 0 && i < (int) p.notes.size())
  4514. p.notes[(std::size_t) i].chance = 1.0f, p.notes[(std::size_t) i].velocityRange = 0.0f;
  4515. return t;
  4516. });
  4517. });
  4518. chance.addItem (tr ("New chance seed (draws again for the whole project)"), [this] {
  4519. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt64();
  4520. engine.editSong ([seed] (Song& s) { s.chanceSeed = seed == 0 ? 1u : seed; });
  4521. repaint();
  4522. });
  4523. chance.addSeparator();
  4524. chance.addItem (tr ("Show the chance lane"), true, laneIsChance(), [this] {
  4525. laneBox.setSelectedId (laneChance);
  4526. });
  4527. menu.addSubMenu (tr ("Chance (LYNX)"), chance);
  4528. }
  4529. menu.addSeparator();
  4530. menu.addItem (tr ("Edit events..."), [this] {
  4531. openEventEditor (engine, { AutomationTargetKind::channelVolume, engine.getSelectedChannel() });
  4532. });
  4533. // FL's second column: "Scripts", the Piano roll's Python scripts (round 190as)
  4534. menu.addColumnBreak();
  4535. menu.addSectionHeader (tr ("Scripts"));
  4536. addScriptItems (menu);
  4537. return menu;
  4538. }
  4539. void PianoRollComponent::openNoteTool (NoteTool tool)
  4540. {
  4541. const auto target = selectionOrAll();
  4542. if (target.empty() && ! noteToolGenerates (tool))
  4543. return;
  4544. showNoteTool (engine, tool, target, gridTicks(), [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  4545. if (safe != nullptr)
  4546. safe->setSelection ({});
  4547. });
  4548. }
  4549. void PianoRollComponent::zoomAroundCentre (double factor)
  4550. {
  4551. const auto grid = gridArea();
  4552. const auto centre = xToTick (grid.getCentreX());
  4553. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * factor);
  4554. scrollTicks = juce::jmax (0.0, centre - (grid.getCentreX() - keyboardWidth) / pixelsPerTick);
  4555. updateScrollBars();
  4556. repaint();
  4557. }
  4558. void PianoRollComponent::zoomToBars (int bars)
  4559. {
  4560. const auto bar = (double) engine.getSong().barTicks();
  4561. const auto from = std::floor (scrollTicks / bar) * bar;
  4562. zoomToTicks (from, from + bars * bar);
  4563. }
  4564. void PianoRollComponent::zoomAll()
  4565. {
  4566. const auto& song = engine.getSong();
  4567. zoomToTicks (0.0, (double) currentPattern (song).effectiveLength (song.meter()));
  4568. }
  4569. void PianoRollComponent::zoomToSelection()
  4570. {
  4571. const auto target = selectionOrAll();
  4572. if (target.empty())
  4573. return zoomAll();
  4574. const auto& notes = currentPattern (engine.getSong()).notes;
  4575. std::int64_t from = INT64_MAX, to = 0;
  4576. int low = 127, high = 0;
  4577. for (auto i : target)
  4578. {
  4579. const auto& n = notes[(std::size_t) i];
  4580. from = juce::jmin (from, n.start);
  4581. to = juce::jmax (to, n.start + n.length);
  4582. low = juce::jmin (low, n.key);
  4583. high = juce::jmax (high, n.key);
  4584. }
  4585. const auto margin = (double) ticksPerStep;
  4586. zoomToTicks (juce::jmax (0.0, (double) from - margin), (double) to + margin);
  4587. scrollY = juce::jmax (0, rowFor ((low + high) / 2) * rowHeight - gridArea().getHeight() / 2);
  4588. updateScrollBars();
  4589. repaint();
  4590. }
  4591. void PianoRollComponent::centreOnPlayhead()
  4592. {
  4593. const auto& song = engine.getSong();
  4594. const auto length = (double) juce::jmax<std::int64_t> (1, currentPattern (song).effectiveLength (song.meter()));
  4595. auto tick = transportedit::patternPlayhead (song, song.currentPattern, engine.getTransport().positionTicks.load());
  4596. if (tick < 0.0)
  4597. tick = std::fmod (engine.getTransport().positionTicks.load(), length);
  4598. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick / 2.0);
  4599. updateScrollBars();
  4600. repaint();
  4601. }
  4602. void PianoRollComponent::centreOnTick (double tick, double at)
  4603. {
  4604. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick * at);
  4605. updateScrollBars();
  4606. repaint();
  4607. }
  4608. void PianoRollComponent::ColourSwatch::paintButton (juce::Graphics& g, bool over, bool down)
  4609. {
  4610. auto r = getLocalBounds().toFloat().reduced (3.0f);
  4611. g.setColour (theme::noteGroupColour (colourIndex, 0.85f));
  4612. g.fillRoundedRectangle (r, 3.0f);
  4613. g.setColour (over || down ? theme::colour::textPrimary : theme::colour::bg0.withAlpha (0.7f));
  4614. g.drawRoundedRectangle (r, 3.0f, 1.0f);
  4615. g.setColour (theme::colour::bg0.withAlpha (0.85f));
  4616. g.setFont (theme::font (theme::type::caption, true));
  4617. g.drawText (juce::String (colourIndex + 1), r, juce::Justification::centred, false);
  4618. }
  4619. void PianoRollComponent::colourSelection (int colour)
  4620. {
  4621. const auto target = selection;
  4622. if (target.empty())
  4623. return;
  4624. editNotes ([&] (Pattern& p) { notetools::setColour (p, target, colour); });
  4625. repaint();
  4626. }
  4627. void PianoRollComponent::selectByColour (int colour)
  4628. {
  4629. setSelection (notetools::selectByColour (currentPattern (engine.getSong()), channelNotes(), colour));
  4630. }
  4631. void PianoRollComponent::showColourMenu()
  4632. {
  4633. juce::PopupMenu menu;
  4634. menu.addSectionHeader (tr ("Colour for new notes"));
  4635. for (int c = 0; c < noteColourCount; ++c)
  4636. menu.addColouredItem (c + 1, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, c == noteColour);
  4637. menu.addSeparator();
  4638. menu.addItem (1000, tr ("Colour the selected notes with it") + "\tAlt+C", ! selection.empty());
  4639. {
  4640. juce::PopupMenu colourAs;
  4641. for (int c = 0; c < noteColourCount; ++c)
  4642. colourAs.addColouredItem (2001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, false);
  4643. menu.addSubMenu (tr ("Colour the selected notes"), colourAs, ! selection.empty());
  4644. }
  4645. {
  4646. juce::PopupMenu select;
  4647. const auto& pattern = currentPattern (engine.getSong());
  4648. for (int c = 0; c < noteColourCount; ++c)
  4649. select.addColouredItem (3001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f),
  4650. ! notetools::selectByColour (pattern, channelNotes(), c).empty(), false);
  4651. menu.addSubMenu (tr ("Select by colour") + "\tShift+C", select);
  4652. }
  4653. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&colourButton), [safe = juce::Component::SafePointer (this)] (int id) {
  4654. if (safe == nullptr || id <= 0)
  4655. return;
  4656. if (id <= noteColourCount)
  4657. {
  4658. safe->noteColour = id - 1;
  4659. safe->colourButton.colourIndex = id - 1;
  4660. safe->colourButton.repaint();
  4661. }
  4662. else if (id == 1000)
  4663. safe->colourSelection (safe->noteColour);
  4664. else if (id > 2000 && id <= 2000 + noteColourCount)
  4665. safe->colourSelection (id - 2001);
  4666. else if (id > 3000 && id <= 3000 + noteColourCount)
  4667. safe->selectByColour (id - 3001);
  4668. });
  4669. }
  4670. juce::PopupMenu PianoRollComponent::selectMenu()
  4671. {
  4672. // FL's piano roll Select submenu (its manual): all, invert, odd, random, muted, overlapping, stacked, by colour
  4673. juce::PopupMenu menu;
  4674. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  4675. setSelection (pick (currentPattern (engine.getSong()), channelNotes()));
  4676. };
  4677. menu.addItem (theme::mnemonic (tr ("All"), 'a') + "\tCtrl+A", [this] { selectAll(); });
  4678. menu.addItem (theme::mnemonic (tr ("Invert selection"), 'I') + "\tShift+I", [this] { runAction ("pianoRoll.invertSelection"); });
  4679. menu.addItem (theme::mnemonic (tr ("Deselect"), 'D') + "\tEsc", ! selection.empty(), false, [this] { setSelection ({}); });
  4680. menu.addSeparator();
  4681. // FL's Select items with their keys (round 168g): they add to the selection
  4682. menu.addItem (theme::mnemonic (tr ("Select one at random"), 'r') + keyText ("pianoRoll.selectRandomOne"), [this] { runAction ("pianoRoll.selectRandomOne"); });
  4683. menu.addItem (theme::mnemonic (tr ("Select more at random"), 'r') + keyText ("pianoRoll.selectRandomMore"), [this] { runAction ("pianoRoll.selectRandomMore"); });
  4684. menu.addItem (theme::mnemonic (tr ("Select odd (swung) notes"), 'o') + keyText ("pianoRoll.selectOddSteps"), [this] { runAction ("pianoRoll.selectOddSteps"); });
  4685. menu.addSeparator();
  4686. menu.addItem (tr ("Odd notes (every other one)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOdd (p, t); }); });
  4687. menu.addItem (tr ("Even notes"), [choose] {
  4688. choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::invertSelection (t, notetools::selectOdd (p, t)); });
  4689. });
  4690. menu.addItem (tr ("Random (half of the notes)"), [choose] {
  4691. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
  4692. choose ([seed] (const Pattern& p, const std::vector<int>& t) { return notetools::selectRandom (p, t, 0.5f, seed); });
  4693. });
  4694. menu.addItem (theme::mnemonic (tr ("Muted notes"), 'm'), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectMuted (p, t); }); });
  4695. menu.addItem (tr ("Overlapping notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOverlapping (p, t); }); });
  4696. menu.addItem (tr ("Stacked notes (hidden duplicates)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectStacked (p, t); }); });
  4697. menu.addItem (theme::mnemonic (tr ("Same colour as the selection"), 'c') + "\tShift+C", [this] { runAction ("pianoRoll.selectByColour"); });
  4698. menu.addSeparator();
  4699. menu.addItem (tr ("Group the selected notes") + "\tShift+G", selection.size() > 1, false, [this] { runAction ("pianoRoll.groupNotes"); });
  4700. menu.addItem (tr ("Ungroup the selected notes") + "\tAlt+G", ! selection.empty(), false, [this] { runAction ("pianoRoll.ungroupNotes"); });
  4701. // FL's last Select item, alone after a line (round 190mp, DE-71; capture 190mp A3.4): Magic lasso, no key, off
  4702. menu.addSeparator();
  4703. menu.addItem (tr ("Magic lasso"), true, EditorGlobals::get().pianoRollMagicLasso, [] {
  4704. auto& g = EditorGlobals::get();
  4705. g.pianoRollMagicLasso = ! g.pianoRollMagicLasso;
  4706. if (g.onOptionsChanged != nullptr)
  4707. g.onOptionsChanged();
  4708. });
  4709. return menu;
  4710. }
  4711. // FL's Magic lasso over the notes (round 190mp, DE-71; core/MagicLasso.h, FL's Playlist rules of round 189g): with the
  4712. // option on, a loop drawn with the mouse (no button) around notes selects them (Shift / a second loop: as FL's decide)
  4713. void PianoRollComponent::feedMagicLasso (juce::Point<int> p, bool buttonDown)
  4714. {
  4715. if (! EditorGlobals::get().pianoRollMagicLasso)
  4716. {
  4717. lassoPath.clear();
  4718. return;
  4719. }
  4720. const auto grid = gridArea();
  4721. const auto at = grid.getConstrainedPoint (p);
  4722. const auto loop = lassoPath.move ({ (double) at.x, (double) at.y }, juce::Time::getMillisecondCounter(), buttonDown || ! grid.contains (p));
  4723. if (loop.empty())
  4724. return;
  4725. const auto& notes = currentPattern (engine.getSong()).notes;
  4726. std::vector<int> enclosed;
  4727. std::vector<bool> enclosedSelected;
  4728. for (const auto i : channelNotes())
  4729. {
  4730. const auto& n = notes[(std::size_t) i];
  4731. const auto r = noteRect (n.start, n.length, n.key);
  4732. if (! r.toNearestInt().intersects (grid))
  4733. continue;
  4734. if (magiclasso::rectInsidePolygon (loop, magiclasso::innerRect ({ (double) r.getX(), (double) r.getY(), (double) r.getRight(), (double) r.getBottom() })))
  4735. {
  4736. enclosed.push_back (i);
  4737. enclosedSelected.push_back (isSelected (i));
  4738. }
  4739. }
  4740. switch (magiclasso::decide (enclosed, juce::ModifierKeys::currentModifiers.isShiftDown(), (int) selection.size(), enclosedSelected))
  4741. {
  4742. case magiclasso::Result::select:
  4743. {
  4744. auto chosen = selection;
  4745. for (const auto i : enclosed)
  4746. if (std::find (chosen.begin(), chosen.end(), i) == chosen.end())
  4747. chosen.push_back (i);
  4748. setSelection (chosen);
  4749. lassoPath.clear();
  4750. break;
  4751. }
  4752. case magiclasso::Result::zoomToSelection:
  4753. {
  4754. std::int64_t from = std::numeric_limits<std::int64_t>::max(), to = 0;
  4755. for (const auto i : selection)
  4756. if (i >= 0 && i < (int) notes.size())
  4757. {
  4758. from = std::min (from, notes[(std::size_t) i].start);
  4759. to = std::max (to, notes[(std::size_t) i].start + notes[(std::size_t) i].length);
  4760. }
  4761. if (to > from)
  4762. zoomToTicks ((double) from, (double) to);
  4763. lassoPath.clear();
  4764. break;
  4765. }
  4766. case magiclasso::Result::nothing:
  4767. break;
  4768. }
  4769. }
  4770. void PianoRollComponent::showKeyMenu (int key)
  4771. {
  4772. const auto channel = engine.getSelectedChannel();
  4773. if (channel < 0 || channel >= (int) engine.getSong().channels.size() || key < 0 || key > 127)
  4774. return;
  4775. const auto& labels = engine.getSong().channels[(std::size_t) channel].keyLabels;
  4776. const auto current = labels.find (key);
  4777. auto setLabels = [this, channel] (std::function<void (std::map<int, std::string>&)> edit) {
  4778. engine.editSong ([channel, edit] (Song& s) {
  4779. if (channel < (int) s.channels.size())
  4780. edit (s.channels[(std::size_t) channel].keyLabels);
  4781. });
  4782. repaint();
  4783. };
  4784. juce::PopupMenu menu;
  4785. menu.addSectionHeader (keyName (key));
  4786. menu.addItem (tr ("Rename this key..."), [key, setLabels, text = current != labels.end() ? current->second : std::string()] {
  4787. auto* window = new juce::AlertWindow (tr ("Key label"), tr ("The name shown on {0} for this channel", { keyName (key) }), juce::MessageBoxIconType::NoIcon);
  4788. window->addTextEditor ("label", juce::String::fromUTF8 (text.c_str()));
  4789. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4790. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4791. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, key, setLabels] (int result) {
  4792. if (result != 1)
  4793. return;
  4794. const auto label = window->getTextEditorContents ("label").trim().toStdString();
  4795. setLabels ([key, label] (std::map<int, std::string>& l) {
  4796. if (label.empty())
  4797. l.erase (key);
  4798. else
  4799. l[key] = label;
  4800. });
  4801. }),
  4802. true);
  4803. });
  4804. menu.addItem (tr ("Remove this key's label"), current != labels.end(), false,
  4805. [setLabels, key] { setLabels ([key] (std::map<int, std::string>& l) { l.erase (key); }); });
  4806. menu.addSeparator();
  4807. menu.addItem (tr ("Label the keys with the General MIDI drum map"), [setLabels] {
  4808. setLabels ([] (std::map<int, std::string>& l) {
  4809. for (int k = 35; k <= 81; ++k)
  4810. if (const auto* name = notetools::generalMidiDrumName (k))
  4811. l[k] = name;
  4812. });
  4813. });
  4814. menu.addItem (tr ("Remove all key labels of this channel"), ! labels.empty(), false,
  4815. [setLabels] { setLabels ([] (std::map<int, std::string>& l) { l.clear(); }); });
  4816. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  4817. }
  4818. void PianoRollComponent::updateChordReadout()
  4819. {
  4820. auto keys = engine.heldInputKeys();
  4821. if (keys.size() < 2)
  4822. {
  4823. keys.clear();
  4824. const auto& notes = currentPattern (engine.getSong()).notes;
  4825. for (auto i : selection)
  4826. if (i >= 0 && i < (int) notes.size())
  4827. keys.push_back (notes[(std::size_t) i].key);
  4828. }
  4829. const auto text = chordName (keys);
  4830. if (chordLabel.getText() != text)
  4831. chordLabel.setText (text, juce::dontSendNotification);
  4832. updateChordBubble();
  4833. }
  4834. void PianoRollComponent::updateChordBubble()
  4835. {
  4836. const auto now = juce::Time::getMillisecondCounter();
  4837. if (selection != chordPanelSelection)
  4838. {
  4839. // the toolbar's chord panel follows the selection whether this bubble is on or not (FL: FUN_00d32da0)
  4840. chordPanelSelection = selection;
  4841. if (auto* helper = dynamic_cast<ChordHelperPanel*> (chordHelper.getComponent())) // (round 190mc: only while it is open)
  4842. helper->refresh();
  4843. if (onSelectedKeys)
  4844. {
  4845. const auto& notes = currentPattern (engine.getSong()).notes;
  4846. std::vector<int> keys;
  4847. for (auto i : selection)
  4848. if (i >= 0 && i < (int) notes.size() && ! notes[(std::size_t) i].muted)
  4849. keys.push_back (notes[(std::size_t) i].key);
  4850. onSelectedKeys (keys);
  4851. }
  4852. }
  4853. if (! showChordName)
  4854. {
  4855. chordBubble.setVisible (false);
  4856. chordBubbleSelection = selection;
  4857. return;
  4858. }
  4859. if (selection != chordBubbleSelection)
  4860. {
  4861. // FL (FUN_00e5a850 → FUN_00d32da0, on every selection change): the different keys of the selected notes, muted
  4862. // ones left out; 2 to 10 of them name a chord
  4863. chordBubbleSelection = selection;
  4864. const auto& notes = currentPattern (engine.getSong()).notes;
  4865. std::vector<int> keys;
  4866. for (auto i : selection)
  4867. if (i >= 0 && i < (int) notes.size() && ! notes[(std::size_t) i].muted)
  4868. keys.push_back (notes[(std::size_t) i].key);
  4869. std::sort (keys.begin(), keys.end());
  4870. keys.erase (std::unique (keys.begin(), keys.end()), keys.end());
  4871. const auto text = keys.size() >= 2 && keys.size() <= 10 ? chordName (keys) : juce::String();
  4872. if (text.isNotEmpty())
  4873. {
  4874. chordBubble.setText (text, juce::dontSendNotification);
  4875. const auto font = chordBubble.getFont();
  4876. const auto width = juce::roundToInt (juce::GlyphArrangement::getStringWidth (font, text)) + 20;
  4877. const auto grid = gridArea();
  4878. chordBubble.setBounds (grid.getX() + 16, grid.getY() + 16, width, juce::roundToInt (font.getHeight()) + 10);
  4879. chordBubble.setVisible (true);
  4880. chordBubble.toFront (false);
  4881. chordBubbleUntil = now + 2000; // (FL keeps its chord readout at least 2 s: FUN_00d32da0 +0xac)
  4882. }
  4883. else
  4884. chordBubble.setVisible (false);
  4885. }
  4886. else if (chordBubble.isVisible() && now > chordBubbleUntil)
  4887. chordBubble.setVisible (false);
  4888. }
  4889. // Round 190hr: the reference's grid menu [STR AGridContextMenu: Widest … Narrowest (adaptive), Fixed with its values,
  4890. // Triplet; DOC: Snap to Grid Ctrl+4, Fixed / Adaptive Ctrl+5]. Each pick changes this editor's grid at once.
  4891. juce::PopupMenu PianoRollComponent::liveGridMenu()
  4892. {
  4893. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  4894. const auto change = [safe] (std::function<void (livegrid::Grid&)> fn) {
  4895. return [safe, fn] {
  4896. if (safe == nullptr)
  4897. return;
  4898. fn (safe->liveGrid);
  4899. safe->resized();
  4900. safe->repaint();
  4901. };
  4902. };
  4903. juce::PopupMenu menu;
  4904. menu.addSectionHeader (tr ("Adaptive Grid"));
  4905. for (int d = 0; d < livegrid::densityCount; ++d)
  4906. menu.addItem (tr (livegrid::densityName (d)), true, ! liveGrid.fixed && liveGrid.density == d, change ([d] (livegrid::Grid& g) {
  4907. g.fixed = false;
  4908. g.density = d;
  4909. g.snap = true;
  4910. }));
  4911. menu.addSectionHeader (tr ("Fixed Grid"));
  4912. for (int i = 0; i < livegrid::fixedCount; ++i)
  4913. {
  4914. const auto f = livegrid::fixedValues[i];
  4915. 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);
  4916. menu.addItem (text, true, liveGrid.fixed && liveGrid.fixedIndex == i, change ([i] (livegrid::Grid& g) {
  4917. g.fixed = true;
  4918. g.fixedIndex = i;
  4919. g.snap = true;
  4920. }));
  4921. }
  4922. menu.addSeparator();
  4923. menu.addItem (tr ("Triplet Grid") + "\tCtrl+3", true, liveGrid.triplet, change ([] (livegrid::Grid& g) { g.triplet = ! g.triplet; }));
  4924. menu.addItem (tr ("Snap to Grid") + "\tCtrl+4", true, liveGrid.snap, change ([] (livegrid::Grid& g) { g.snap = ! g.snap; }));
  4925. menu.addSeparator();
  4926. menu.addItem (tr ("Narrow Grid") + "\tCtrl+1", true, false, change ([] (livegrid::Grid& g) { livegrid::narrower (g); }));
  4927. menu.addItem (tr ("Widen Grid") + "\tCtrl+2", true, false, change ([] (livegrid::Grid& g) { livegrid::wider (g); }));
  4928. menu.addSeparator();
  4929. menu.addItem (tr ("Quantize") + "\tCtrl+U", onLiveQuantize != nullptr, false, [safe] { if (safe != nullptr && safe->onLiveQuantize != nullptr) safe->onLiveQuantize(); });
  4930. menu.addItem (tr ("Quantize Settings...") + "\tCtrl+Shift+U", onLiveQuantizeSettings != nullptr, false, [safe] {
  4931. if (safe != nullptr && safe->onLiveQuantizeSettings != nullptr)
  4932. safe->onLiveQuantizeSettings();
  4933. });
  4934. return menu;
  4935. }
  4936. bool PianoRollComponent::runAction (const std::string& id)
  4937. {
  4938. auto is = [&id] (const char* name) { return id == name; };
  4939. // round 190hr: the reference's grid and quantize keys, only while docked in the Clip-launch detail view
  4940. if (id.rfind ("pianoRoll.live", 0) == 0)
  4941. {
  4942. if (! liveGridOn())
  4943. return false;
  4944. if (is ("pianoRoll.liveGridNarrower")) livegrid::narrower (liveGrid);
  4945. else if (is ("pianoRoll.liveGridWider")) livegrid::wider (liveGrid);
  4946. else if (is ("pianoRoll.liveGridTriplet")) liveGrid.triplet = ! liveGrid.triplet;
  4947. else if (is ("pianoRoll.liveGridSnap")) liveGrid.snap = ! liveGrid.snap;
  4948. else if (is ("pianoRoll.liveGridFixed")) liveGrid.fixed = ! liveGrid.fixed;
  4949. else if (is ("pianoRoll.liveQuantize") && onLiveQuantize != nullptr) onLiveQuantize();
  4950. else if (is ("pianoRoll.liveQuantizeSettings") && onLiveQuantizeSettings != nullptr) onLiveQuantizeSettings();
  4951. else
  4952. return false;
  4953. resized();
  4954. repaint();
  4955. return true;
  4956. }
  4957. if (is ("pianoRoll.arpeggiate")) openNoteTool (NoteTool::arpeggiate);
  4958. else if (is ("pianoRoll.strum")) openNoteTool (NoteTool::strum);
  4959. else if (is ("pianoRoll.flip")) openNoteTool (NoteTool::flip);
  4960. else if (is ("pianoRoll.randomise")) openNoteTool (NoteTool::randomise);
  4961. else if (is ("pianoRoll.scaleLevels")) openNoteTool (NoteTool::scaleLevels);
  4962. else if (is ("pianoRoll.limit")) openNoteTool (NoteTool::limit);
  4963. else if (is ("pianoRoll.quantize")) openNoteTool (NoteTool::quantize);
  4964. else if (is ("pianoRoll.chop")) openNoteTool (NoteTool::chop);
  4965. else if (is ("pianoRoll.flam")) openNoteTool (NoteTool::flam);
  4966. else if (is ("pianoRoll.claw")) openNoteTool (NoteTool::claw);
  4967. else if (is ("pianoRoll.lfo")) openNoteTool (NoteTool::lfo);
  4968. else if (is ("pianoRoll.articulate")) openNoteTool (NoteTool::articulate);
  4969. else if (is ("pianoRoll.riffMachine")) openNoteTool (NoteTool::riffMachine);
  4970. else if (is ("pianoRoll.chordProgression")) openNoteTool (NoteTool::chordProgression);
  4971. else if (is ("pianoRoll.chordHelper")) openChordHelper();
  4972. else if (is ("pianoRoll.runLastScript")) runLastScript();
  4973. else if (is ("pianoRoll.zoomIn")) zoomAroundCentre (1.25);
  4974. else if (is ("pianoRoll.zoomOut")) zoomAroundCentre (1.0 / 1.25);
  4975. else if (is ("pianoRoll.zoom1")) zoomToBars (1);
  4976. else if (is ("pianoRoll.zoom2")) zoomToBars (4);
  4977. else if (is ("pianoRoll.zoom3")) zoomToBars (16);
  4978. else if (is ("pianoRoll.zoomAll")) zoomAll();
  4979. else if (is ("pianoRoll.zoomSelection")) zoomToSelection();
  4980. else if (is ("pianoRoll.centrePlayhead")) centreOnPlayhead();
  4981. else if (is ("pianoRoll.follow")) EditorGlobals::get().setFollowing (true, ! EditorGlobals::get().isFollowing (true));
  4982. else if (is ("pianoRoll.eventPaneAlternate")) toggleEventPaneAlternate(); // FL's Shift+Enter (round 190fz)
  4983. else if (is ("pianoRoll.quantizeStarts")) quantizeOperation (0);
  4984. else if (is ("pianoRoll.quickQuantize")) quantizeOperation (1);
  4985. else if (is ("pianoRoll.quantizeHalf")) quantizeOperation (2);
  4986. else if (is ("pianoRoll.colourSelected")) colourSelection (noteColour);
  4987. else if (is ("pianoRoll.selectByColour"))
  4988. {
  4989. // the colour of the selected note (FL: the selection's colour), else the current note colour
  4990. const auto& notes = currentPattern (engine.getSong()).notes;
  4991. selectByColour (! selection.empty() && selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].colour : noteColour);
  4992. }
  4993. else if (is ("pianoRoll.invertSelection")) setSelection (notetools::invertSelection (channelNotes(), selection));
  4994. // round 168g: FL's View / Select / Stamp / Edit / File items
  4995. else if (is ("pianoRoll.gridHighlights"))
  4996. {
  4997. gridHighlights = ! gridHighlights;
  4998. if (EditorGlobals::get().onOptionsChanged)
  4999. EditorGlobals::get().onOptionsChanged();
  5000. repaint();
  5001. }
  5002. else if (is ("pianoRoll.backgroundWave")) setBackgroundWaveShown (! isBackgroundWaveShown());
  5003. else if (is ("pianoRoll.songBarsRuler"))
  5004. {
  5005. songBarsRuler = ! songBarsRuler;
  5006. if (EditorGlobals::get().onOptionsChanged)
  5007. EditorGlobals::get().onOptionsChanged();
  5008. repaint();
  5009. }
  5010. else if (is ("pianoRoll.stackedLanes")) // round 190on (P10): Settings › LYNX extras, the View menu
  5011. {
  5012. stackedLanesExtra = ! stackedLanesExtra;
  5013. if (EditorGlobals::get().onOptionsChanged)
  5014. EditorGlobals::get().onOptionsChanged();
  5015. stackedLanesChanged();
  5016. }
  5017. else if (is ("pianoRoll.showChordName"))
  5018. {
  5019. showChordName = ! showChordName;
  5020. chordBubbleSelection.clear(); // shows the current selection's chord at once
  5021. if (EditorGlobals::get().onOptionsChanged)
  5022. EditorGlobals::get().onOptionsChanged();
  5023. updateChordBubble();
  5024. }
  5025. else if (is ("pianoRoll.selectRandomOne") || is ("pianoRoll.selectRandomMore"))
  5026. setSelection (noteedit::selectRandomMore (currentPattern (engine.getSong()), channelNotes(), selection, is ("pianoRoll.selectRandomMore"),
  5027. (std::uint32_t) juce::Random::getSystemRandom().nextInt()));
  5028. else if (is ("pianoRoll.selectOddSteps"))
  5029. setSelection (noteedit::selectOddSteps (currentPattern (engine.getSong()), channelNotes(), selection, ticksPerStep));
  5030. else if (is ("pianoRoll.stampNone")) chordBox.setSelectedId (1, juce::sendNotificationSync);
  5031. else if (is ("pianoRoll.scaleSnap"))
  5032. {
  5033. if (scaleIndex() > 0) // (like its menu item and button: only with a scale chosen)
  5034. setScaleSnap (! scaleSnap);
  5035. }
  5036. else if (is ("pianoRoll.insertSpace")) spaceOperation (0);
  5037. else if (is ("pianoRoll.sliceInsertSpace")) spaceOperation (1);
  5038. else if (is ("pianoRoll.deleteSpace")) spaceOperation (2);
  5039. else if (is ("pianoRoll.trimSpace")) spaceOperation (3);
  5040. else if (is ("pianoRoll.deleteAll")) deleteAllNotes();
  5041. else if (is ("pianoRoll.insertControllerValue")) insertControllerValue();
  5042. else if (is ("pianoRoll.importMidi") || is ("pianoRoll.openScore"))
  5043. {
  5044. // FL: Import MIDI and Open score share one file window (FUN_0120b340): .fsc, .mid or both
  5045. const auto score = is ("pianoRoll.openScore");
  5046. chooser = lynx::ui::makeFileChooser (score ? tr ("Open score") : tr ("Import MIDI"), juce::File(),
  5047. score ? "*.fsc;*.mid;*.midi" : "*.mid;*.midi");
  5048. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  5049. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  5050. if (safe != nullptr && fc.getResult().existsAsFile())
  5051. safe->loadFile (fc.getResult());
  5052. });
  5053. }
  5054. else if (is ("pianoRoll.exportMidi"))
  5055. {
  5056. const auto& song = engine.getSong();
  5057. const auto name = juce::String::fromUTF8 (song.activePattern().name.c_str());
  5058. chooser = lynx::ui::makeFileChooser (tr ("Export MIDI"), juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (name + ".mid"),
  5059. "*.mid");
  5060. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  5061. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  5062. auto file = fc.getResult();
  5063. if (safe == nullptr || file == juce::File())
  5064. return;
  5065. if (! file.hasFileExtension ("mid;midi"))
  5066. file = file.withFileExtension (".mid");
  5067. juce::String error;
  5068. if (! MidiFileIo::savePattern (safe->engine.getSong(), safe->engine.getSong().currentPattern, file, error))
  5069. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  5070. });
  5071. }
  5072. else if (is ("pianoRoll.saveScore"))
  5073. {
  5074. const auto channel = engine.getSelectedChannel();
  5075. const auto& song = engine.getSong();
  5076. auto name = channel >= 0 && channel < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str())
  5077. : juce::String ("Score");
  5078. chooser = lynx::ui::makeFileChooser (tr ("Save score as"),
  5079. juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (juce::File::createLegalFileName (name) + ".fsc"),
  5080. "*.fsc;*.mid");
  5081. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  5082. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  5083. auto file = fc.getResult();
  5084. if (safe == nullptr || file == juce::File())
  5085. return;
  5086. if (! file.hasFileExtension ("fsc;mid;midi"))
  5087. file = file.withFileExtension (".fsc");
  5088. if (! safe->saveScore (file))
  5089. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Save score as"),
  5090. tr ("There are no notes to save, or the file could not be written."));
  5091. });
  5092. }
  5093. else if (is ("pianoRoll.copyMidiClipboard")) copyToMidiClipboard();
  5094. else if (is ("pianoRoll.pasteMidiClipboard")) pasteFromMidiClipboard();
  5095. else if (is ("pianoRoll.markerAdd")) editPatternMarker (markerKeyTick(), -1);
  5096. else if (is ("pianoRoll.markerAuto"))
  5097. {
  5098. const auto tick = snap ((double) markerKeyTick(), true);
  5099. if (std::none_of (currentPattern (engine.getSong()).markers.begin(), currentPattern (engine.getSong()).markers.end(),
  5100. [tick] (const Marker& m) { return m.tick == tick; })) // (FL keeps the marker there, no undo step)
  5101. engine.editSong ([tick] (Song& s) { noteedit::addPatternAutoMarker (currentPattern (s), tick); });
  5102. repaint();
  5103. }
  5104. else if (is ("pianoRoll.markerSignature")) addPatternSignatureByKey();
  5105. else if (is ("pianoRoll.browseScores"))
  5106. {
  5107. if (onBrowseScores)
  5108. onBrowseScores();
  5109. }
  5110. else if (is ("pianoRoll.groupNotes") || is ("pianoRoll.ungroupNotes"))
  5111. {
  5112. const auto target = selection;
  5113. if (target.empty())
  5114. return true;
  5115. const auto group = is ("pianoRoll.groupNotes");
  5116. editNotes ([&] (Pattern& p) {
  5117. if (group)
  5118. notetools::groupNotes (p, target);
  5119. else
  5120. notetools::ungroupNotes (p, target);
  5121. });
  5122. repaint();
  5123. }
  5124. else
  5125. return false;
  5126. return true;
  5127. }
  5128. void PianoRollComponent::wheelNoteProperty (int note, float deltaY, bool fine, juce::Point<int> mouse)
  5129. {
  5130. // FL 2026 [SHOT round 166e]: the whole selection wherever the mouse is, else the one note
  5131. const auto targets = note < 0 ? selection : std::vector<int> { note };
  5132. if (targets.empty())
  5133. return;
  5134. const auto now = juce::Time::getMillisecondCounter();
  5135. const auto newBurst = now - lastWheelEdit > 700; // one undo step per burst of wheel moves
  5136. lastWheelEdit = now;
  5137. editNotes ([&] (Pattern& p) {
  5138. for (auto i : targets)
  5139. {
  5140. auto& n = p.notes[(std::size_t) i];
  5141. setLaneValue (n, (float) gesture::wheelStepValue (laneValue (n), deltaY, fine));
  5142. }
  5143. if (laneIsChance())
  5144. notetools::spreadGroupChance (p, targets);
  5145. }, newBurst);
  5146. // hear it (FL previews the single note; the selection's nearest note too is LYNX's own, issue #16) and a single
  5147. // note becomes the template for new notes (FL)
  5148. const auto& notes = currentPattern (engine.getSong()).notes;
  5149. const auto heard = note >= 0 ? note : noteedit::nearestNote (notes, targets, xToTick (mouse.x), yToKey (mouse.y), pixelsPerTick, rowHeight);
  5150. if (heard < 0 || heard >= (int) notes.size())
  5151. return;
  5152. const auto& n = notes[(std::size_t) heard];
  5153. if (note >= 0)
  5154. noteTemplate.takeFrom (n);
  5155. previewEdit (n.key, n.velocity);
  5156. const auto serial = ++wheelPreviewSerial;
  5157. juce::Timer::callAfterDelay (180, [safe = juce::Component::SafePointer<PianoRollComponent> (this), serial] {
  5158. if (safe != nullptr && safe->wheelPreviewSerial == serial && safe->drag == Drag::none)
  5159. safe->previewOff();
  5160. });
  5161. }
  5162. void PianoRollComponent::glideBy (double ticks, double pixels, bool immediate)
  5163. {
  5164. if (! gliding)
  5165. {
  5166. glideX.jumpTo (scrollTicks);
  5167. glideY.jumpTo (scrollY);
  5168. gliding = true;
  5169. }
  5170. const auto grid = gridArea();
  5171. glideX.target = juce::jlimit (0.0, juce::jmax (0.0, (double) viewLengthTicks() - grid.getWidth() / pixelsPerTick), glideX.target + ticks);
  5172. glideY.target = juce::jlimit (0.0, juce::jmax (0.0, (double) rows.count * rowHeight - grid.getHeight()), glideY.target + pixels);
  5173. if (immediate || ! ui::motion::enabled()) // (Settings › General › Animations off: the wheel jumps)
  5174. {
  5175. scrollTicks = glideX.target;
  5176. scrollY = (int) std::round (glideY.target);
  5177. gliding = false;
  5178. updateScrollBars();
  5179. glideX.jumpTo (scrollTicks);
  5180. glideY.jumpTo (scrollY);
  5181. repaint();
  5182. return;
  5183. }
  5184. vblank.start(); // the next frames at the display's refresh (round 190gv: no vertical blanks while still)
  5185. glideFrame();
  5186. }
  5187. void PianoRollComponent::glideFrame()
  5188. {
  5189. if (! gliding)
  5190. return;
  5191. // someone else moved the view (scroll bar, zoom, pan): the glide gives way
  5192. if (std::abs (scrollTicks - glideX.current) > 1e-6 || std::abs ((double) scrollY - std::round (glideY.current)) > 0.5)
  5193. {
  5194. gliding = false;
  5195. return;
  5196. }
  5197. scrollTicks = glideX.step (0.45, 0.5 / pixelsPerTick);
  5198. scrollY = (int) std::round (glideY.step (0.45, 1.0));
  5199. glideY.current = scrollY;
  5200. updateScrollBars();
  5201. glideX.current = scrollTicks; // the scroll bar may have clamped it
  5202. gliding = glideX.isMoving() || glideY.isMoving();
  5203. repaint();
  5204. }
  5205. void PianoRollComponent::mouseMagnify (const juce::MouseEvent& e, float scale)
  5206. {
  5207. gliding = false;
  5208. const auto factor = gesture::pinchZoomFactor (scale);
  5209. if (e.mods.isAltDown()) // taller / shorter keys, keeping the key under the pointer in place
  5210. {
  5211. const auto key = yToKey (e.y);
  5212. const auto offset = e.y - keyToY (key);
  5213. const auto height = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, juce::roundToInt (rowHeight * factor));
  5214. rowHeight = height != rowHeight ? height : juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, rowHeight + (factor > 1.0 ? 1 : factor < 1.0 ? -1 : 0));
  5215. scrollY = juce::jmax (0, rowFor (key) * rowHeight + offset - (e.y - headerHeight));
  5216. }
  5217. else
  5218. {
  5219. const auto anchorPixels = (double) juce::jmax (0, e.x - keyboardWidth);
  5220. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * factor);
  5221. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  5222. pixelsPerTick = zoomed;
  5223. }
  5224. updateScrollBars();
  5225. repaint();
  5226. }
  5227. PianoRollComponent::NoteOnScreen PianoRollComponent::firstVisibleNoteForSnapshot (int skip, juce::Point<int> near) const
  5228. {
  5229. const auto& notes = currentPattern (engine.getSong()).notes;
  5230. const auto grid = gridArea().reduced (8);
  5231. NoteOnScreen best;
  5232. for (const auto i : channelNotes())
  5233. {
  5234. const auto& n = notes[(std::size_t) i];
  5235. if (const auto r = noteRect (n.start, n.length, n.key).toNearestInt(); grid.contains (r) && i != skip)
  5236. {
  5237. if (skip < 0)
  5238. return { i, r };
  5239. if (best.index < 0 || r.getCentre().getDistanceFrom (near) < best.bounds.getCentre().getDistanceFrom (near))
  5240. best = { i, r };
  5241. }
  5242. }
  5243. return best;
  5244. }
  5245. void PianoRollComponent::showToolModeMenu()
  5246. {
  5247. drag = Drag::none;
  5248. setMouseCursor (juce::MouseCursor::NormalCursor);
  5249. toolModeMenu (tools, [this] (EditTool t) { tools.setTool (t); }, mainMenu != nullptr ? mainMenu() : juce::PopupMenu())
  5250. .showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  5251. }
  5252. void PianoRollComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& rawWheel)
  5253. {
  5254. const LaneScope laneScope (*this, stackedLaneAt (e.getPosition())); // (round 190on)
  5255. const auto wheel = flmods::normalisedWheel (rawWheel); // Windows touchpads: pieces of a notch (round 170e)
  5256. // FL's right-hold + wheel (round 190mp, DE-61; capture 190mp A3.3): each notch down picks the next tool to the right,
  5257. // up the one to the left, stopping at the ends; the held press does nothing more (no erase stroke, no knife, nothing
  5258. // on release)
  5259. if (e.mods.isRightButtonDown() && ! e.mods.isLeftButtonDown() && ! e.mods.isMiddleButtonDown())
  5260. {
  5261. if (wheel.deltaY != 0.0f)
  5262. {
  5263. drag = Drag::none;
  5264. tools.step (wheel.deltaY < 0.0f ? 1 : -1);
  5265. }
  5266. return;
  5267. }
  5268. const auto ctrl = flmods::ctrl (e.mods), alt = e.mods.isAltDown(), shift = e.mods.isShiftDown();
  5269. const auto overGrid = gridArea().contains (e.getPosition()) || velocityArea().contains (e.getPosition());
  5270. // issue #254 (round 190ou): a notch of the horizontal wheel (a tilt wheel, a second wheel) moves the view 1.5 beats
  5271. // sideways whatever the zoom, as in FL 2026 (a trackpad's swipe and Shift+wheel keep their own ways below)
  5272. if (! ctrl && ! alt)
  5273. if (const auto notch = gesture::horizontalWheelNotch (wheel.deltaX, wheel.deltaY, wheel.isSmooth, shift); notch != 0)
  5274. {
  5275. gliding = false;
  5276. glideBy (notch * gesture::horizontalWheelBeats * ppq, 0.0);
  5277. return;
  5278. }
  5279. // the wheel over the zoom wheel: one zoom level a notch (FL: the only wheel gesture of the vertical zoom)
  5280. if (zoomWheelArea().contains (e.getPosition()))
  5281. {
  5282. if (wheel.deltaY != 0.0f)
  5283. {
  5284. const auto key = zoomAnchorKey();
  5285. setRowHeightAround (rowHeight + (wheel.deltaY > 0 ? 2 : -2), key, keyToY (key) + rowHeight / 2);
  5286. }
  5287. return;
  5288. }
  5289. // Alt+wheel: the velocity (or the lane's property) of the selected notes wherever the mouse is, with nothing
  5290. // selected of the note nearest to the mouse (FL 2026, round 166e); Ctrl+Alt: fine steps
  5291. if (alt && ! shift && overGrid && wheel.deltaY != 0.0f)
  5292. {
  5293. auto note = -1;
  5294. if (selection.empty())
  5295. {
  5296. note = hoverAt (e.getPosition()).note;
  5297. if (note < 0)
  5298. note = noteedit::nearestNote (currentPattern (engine.getSong()).notes, channelNotes(), xToTick (e.x), yToKey (e.y), pixelsPerTick,
  5299. velocityArea().contains (e.getPosition()) ? 0.0 : rowHeight);
  5300. }
  5301. if (note >= 0 || ! selection.empty())
  5302. {
  5303. wheelNoteProperty (note, wheel.deltaY, ctrl, e.getPosition());
  5304. return;
  5305. }
  5306. }
  5307. if (shift && alt) // nudge the selection by the grid
  5308. {
  5309. if (wheel.deltaY != 0.0f && ! selection.empty())
  5310. {
  5311. const auto now = juce::Time::getMillisecondCounter();
  5312. const auto newBurst = now - lastWheelEdit > 700;
  5313. lastWheelEdit = now;
  5314. const auto ticks = (wheel.deltaY > 0 ? 1 : -1) * gridTicks();
  5315. editNotes ([this, ticks] (Pattern& p) {
  5316. auto deltaTicks = ticks;
  5317. auto deltaKeys = 0;
  5318. noteedit::move (p, selection, deltaTicks, deltaKeys);
  5319. }, newBurst);
  5320. sortNotes();
  5321. }
  5322. return;
  5323. }
  5324. gliding = false;
  5325. if (ctrl && alt)
  5326. {
  5327. // vertical zoom keeping the key under the mouse in place
  5328. const auto key = yToKey (e.y);
  5329. const auto offset = e.y - keyToY (key);
  5330. rowHeight = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, rowHeight + (wheel.deltaY > 0 ? 2 : -2));
  5331. scrollY = juce::jmax (0, rowFor (key) * rowHeight + offset - (e.y - headerHeight));
  5332. }
  5333. else if (ctrl)
  5334. {
  5335. // zoom keeping the tick under the mouse in place
  5336. const auto anchorPixels = (double) juce::jmax (0, e.x - keyboardWidth);
  5337. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  5338. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  5339. pixelsPerTick = zoomed;
  5340. }
  5341. else
  5342. {
  5343. // plain wheel: up/down (Shift: left/right); a horizontal wheel or trackpad swipe scrolls sideways
  5344. const auto vertical = gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 3.0 * rowHeight);
  5345. const auto sideways = gesture::wheelScrollPixels (wheel.deltaX, wheel.isSmooth, 60.0);
  5346. if (shift)
  5347. glideBy (gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 80.0) / pixelsPerTick, 0.0, wheel.isSmooth);
  5348. else
  5349. glideBy (sideways / pixelsPerTick, vertical, wheel.isSmooth); // a trackpad moves the view at once
  5350. return;
  5351. }
  5352. updateScrollBars();
  5353. repaint();
  5354. }
  5355. // --- keyboard ----------------------------------------------------------------
  5356. void PianoRollComponent::deleteSelection()
  5357. {
  5358. if (selection.empty())
  5359. return;
  5360. const auto doomed = selection;
  5361. fadeOut (doomed); // (issue #250)
  5362. setSelection ({});
  5363. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  5364. }
  5365. void PianoRollComponent::fadeOut (const std::vector<int>& notes)
  5366. {
  5367. // issue #250 (round 190oq): each deleted note in view leaves FL's ghost (nothing at all when Animations are off or
  5368. // effects reduced: ui/DeleteFade.h)
  5369. if (! ui::DeleteFade::enabled())
  5370. return;
  5371. const auto& pattern = currentPattern (engine.getSong());
  5372. const auto grid = gridArea().toFloat();
  5373. for (const auto i : notes)
  5374. if (i >= 0 && i < (int) pattern.notes.size())
  5375. {
  5376. const auto& n = pattern.notes[(std::size_t) i];
  5377. if (const auto r = noteRect (n.start, n.length, n.key); r.intersects (grid))
  5378. deleteFade.add (r, theme::noteGroupColour (n.colour, n.velocity));
  5379. }
  5380. }
  5381. void PianoRollComponent::paintOverChildren (juce::Graphics& g)
  5382. {
  5383. deleteFade.paint (g, gridArea()); // (issue #250: nothing while no note is fading)
  5384. }
  5385. void PianoRollComponent::copySelection()
  5386. {
  5387. clipboard = noteedit::copy (currentPattern (engine.getSong()), selectionOrAll());
  5388. publishNotes();
  5389. }
  5390. // issue #232 stage 2 (round 190nz): the note clipboard also on the system clipboard, for another LYNX SHARE window
  5391. void PianoRollComponent::publishNotes()
  5392. {
  5393. if (! windowclip::enabled() || clipboard.empty())
  5394. return;
  5395. crossclipboard::Payload copy;
  5396. copy.kind = crossclipboard::Kind::notes;
  5397. copy.notes = clipboard;
  5398. windowclip::publish (std::move (copy));
  5399. }
  5400. // Pain point 26 (round 177d, LYNX's own; FL's ghost notes can only be looked at): the ghost notes on show (the other
  5401. // channels' notes in this pattern, and this channel's notes in the clips that play at the same time) go to the note
  5402. // clipboard, so Ctrl+V pastes them into the channel being edited, where they were drawn.
  5403. std::vector<Note> PianoRollComponent::visibleGhostNotes() const
  5404. {
  5405. std::vector<Note> out;
  5406. if (! showGhosts || allChannels)
  5407. return out;
  5408. const auto& song = engine.getSong();
  5409. for (const auto& n : currentPattern (song).notes)
  5410. if (! edits (n) && ghostShown (n.channel))
  5411. out.push_back (n);
  5412. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, engine.getSelectedChannel()))
  5413. out.push_back (n);
  5414. std::stable_sort (out.begin(), out.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  5415. return out;
  5416. }
  5417. void PianoRollComponent::copyGhostNotes()
  5418. {
  5419. auto ghosts = visibleGhostNotes();
  5420. if (ghosts.empty())
  5421. return;
  5422. const auto count = (int) ghosts.size();
  5423. clipboard = std::move (ghosts);
  5424. publishNotes();
  5425. ui::postHint ({ tr ("Copied {0} ghost notes: Ctrl+V pastes them into this channel", { juce::String (count) }) }, 2500);
  5426. }
  5427. void PianoRollComponent::paste()
  5428. {
  5429. // issue #232 (round 190nz): notes copied in another LYNX SHARE window paste here, on the channel being edited
  5430. auto incoming = windowclip::incoming (crossclipboard::Kind::notes);
  5431. if (incoming && ! incoming->notes.empty())
  5432. clipboard = incoming->notes;
  5433. else
  5434. incoming.reset();
  5435. if (clipboard.empty())
  5436. return;
  5437. // issue #211 (round 190mq): where the notes go depends on the layout (core/PastePlace.h): FL's rule in the Pattern
  5438. // layout (the part of the pattern in view), Live's insert marker in Clip-launch, the playhead in Simple. Pasted
  5439. // notes are selected, ready to drag.
  5440. const auto offset = pasteOffset();
  5441. std::vector<int> added;
  5442. // ("All": each note keeps its channel; another window's notes go on the channel being edited)
  5443. const auto channel = allChannels && ! incoming ? -1 : engine.getSelectedChannel();
  5444. editNotes ([&added, channel, offset] (Pattern& p) {
  5445. added = noteedit::paste (p, clipboard, offset, channel);
  5446. notetools::regroup (p, added); // copies of grouped notes form groups of their own
  5447. });
  5448. setSelection (added);
  5449. sortNotes();
  5450. if (incoming)
  5451. ui::postHint ({ windowclip::pastedFrom (*incoming) }, 2500);
  5452. }
  5453. std::int64_t PianoRollComponent::pasteOffset() const
  5454. {
  5455. if (clipboard.empty())
  5456. return 0;
  5457. pasteplace::Where w;
  5458. w.first = clipboard.front().start;
  5459. for (const auto& n : clipboard)
  5460. w.first = std::min (w.first, n.start);
  5461. w.rulerMark = rulerMark;
  5462. w.grid = gridTicks();
  5463. w.viewFrom = (std::int64_t) std::max (0.0, scrollTicks);
  5464. w.viewTo = (std::int64_t) xToTick (gridArea().getRight());
  5465. if (timeFrom >= 0 && timeTo > timeFrom)
  5466. w.selection = timeFrom;
  5467. // the song position in this pattern (the playhead while it plays; stopped, where it would start)
  5468. const auto& song = engine.getSong();
  5469. const auto position = playheadTick >= 0.0 ? playheadTick
  5470. : transportedit::patternPlayhead (song, song.currentPattern, engine.getTransport().positionTicks.load(),
  5471. engine.patternLinearOrigin());
  5472. if (position >= 0.0)
  5473. w.position = snap (position, true);
  5474. const auto rule = pasteplace::ruleFor (layoutstyle::current());
  5475. return pasteplace::start (rule, w, pasteplace::UniformBars { song.barTicks() }) - w.first;
  5476. }
  5477. void PianoRollComponent::duplicateSelection()
  5478. {
  5479. const auto source = selectionOrAll();
  5480. if (source.empty())
  5481. return;
  5482. std::vector<int> added;
  5483. const auto meter = engine.getSong().meter();
  5484. editNotes ([&added, &source, meter] (Pattern& p) {
  5485. added = noteedit::duplicateBars (p, source, meter); // FL: whole bars later (round 170h)
  5486. notetools::regroup (p, added);
  5487. });
  5488. setSelection (added);
  5489. sortNotes();
  5490. }
  5491. void PianoRollComponent::quantizeOperation (int kind)
  5492. {
  5493. const auto grid = gridTicks();
  5494. runOperation ([grid, kind] (Pattern& p, const std::vector<int>& t) {
  5495. if (kind == 1)
  5496. noteedit::quantizeFull (p, t, grid);
  5497. else
  5498. transportedit::quantizeNoteStarts (p, t, grid, kind == 2 ? 0.5 : 1.0);
  5499. return t;
  5500. });
  5501. }
  5502. void PianoRollComponent::nudge (std::int64_t ticks, int keys)
  5503. {
  5504. if (selection.empty())
  5505. return;
  5506. // folded to the scale (round 166d): Up / Down step through the shown keys (an octave stays an octave)
  5507. if (folded() && keys != 0 && std::abs (keys) < 12)
  5508. {
  5509. editNotes ([this, &ticks, keys] (Pattern& p) {
  5510. auto noKeys = 0;
  5511. noteedit::move (p, selection, ticks, noKeys);
  5512. for (auto i : selection)
  5513. if (i >= 0 && i < (int) p.notes.size())
  5514. p.notes[(std::size_t) i].key = rows.step (p.notes[(std::size_t) i].key, keys);
  5515. });
  5516. }
  5517. else
  5518. {
  5519. if (keys == 1 || keys == -1) // snap to scale: up / down step along the scale (every selected note, issue #14)
  5520. if (const auto scale = snapScale(); scale.active())
  5521. {
  5522. editNotes ([this, keys, scale] (Pattern& p) { scalesnap::moveBySteps (p, selection, keys, scale); });
  5523. keys = 0;
  5524. if (ticks == 0)
  5525. {
  5526. sortNotes();
  5527. return;
  5528. }
  5529. }
  5530. editNotes ([this, &ticks, &keys] (Pattern& p) { noteedit::move (p, selection, ticks, keys); });
  5531. }
  5532. if (keys != 0 && selection.size() == 1)
  5533. {
  5534. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) selection[0]];
  5535. previewEdit (n.key, n.velocity);
  5536. juce::Timer::callAfterDelay (150, [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  5537. if (safe != nullptr)
  5538. safe->previewOff();
  5539. });
  5540. }
  5541. sortNotes();
  5542. }
  5543. bool PianoRollComponent::handleKey (const juce::KeyPress& key)
  5544. {
  5545. // round 190im (R15): a key that changed the song is an edit by hand: Follow pauses (when that option is on)
  5546. const juce::ScopeGuard followEdit { [this, before = engine.getPublishCount()] {
  5547. EditorGlobals::get().pauseFollowIfEdited (EditorGlobals::FollowView::pianoRoll, before, engine.getPublishCount());
  5548. } };
  5549. const auto mods = key.getModifiers();
  5550. const auto cmd = mods.isCommandDown();
  5551. const auto alt = mods.isAltDown();
  5552. const auto shift = mods.isShiftDown();
  5553. const auto code = key.getKeyCode();
  5554. const auto letter = keys::letterOfKeyCode (code); // (0 for F-keys, numpad, arrows: issue #12)
  5555. const auto grid = gridTicks();
  5556. const auto bar = engine.getSong().barTicks();
  5557. // round 190hr: the Clip-launch layout's docked editor takes the reference's grid keys (Ctrl+1…5) and Quantize
  5558. // (Ctrl+U / Ctrl+Shift+U) before the FL editor's own (FL's Ctrl+U chop stays in the Pattern layout)
  5559. if (liveGridOn() && cmd && ! alt)
  5560. {
  5561. const char* live = nullptr;
  5562. if (letter == 'U')
  5563. live = shift ? "pianoRoll.liveQuantizeSettings" : "pianoRoll.liveQuantize";
  5564. else if (! shift && code >= '1' && code <= '5')
  5565. {
  5566. static constexpr const char* gridKeys[] { "pianoRoll.liveGridNarrower", "pianoRoll.liveGridWider", "pianoRoll.liveGridTriplet",
  5567. "pianoRoll.liveGridSnap", "pianoRoll.liveGridFixed" };
  5568. live = gridKeys[code - '1'];
  5569. }
  5570. if (live != nullptr && runAction (live))
  5571. return true;
  5572. }
  5573. // (issue #219, round 190ng: Backspace's snap on / off is the key map's playlist.snapToggle / pianoRoll.snapToggle now, so it
  5574. // can be given another key)
  5575. if (code == juce::KeyPress::deleteKey && ! cmd) // (Ctrl+Shift+Del: pattern.delete; Ctrl+Del: pianoRoll.deleteSpace)
  5576. {
  5577. deleteSelection();
  5578. return true;
  5579. }
  5580. if (code == juce::KeyPress::escapeKey)
  5581. {
  5582. // (issue #217, round 190ng: an Esc with nothing selected is left to the main window, which closes the Piano roll as FL)
  5583. if (selection.empty() && timeFrom < 0)
  5584. return false;
  5585. setSelection ({});
  5586. setTimeSelection (-1, -1);
  5587. return true;
  5588. }
  5589. if (alt && cmd && letter == 'V') // editable ghost notes
  5590. {
  5591. editGhosts = ! editGhosts;
  5592. if (editGhosts && ! showGhosts)
  5593. ghostButton.setToggleState (true, juce::sendNotificationSync);
  5594. repaint();
  5595. return true;
  5596. }
  5597. if (alt && ! cmd && letter == 'V')
  5598. {
  5599. ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync);
  5600. return true;
  5601. }
  5602. if (cmd && alt && code == juce::KeyPress::homeKey)
  5603. {
  5604. resizeFromLeft = ! resizeFromLeft;
  5605. return true;
  5606. }
  5607. if (cmd && letter == 'A')
  5608. {
  5609. selectAll();
  5610. return true;
  5611. }
  5612. if (cmd && ! shift && letter == 'C') // (Ctrl+Shift+C: pattern.clone)
  5613. {
  5614. copySelection();
  5615. return true;
  5616. }
  5617. if (cmd && letter == 'X')
  5618. {
  5619. copySelection();
  5620. deleteSelection();
  5621. return true;
  5622. }
  5623. if (cmd && ! shift && letter == 'V') // (Ctrl+Shift+V: pianoRoll.pasteMidiClipboard)
  5624. {
  5625. paste();
  5626. return true;
  5627. }
  5628. if (cmd && letter == 'B')
  5629. {
  5630. duplicateSelection();
  5631. return true;
  5632. }
  5633. // quick note operations: one undo step each, on the selection (or all notes). The quantize ones are key map
  5634. // actions (pianoRoll.quickQuantize / quantizeStarts / quantizeHalf) so they can be reassigned.
  5635. if (cmd && letter == 'U')
  5636. {
  5637. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); });
  5638. return true;
  5639. }
  5640. if (cmd && letter == 'G')
  5641. {
  5642. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; });
  5643. return true;
  5644. }
  5645. if (cmd && letter == 'L')
  5646. {
  5647. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; });
  5648. return true;
  5649. }
  5650. if (shift && ! cmd && ! alt && letter == 'D')
  5651. {
  5652. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::shrinkToGrid (p, t, grid); return t; });
  5653. return true;
  5654. }
  5655. if (cmd && shift && (code == juce::KeyPress::leftKey || code == juce::KeyPress::rightKey))
  5656. {
  5657. const auto steps = code == juce::KeyPress::rightKey ? 1 : -1;
  5658. runOperation ([grid, bar, steps] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, steps); return t; });
  5659. return true;
  5660. }
  5661. // FL's editor keys (ShortcutsModule EEMuteAction / EEUnmuteAction / EEDeselAction, round 167j): Alt+M mutes,
  5662. // Shift+Alt+M unmutes, Ctrl+D deselects. (Ctrl+M stays FL's metronome.)
  5663. if (alt && ! cmd && letter == 'M')
  5664. {
  5665. auto mute = ! shift;
  5666. // issue #249 (round 190oq, LYNX extra, off = FL): Alt+M on notes that are all muted unmutes them
  5667. if (mute && mutekeys::toggles())
  5668. {
  5669. const auto& notes = currentPattern (engine.getSong()).notes;
  5670. const auto target = selectionOrAll();
  5671. mute = target.empty() || ! std::all_of (target.begin(), target.end(), [&notes] (int i) {
  5672. return i >= 0 && i < (int) notes.size() && notes[(std::size_t) i].muted;
  5673. });
  5674. }
  5675. setNotesMuted (mute);
  5676. return true;
  5677. }
  5678. if (cmd && ! alt && ! shift && letter == 'D')
  5679. {
  5680. setSelection ({});
  5681. setTimeSelection (-1, -1);
  5682. rulerMark = -1;
  5683. return true;
  5684. }
  5685. if (cmd && letter == 'P')
  5686. {
  5687. togglePorta();
  5688. return true;
  5689. }
  5690. // FL's editor arrow keys (noteedit::arrowMove): Shift+Up/Down a semitone, Ctrl+Up/Down an octave,
  5691. // Shift+Left/Right one grid step
  5692. if (! selection.empty())
  5693. {
  5694. using noteedit::Arrow;
  5695. const auto arrow = code == juce::KeyPress::upKey ? std::optional<Arrow> (Arrow::up)
  5696. : code == juce::KeyPress::downKey ? std::optional<Arrow> (Arrow::down)
  5697. : code == juce::KeyPress::leftKey ? std::optional<Arrow> (Arrow::left)
  5698. : code == juce::KeyPress::rightKey ? std::optional<Arrow> (Arrow::right)
  5699. : std::nullopt;
  5700. if (arrow)
  5701. if (const auto move = noteedit::arrowMove (*arrow, cmd, shift, alt); move.handled)
  5702. {
  5703. nudge (move.gridSteps * grid, move.keys);
  5704. return true;
  5705. }
  5706. }
  5707. // (the tools and the other single letters are key map actions now: runKeyAction, issue #12)
  5708. return false;
  5709. }
  5710. bool PianoRollComponent::runKeyAction (const std::string& id)
  5711. {
  5712. for (const auto& t : editTools())
  5713. if (t.tool != EditTool::slip && id == "pianoRoll.tool." + std::string (editToolId (t.tool)))
  5714. {
  5715. tools.setTool (t.tool);
  5716. return true;
  5717. }
  5718. if (id == "pianoRoll.slide") slideButton.setToggleState (! slideButton.getToggleState(), juce::dontSendNotification);
  5719. else if (id == "pianoRoll.previousChannel") stepChannel (-1, false);
  5720. else if (id == "pianoRoll.nextChannel") stepChannel (1, false);
  5721. else if (id == "pianoRoll.previousChannelWithNotes") stepChannel (-1, true);
  5722. else if (id == "pianoRoll.nextChannelWithNotes") stepChannel (1, true);
  5723. else return false;
  5724. return true;
  5725. }
  5726. void PianoRollComponent::refreshToolKeys (const std::function<juce::String (const std::string&)>& keyOf)
  5727. {
  5728. tools.refreshKeys ([&keyOf] (EditTool t) { return keyOf ("pianoRoll.tool." + std::string (editToolId (t))); });
  5729. // round 179a: the slide toggle is only an icon, so its tips name its key the way the tool buttons do
  5730. const auto slideKey = keyOf ("pianoRoll.slide");
  5731. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)")
  5732. + (slideKey.isNotEmpty() ? " (" + slideKey + ")" : juce::String()));
  5733. ui::setQuickTip (slideButton, tr ("Slide notes"), slideKey);
  5734. }
  5735. juce::PopupMenu PianoRollComponent::midiMenu()
  5736. {
  5737. juce::PopupMenu menu;
  5738. menu.addItem (tr ("Import .mid into this channel...") + keyText ("pianoRoll.importMidi"), [this] { runAction ("pianoRoll.importMidi"); });
  5739. menu.addItem (tr ("Export pattern as .mid...") + keyText ("pianoRoll.exportMidi"), [this] { runAction ("pianoRoll.exportMidi"); });
  5740. return menu;
  5741. }
  5742. void PianoRollComponent::importMidi (const midiimport::ParsedMidi& midi, const juce::String& name)
  5743. {
  5744. // FL's "Import MIDI data" window with Blend (REA round 146b): which tracks / channels / controller
  5745. static midiimport::Options remembered;
  5746. juce::Component::SafePointer<PianoRollComponent> safe (this);
  5747. showMidiImportDialog (name, midi, remembered, true, [safe, midi] (const midiimport::Options& o) {
  5748. remembered = o;
  5749. if (safe == nullptr)
  5750. return;
  5751. std::vector<int> added;
  5752. std::string err;
  5753. const auto channel = safe->engine.getSelectedChannel();
  5754. safe->engine.editSong ([&] (Song& s) { added = midiimport::importIntoChannel (s, channel, midi, o, err); });
  5755. if (added.empty())
  5756. {
  5757. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", juce::String::fromUTF8 (err.c_str()));
  5758. return;
  5759. }
  5760. safe->knownNoteCount = currentPattern (safe->engine.getSong()).notes.size();
  5761. safe->setSelection (added);
  5762. safe->scrollToNotes();
  5763. safe->repaint();
  5764. });
  5765. }
  5766. // --- other -------------------------------------------------------------------
  5767. void PianoRollComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
  5768. {
  5769. if (bar == &hBar)
  5770. scrollTicks = start;
  5771. else
  5772. scrollY = (int) start;
  5773. repaint();
  5774. }
  5775. void PianoRollComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  5776. {
  5777. // pattern/channel switched or the pattern changed externally (undo, another window): the selection no longer applies
  5778. const auto& song = engine.getSong();
  5779. const auto count = currentPattern (song).notes.size();
  5780. if (song.currentPattern != knownPattern || engine.getSelectedChannel() != knownChannel || count != knownNoteCount)
  5781. {
  5782. if (engine.getSelectedChannel() != knownChannel)
  5783. {
  5784. stopListening();
  5785. if (knownChannel >= 0)
  5786. allChannels = false; // another channel picked (Channel Rack, keys): back to it alone
  5787. }
  5788. if (song.currentPattern != knownPattern)
  5789. {
  5790. timeFrom = timeTo = -1; // (the time selection belongs to the pattern it was made in)
  5791. rulerMark = -1;
  5792. }
  5793. knownPattern = song.currentPattern;
  5794. knownChannel = engine.getSelectedChannel();
  5795. knownNoteCount = count;
  5796. if (drag == Drag::none)
  5797. selection.clear();
  5798. }
  5799. followButton.setToggleState (EditorGlobals::get().isFollowing (true), juce::dontSendNotification);
  5800. syncPadRows();
  5801. refreshChannelBox();
  5802. rebuildLaneBox();
  5803. updateScrollBars();
  5804. repaint();
  5805. }
  5806. std::optional<AutomationTarget> PianoRollComponent::eventLaneTarget() const
  5807. {
  5808. const auto k = laneId() - eventLaneIdBase;
  5809. if (k >= 0 && k < (int) eventTargets.size())
  5810. return eventTargets[(std::size_t) k];
  5811. return std::nullopt;
  5812. }
  5813. void PianoRollComponent::rebuildLaneBox (std::optional<AutomationTarget> shown, bool force)
  5814. {
  5815. // the pattern's event lanes, plus the one shown (it may have no events yet)
  5816. if (! shown)
  5817. shown = eventLaneTarget();
  5818. std::vector<AutomationTarget> targets;
  5819. for (const auto& lane : currentPattern (engine.getSong()).events)
  5820. if (lane.target.kind != AutomationTargetKind::none && ! lane.events.empty())
  5821. targets.push_back (lane.target);
  5822. if (shown && std::find (targets.begin(), targets.end(), *shown) == targets.end())
  5823. targets.push_back (*shown);
  5824. for (const auto& l : stacked) // (round 190on: the stacked lanes' targets too, even with no event yet)
  5825. if (l->spec.target && std::find (targets.begin(), targets.end(), *l->spec.target) == targets.end())
  5826. targets.push_back (*l->spec.target);
  5827. if (targets == eventTargets && ! force)
  5828. return;
  5829. eventTargets = targets;
  5830. const auto previous = laneBox.getSelectedId();
  5831. laneBox.clear (juce::dontSendNotification);
  5832. addNoteLanes();
  5833. if (! eventTargets.empty())
  5834. laneBox.addSectionHeading (tr ("Pattern events"));
  5835. for (int k = 0; k < (int) eventTargets.size(); ++k)
  5836. laneBox.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
  5837. auto id = previous >= 1 && previous <= laneLast ? previous : 1;
  5838. if (shown)
  5839. id = eventLaneIdBase + (int) (std::find (eventTargets.begin(), eventTargets.end(), *shown) - eventTargets.begin());
  5840. laneBox.setSelectedId (id, juce::dontSendNotification);
  5841. rebuildStackedBoxes(); // (round 190on: their lists hold the same event lanes)
  5842. }
  5843. void PianoRollComponent::showEventLane (const AutomationTarget& target)
  5844. {
  5845. rebuildLaneBox (target, true);
  5846. repaint();
  5847. }
  5848. void PianoRollComponent::drawEvents (int fromX, int toX, int y, bool erase)
  5849. {
  5850. const auto target = eventLaneTarget();
  5851. if (! target)
  5852. return;
  5853. const auto lane = velocityArea();
  5854. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8));
  5855. const auto step = std::max<std::int64_t> (1, gridTicks());
  5856. const auto t0 = std::max<std::int64_t> (0, (std::int64_t) std::floor (xToTick (juce::jmin (fromX, toX)) / (double) step) * step);
  5857. const auto t1 = std::max (t0 + step, (std::int64_t) std::floor (xToTick (juce::jmax (fromX, toX)) / (double) step) * step + step);
  5858. const auto pattern = engine.getSong().currentPattern;
  5859. engine.editSong ([&] (Song& s) {
  5860. if (pattern < 0 || pattern >= (int) s.patterns.size())
  5861. return;
  5862. auto& p = s.patterns[(std::size_t) pattern];
  5863. if (erase)
  5864. {
  5865. if (auto* l = eventedit::findLane (p, *target))
  5866. eventedit::erase (*l, t0, t1);
  5867. eventedit::removeEmptyLanes (p);
  5868. }
  5869. else
  5870. eventedit::fill (eventedit::laneFor (p, *target), t0, t1, value, step);
  5871. });
  5872. repaint (velocityArea());
  5873. }
  5874. NoteMask PianoRollComponent::soundingNow() const
  5875. {
  5876. if (! allChannels)
  5877. return engine.soundingKeys (engine.getSelectedChannel());
  5878. // "All": every channel with notes in this pattern
  5879. NoteMask all {};
  5880. const auto& song = engine.getSong();
  5881. std::vector<char> seen (song.channels.size(), 0);
  5882. for (const auto& n : currentPattern (song).notes)
  5883. if (n.channel >= 0 && n.channel < (int) seen.size() && ! seen[(std::size_t) n.channel])
  5884. {
  5885. seen[(std::size_t) n.channel] = 1;
  5886. const auto k = engine.soundingKeys (n.channel);
  5887. all[0] |= k[0], all[1] |= k[1];
  5888. }
  5889. if (const auto selected = engine.getSelectedChannel(); selected >= 0 && selected < (int) seen.size() && ! seen[(std::size_t) selected])
  5890. {
  5891. const auto k = engine.soundingKeys (selected);
  5892. all[0] |= k[0], all[1] |= k[1];
  5893. }
  5894. return all;
  5895. }
  5896. void PianoRollComponent::timerCallback()
  5897. {
  5898. if (holdRing && hold != Hold::none) // round 190mr (DE-63): the hold ring grows
  5899. repaint (holdRingArea());
  5900. if (channelBox.getSelectedId() != (allChannels ? allChannelsId : engine.getSelectedChannel() + 1))
  5901. refreshChannelBox();
  5902. updateChordReadout();
  5903. // round 190pf (P13): the rows follow the Chord lane's chord at the song position (a check of two ints per tick)
  5904. if (chordlane::pianoRollHighlight())
  5905. {
  5906. const auto& song = engine.getSong();
  5907. const auto now = song.chords().empty() ? chordlane::Highlight {}
  5908. : chordlane::highlightAt (song, (std::int64_t) engine.getTransport().positionTicks.load());
  5909. if (now != shownChord)
  5910. {
  5911. shownChord = now;
  5912. repaint();
  5913. }
  5914. }
  5915. else if (shownChord.root >= 0)
  5916. {
  5917. shownChord = {};
  5918. repaint();
  5919. }
  5920. // the keys the channel plays light up on the keyboard (song, pattern, typing keyboard, MIDI)
  5921. if (const auto lit = isShowing() ? soundingNow() : NoteMask {}; lit != litKeys)
  5922. {
  5923. litKeys = lit;
  5924. repaint (0, headerHeight, keyboardWidth, getHeight() - headerHeight);
  5925. }
  5926. if (const bool playing = engine.getTransport().playing.load(); playButton.getToggleState() != playing)
  5927. playButton.setToggleState (playing, juce::dontSendNotification);
  5928. }
  5929. // round 190ip: the playhead as paint() draws it (the line in the grid, the triangle in the ruler), for the GPU overlay
  5930. void PianoRollComponent::paintPlayheadAt (juce::Graphics& g, float x)
  5931. {
  5932. const auto grid = gridArea();
  5933. g.setColour (theme::colour::playhead);
  5934. {
  5935. juce::Graphics::ScopedSaveState state (g);
  5936. if (g.reduceClipRegion (grid))
  5937. g.drawVerticalLine ((int) x, (float) grid.getY(), (float) grid.getBottom());
  5938. }
  5939. juce::Graphics::ScopedSaveState state (g);
  5940. if (g.reduceClipRegion (juce::Rectangle<int> (keyboardWidth, rulerTop, grid.getWidth(), timelineHeight)))
  5941. {
  5942. juce::Path tri;
  5943. tri.addTriangle (x - 5, (float) rulerTop, x + 5, (float) rulerTop, x, (float) rulerTop + 8);
  5944. g.fillPath (tri);
  5945. }
  5946. }
  5947. ui::MotionOverlay::Mark PianoRollComponent::playheadMark() const
  5948. {
  5949. const auto grid = gridArea();
  5950. ui::MotionOverlay::Mark m;
  5951. m.x = (float) tickToX (playheadTick);
  5952. m.extent = juce::Rectangle<int>::leftTopRightBottom (-7, rulerTop, 7, grid.getBottom());
  5953. m.clip = juce::Rectangle<int>::leftTopRightBottom (grid.getX(), rulerTop, grid.getRight(), grid.getBottom());
  5954. m.look = ((std::uint64_t) (std::uint32_t) theme::colour::playhead.getARGB() << 32) ^ ((std::uint64_t) (std::uint32_t) grid.getY() << 20)
  5955. ^ (std::uint64_t) (std::uint32_t) grid.getHeight() ^ ((std::uint64_t) (std::uint32_t) keyboardWidth << 44);
  5956. return m;
  5957. }
  5958. juce::Rectangle<int> PianoRollComponent::playheadColumn (double tick) const
  5959. {
  5960. return tick >= 0.0 ? juce::Rectangle<int> ((int) tickToX (tick) - 7, 0, 14, getHeight()) : juce::Rectangle<int>();
  5961. }
  5962. bool PianoRollComponent::playheadFrame (double)
  5963. {
  5964. auto& transport = engine.getTransport();
  5965. auto tick = -1.0;
  5966. const auto playing = transport.playing.load();
  5967. // round 190im (R15): a scroll by hand while playing (sideways, same zoom, not by Follow) pauses Follow
  5968. auto& globals = EditorGlobals::get();
  5969. globals.noteTransport (playing);
  5970. if (playing && scrollTicks != followSeenScroll && pixelsPerTick == followSeenZoom)
  5971. globals.pauseFollowForScroll (EditorGlobals::FollowView::pianoRoll);
  5972. followSeenScroll = scrollTicks;
  5973. followSeenZoom = pixelsPerTick;
  5974. // the playhead shows while the edited pattern plays: Pattern mode, or a clip of it in Song mode (round 162);
  5975. // stopped in Step edit too (round 170e5): it is where the next played note goes (FL enters step-edit notes at the
  5976. // song position, which it draws in the Piano roll), and it moves a snap step on after each one
  5977. if ((playing || engine.isStepEdit()) && ui::showingOrShot (*this))
  5978. {
  5979. const auto& song = engine.getSong();
  5980. // (between two audio blocks it moves on at the song's tempo: smooth at 144 Hz, round 174e)
  5981. tick = transportedit::patternPlayhead (song, song.currentPattern, transport.positionTicks.load() + engine.playheadAdvanceTicks(),
  5982. engine.patternLinearOrigin());
  5983. // round 190im (R13, DL-74): docked in the Clip View for a clip of the grid, the clip's own position while it is
  5984. // launched (Live's manual 8.7) wins over the Playlist's
  5985. if (launchedPlayhead != nullptr)
  5986. if (const auto launched = launchedPlayhead(); launched >= 0.0)
  5987. tick = launched;
  5988. }
  5989. // whenever it moved: the line is anti-aliased, so even a fraction of a pixel shows (zoomed out, a playhead crossing
  5990. // a few pixels a second glides at the display's rate instead of stepping, as FL's does)
  5991. const auto moved = (tick < 0.0) != (playheadTick < 0.0) || std::abs ((tick - playheadTick) * pixelsPerTick) >= 0.002;
  5992. // round 190ip: stopped (step edit keeps it), the playhead is painted again; the overlay goes once that is on screen
  5993. if (gpuPlayhead.isShowing() && (! playing || ! isShowing()))
  5994. {
  5995. gpuPlayhead.hide (tick >= 0.0 && isShowing()); // (gone or no longer shown: at once)
  5996. repaint (playheadColumn (playheadTick));
  5997. }
  5998. if (moved)
  5999. {
  6000. // (old and new column as one rectangle when they overlap: each rectangle of a repaint is a paint)
  6001. auto column = [this] (double t) { return playheadColumn (t); };
  6002. auto dirty = [this] (juce::Rectangle<int> r) {
  6003. if (! r.isEmpty())
  6004. repaint (r);
  6005. };
  6006. const auto before = column (playheadTick);
  6007. playheadTick = tick;
  6008. // while playing the GPU moves it (nothing under it is painted); the frame that starts or ends, the columns are
  6009. // painted once
  6010. const auto gpu = ui::stepMark (gpuPlayhead, playing && tick >= 0.0 && isShowing(), playheadMark(), tick >= 0.0);
  6011. // Follow: a page further when the playhead leaves the view (off: the view stays where it is)
  6012. const auto grid = gridArea();
  6013. // (Pattern mode loops the pattern: the view holds still at its end and comes back in one jump at the wrap;
  6014. // a take with Loop record off, and Song mode, go on past it: plain paging)
  6015. const auto& followSong = engine.getSong();
  6016. const auto loops = followSong.mode == PlayMode::pattern && engine.patternLinearOrigin() < 0.0 && followSong.currentPattern >= 0
  6017. && followSong.currentPattern < (int) followSong.patterns.size();
  6018. const auto loopTicks = loops ? (double) followSong.activePattern().effectiveLength (followSong.meter()) : 0.0;
  6019. const auto newStart = transportedit::followViewStartInLoop (scrollTicks, grid.getWidth() / pixelsPerTick, tick, 20.0 / pixelsPerTick,
  6020. 20.0 / pixelsPerTick, loopTicks);
  6021. if (EditorGlobals::get().followsNow (EditorGlobals::FollowView::pianoRoll) && tick >= 0.0 && newStart != scrollTicks && drag == Drag::none)
  6022. {
  6023. scrollTicks = newStart;
  6024. followSeenScroll = scrollTicks; // (round 190im: not a scroll by hand)
  6025. updateScrollBars();
  6026. repaint();
  6027. if (gpuPlayhead.isShowing())
  6028. gpuPlayhead.show (playheadMark()); // (at its place in the new page)
  6029. }
  6030. else if (gpu.onOverlay && ! gpu.flipped)
  6031. {
  6032. // (the GPU moved it: nothing under it is painted)
  6033. }
  6034. else if (const auto after = column (tick); ! before.isEmpty() && ! after.isEmpty() && std::abs (after.getX() - before.getX()) <= 14)
  6035. dirty (before.getUnion (after));
  6036. else
  6037. {
  6038. dirty (before);
  6039. dirty (after);
  6040. }
  6041. }
  6042. // round 177d: the notes held in a take grow with the playhead (only their rows, from their start)
  6043. if (engine.isLiveRecording() && isShowing())
  6044. {
  6045. juce::Rectangle<int> area;
  6046. for (const auto& n : engine.liveRecording().held)
  6047. {
  6048. const auto x0 = (int) tickToX ((double) n.start) - 2;
  6049. const auto x1 = juce::jmax (x0 + 8, (int) tickToX ((double) (n.start + n.length)) + 8);
  6050. area = area.getUnion (juce::Rectangle<int> (x0, keyToY (n.key), x1 - x0, rowHeight + 1));
  6051. }
  6052. const auto dirty = area.getUnion (liveHeldArea).getIntersection (gridArea());
  6053. liveHeldArea = area;
  6054. if (! dirty.isEmpty())
  6055. repaint (dirty);
  6056. }
  6057. else if (! liveHeldArea.isEmpty())
  6058. {
  6059. repaint (liveHeldArea);
  6060. liveHeldArea = {};
  6061. }
  6062. return playing || moved;
  6063. }
  6064. // --- round 168g: FL's Piano roll File / Edit / View items ----------------------------------------------------------------
  6065. void PianoRollComponent::setTimeSelection (std::int64_t from, std::int64_t to)
  6066. {
  6067. if (from < 0 || to <= from)
  6068. from = to = -1;
  6069. if (from == timeFrom && to == timeTo)
  6070. return;
  6071. timeFrom = from;
  6072. timeTo = to;
  6073. repaint();
  6074. }
  6075. void PianoRollComponent::spaceOperation (int kind)
  6076. {
  6077. // FL needs a time selection for these (FUN_00eb35f0: nothing without one)
  6078. if (timeFrom < 0 || timeTo <= timeFrom)
  6079. {
  6080. ui::postHint ({ tr ("Select a time range on the ruler first (Ctrl+drag)") }, 2000);
  6081. return;
  6082. }
  6083. std::vector<int> channel;
  6084. const auto& notes = currentPattern (engine.getSong()).notes;
  6085. for (int i = 0; i < (int) notes.size(); ++i)
  6086. if (edits (notes[(std::size_t) i]))
  6087. channel.push_back (i);
  6088. const auto from = timeFrom, to = timeTo;
  6089. const auto& song = engine.getSong();
  6090. const auto end = currentPattern (song).effectiveLength (song.meter());
  6091. const auto who = allChannels ? -1 : engine.getSelectedChannel();
  6092. std::vector<int> moved;
  6093. setSelection ({});
  6094. editNotes ([&] (Pattern& p) {
  6095. if (kind == 0 || kind == 1)
  6096. moved = noteedit::insertSpace (p, channel, from, to, kind == 1);
  6097. else if (kind == 2)
  6098. moved = noteedit::deleteSpace (p, channel, from, to);
  6099. else
  6100. noteedit::trimToSelection (p, who, from, to, end);
  6101. noteedit::sortTracking (p, moved);
  6102. });
  6103. if (kind == 3)
  6104. setTimeSelection (-1, -1); // (FL clears the time selection after a trim)
  6105. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  6106. setSelection (moved); // FL selects the notes that moved (FUN_00e3b1a0)
  6107. }
  6108. void PianoRollComponent::insertControllerValue()
  6109. {
  6110. // FL's Ctrl+I (EEInitAction → FUN_00eb38d0): the event lane's control, its current value, at the start of the
  6111. // time selection (or at the pattern's start)
  6112. const auto target = eventLaneTarget();
  6113. if (! target)
  6114. {
  6115. ui::postHint ({ tr ("Show a control's events in the bottom lane first (its box on the left)") }, 2000);
  6116. return;
  6117. }
  6118. const auto value = engine.getSong().targetValue (*target);
  6119. const auto at = timeFrom >= 0 ? timeFrom : (std::int64_t) 0;
  6120. engine.editSong ([&] (Song& s) { eventedit::setEvent (eventedit::laneFor (currentPattern (s), *target), at, value); });
  6121. repaint (velocityArea());
  6122. }
  6123. void PianoRollComponent::deleteAllNotes()
  6124. {
  6125. // FL's Edit › Delete all (FUN_00e3d230): every note of the edited channel in the pattern, one undo step
  6126. std::vector<int> doomed;
  6127. const auto& notes = currentPattern (engine.getSong()).notes;
  6128. for (int i = 0; i < (int) notes.size(); ++i)
  6129. if (edits (notes[(std::size_t) i]))
  6130. doomed.push_back (i);
  6131. if (doomed.empty())
  6132. return;
  6133. setSelection ({});
  6134. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  6135. }
  6136. bool PianoRollComponent::openScore (const juce::File& file)
  6137. {
  6138. juce::MemoryBlock bytes;
  6139. if (! file.loadFileAsData (bytes))
  6140. return false;
  6141. const auto score = prtools::parseScore (std::span<const std::uint8_t> (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize()));
  6142. if (! score)
  6143. return false;
  6144. const auto channel = engine.getSelectedChannel();
  6145. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  6146. return false;
  6147. // FL's score loading (FUN_00ff85c0): the channel's notes in the pattern are replaced by the score's
  6148. const auto loaded = prtools::notesFromScore (*score, channel);
  6149. std::vector<int> added;
  6150. setSelection ({});
  6151. editNotes ([&] (Pattern& p) {
  6152. std::vector<int> old;
  6153. for (int i = 0; i < (int) p.notes.size(); ++i)
  6154. if (p.notes[(std::size_t) i].channel == channel)
  6155. old.push_back (i);
  6156. noteedit::remove (p, old);
  6157. added = noteedit::paste (p, loaded, 0, channel);
  6158. noteedit::sortTracking (p, added);
  6159. });
  6160. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  6161. repaint();
  6162. return true;
  6163. }
  6164. bool PianoRollComponent::saveScore (const juce::File& file) const
  6165. {
  6166. // FL (FUN_0121b1b0): every note of the edited channel; "*.mid" in the same window saves a MIDI file
  6167. const auto& notes = currentPattern (engine.getSong()).notes;
  6168. std::vector<Note> mine;
  6169. for (const auto& n : notes)
  6170. if (n.channel == engine.getSelectedChannel())
  6171. mine.push_back (n);
  6172. if (mine.empty())
  6173. return false;
  6174. if (file.hasFileExtension ("mid;midi"))
  6175. {
  6176. const auto& song = engine.getSong();
  6177. const auto c = engine.getSelectedChannel();
  6178. const auto smf = MidiFileIo::writeNotes (song, mine, c >= 0 && c < (int) song.channels.size() ? song.channels[(std::size_t) c].name : std::string());
  6179. return file.replaceWithData (smf.getData(), smf.getSize());
  6180. }
  6181. const auto bytes = prtools::writeScore (mine);
  6182. return file.replaceWithData (bytes.data(), bytes.size());
  6183. }
  6184. void PianoRollComponent::setNoteClipboard (std::vector<Note> notes)
  6185. {
  6186. clipboard = std::move (notes);
  6187. publishNotes();
  6188. }
  6189. bool PianoRollComponent::copyToMidiClipboard() const
  6190. {
  6191. const auto& song = engine.getSong();
  6192. const auto c = engine.getSelectedChannel();
  6193. std::vector<Note> mine;
  6194. for (const auto& n : currentPattern (song).notes)
  6195. if (n.channel == c)
  6196. mine.push_back (n);
  6197. if (mine.empty())
  6198. return false;
  6199. const auto smf = MidiFileIo::writeNotes (song, mine, c >= 0 && c < (int) song.channels.size() ? song.channels[(std::size_t) c].name : std::string());
  6200. const auto ok = midiclipboard::put (smf);
  6201. ui::postHint ({ ok ? tr ("Copied {0} notes to the MIDI clipboard", { juce::String ((int) mine.size()) }) : tr ("The clipboard is busy: try again") }, 2000);
  6202. return ok;
  6203. }
  6204. void PianoRollComponent::pasteFromMidiClipboard()
  6205. {
  6206. const auto smf = midiclipboard::get();
  6207. if (! smf)
  6208. {
  6209. ui::postHint ({ tr ("There is no MIDI data in the clipboard") }, 2000);
  6210. return;
  6211. }
  6212. juce::String error;
  6213. const auto midi = MidiFileIo::parseBytes (smf->getData(), smf->getSize(), error);
  6214. if (! midi)
  6215. {
  6216. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", tr ("Error parsing the MIDI data..."));
  6217. return;
  6218. }
  6219. importMidi (*midi, tr ("MIDI from clipboard")); // (FL: the same "Import MIDI data" window, FUN_00e1d090)
  6220. }
  6221. bool PianoRollComponent::loadFile (const juce::File& file)
  6222. {
  6223. if (isScoreFile (file))
  6224. return openScore (file);
  6225. if (isMidiFile (file))
  6226. {
  6227. juce::String error;
  6228. const auto midi = MidiFileIo::parseFile (file, error);
  6229. if (! midi)
  6230. {
  6231. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  6232. return true;
  6233. }
  6234. importMidi (*midi, file.getFileName());
  6235. return true;
  6236. }
  6237. if (BrowserComponent::isAudioFile (file))
  6238. {
  6239. loadBackgroundWave (file);
  6240. return true;
  6241. }
  6242. return false;
  6243. }
  6244. bool PianoRollComponent::isInterestedInFileDrag (const juce::StringArray& files)
  6245. {
  6246. for (const auto& f : files)
  6247. if (const juce::File file (f); isScoreFile (file) || isMidiFile (file) || BrowserComponent::isAudioFile (file))
  6248. return true;
  6249. return false;
  6250. }
  6251. void PianoRollComponent::filesDropped (const juce::StringArray& files, int, int)
  6252. {
  6253. for (const auto& f : files)
  6254. if (loadFile (juce::File (f)))
  6255. return;
  6256. }
  6257. bool PianoRollComponent::isInterestedInDragSource (const juce::DragAndDropTarget::SourceDetails& details)
  6258. {
  6259. if (! BrowserComponent::isBrowserDrag (details))
  6260. return false;
  6261. const auto file = BrowserComponent::draggedFile (details);
  6262. return isScoreFile (file) || isMidiFile (file) || BrowserComponent::isAudioFile (file);
  6263. }
  6264. void PianoRollComponent::itemDropped (const juce::DragAndDropTarget::SourceDetails& details)
  6265. {
  6266. loadFile (BrowserComponent::draggedFile (details));
  6267. }
  6268. bool PianoRollComponent::isBackgroundWaveShown() noexcept
  6269. {
  6270. return backgroundWaveOn() && backgroundWave() != nullptr;
  6271. }
  6272. void PianoRollComponent::setBackgroundWaveShown (bool on)
  6273. {
  6274. backgroundWaveOn() = on;
  6275. if (on && backgroundWave() == nullptr)
  6276. ui::postHint ({ tr ("Drop an audio file on the Piano roll to see it as the background waveform") }, 2500);
  6277. repaint();
  6278. }
  6279. void PianoRollComponent::loadBackgroundWave (const juce::File& file)
  6280. {
  6281. // peaks (min / max per 256 samples, every channel) read off the message thread
  6282. juce::Component::SafePointer<PianoRollComponent> safe (this);
  6283. juce::Thread::launch ([file, safe] {
  6284. auto wave = std::make_shared<BackgroundWave>();
  6285. wave->file = file;
  6286. juce::AudioFormatManager formats;
  6287. registerAudioFormats (formats);
  6288. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (file)); reader != nullptr && reader->lengthInSamples > 0)
  6289. {
  6290. wave->sampleRate = reader->sampleRate > 0 ? reader->sampleRate : 44100.0;
  6291. wave->samples = juce::jmin<std::int64_t> (reader->lengthInSamples, (std::int64_t) (wave->sampleRate * 60.0 * 30.0)); // (30 min at most)
  6292. const auto channels = (int) juce::jlimit (1u, 8u, reader->numChannels);
  6293. constexpr int chunk = BackgroundWave::perPeak * 256;
  6294. juce::AudioBuffer<float> buffer (channels, chunk);
  6295. for (std::int64_t pos = 0; pos < wave->samples; pos += chunk)
  6296. {
  6297. const auto n = (int) juce::jmin<std::int64_t> (chunk, wave->samples - pos);
  6298. buffer.clear();
  6299. reader->read (&buffer, 0, n, pos, true, channels > 1);
  6300. for (int b = 0; b < n; b += BackgroundWave::perPeak)
  6301. {
  6302. auto lo = 0.0f, hi = 0.0f;
  6303. const auto m = juce::jmin (BackgroundWave::perPeak, n - b);
  6304. for (int c = 0; c < channels; ++c)
  6305. {
  6306. const auto range = juce::FloatVectorOperations::findMinAndMax (buffer.getReadPointer (c, b), m);
  6307. lo = juce::jmin (lo, range.getStart());
  6308. hi = juce::jmax (hi, range.getEnd());
  6309. }
  6310. wave->lo.push_back (lo);
  6311. wave->hi.push_back (hi);
  6312. }
  6313. }
  6314. }
  6315. juce::MessageManager::callAsync ([safe, wave] {
  6316. if (wave->lo.empty())
  6317. {
  6318. ui::postHint ({ tr ("This audio file could not be read") }, 2000);
  6319. return;
  6320. }
  6321. backgroundWave() = wave;
  6322. backgroundWaveOn() = true; // FL: loading one turns the view on (FUN_00ead950 (1))
  6323. if (safe != nullptr)
  6324. safe->repaint();
  6325. });
  6326. });
  6327. }
  6328. void PianoRollComponent::paintBackgroundWave (juce::Graphics& g, juce::Rectangle<int> grid)
  6329. {
  6330. const auto wave = backgroundWave();
  6331. if (! backgroundWaveOn() || wave == nullptr || wave->lo.empty())
  6332. return;
  6333. // FL (FUN_00e45a00): from the pattern's start, as long as the audio lasts at the song tempo, across the whole grid
  6334. // height (centred, 90% of the half height)
  6335. const auto& song = engine.getSong();
  6336. const auto ticksPerSecond = juce::jmax (1.0, song.bpm) / 60.0 * ppq;
  6337. const auto ticksPerPeak = BackgroundWave::perPeak / wave->sampleRate * ticksPerSecond;
  6338. const auto centre = (float) grid.getCentreY();
  6339. const auto amplitude = (float) grid.getHeight() * 0.5f * 0.9f;
  6340. const auto x0 = juce::jmax (grid.getX(), (int) std::floor (tickToX (0.0)));
  6341. const auto x1 = juce::jmin (grid.getRight(), (int) std::ceil (tickToX ((double) wave->lo.size() * ticksPerPeak)));
  6342. if (x1 <= x0)
  6343. return;
  6344. juce::RectangleList<float> bars;
  6345. for (int x = x0; x < x1; ++x)
  6346. {
  6347. const auto p0 = (std::int64_t) std::floor (xToTick (x) / ticksPerPeak);
  6348. const auto p1 = juce::jmax (p0 + 1, (std::int64_t) std::floor (xToTick (x + 1) / ticksPerPeak));
  6349. auto lo = 0.0f, hi = 0.0f;
  6350. for (auto p = juce::jmax<std::int64_t> (0, p0); p < juce::jmin<std::int64_t> ((std::int64_t) wave->lo.size(), p1); ++p)
  6351. {
  6352. lo = juce::jmin (lo, wave->lo[(std::size_t) p]);
  6353. hi = juce::jmax (hi, wave->hi[(std::size_t) p]);
  6354. }
  6355. const auto top = centre - juce::jlimit (0.0f, 1.0f, hi) * amplitude, bottom = centre - juce::jlimit (-1.0f, 0.0f, lo) * amplitude;
  6356. bars.addWithoutMerging ({ (float) x, top, 1.0f, juce::jmax (1.0f, bottom - top) });
  6357. }
  6358. g.setColour (theme::colour::textPrimary.withAlpha (0.16f));
  6359. g.fillRectList (bars);
  6360. }
  6361. juce::PopupMenu PianoRollComponent::fileMenu()
  6362. {
  6363. // FL's EEFileMenu (DFM): Open score, Browse scores, Save score as | Import / Export MIDI, Paste from / Copy to MIDI
  6364. // clipboard
  6365. juce::PopupMenu menu;
  6366. menu.addItem (theme::mnemonic (tr ("Open score..."), 'O') + keyText ("pianoRoll.openScore"), [this] { runAction ("pianoRoll.openScore"); });
  6367. menu.addItem (theme::mnemonic (tr ("Browse scores"), 'B') + keyText ("pianoRoll.browseScores"), onBrowseScores != nullptr, false, [this] { runAction ("pianoRoll.browseScores"); });
  6368. menu.addItem (theme::mnemonic (tr ("Save score as..."), 'S') + keyText ("pianoRoll.saveScore"), [this] { runAction ("pianoRoll.saveScore"); });
  6369. menu.addSeparator();
  6370. menu.addItem (theme::mnemonic (tr ("Import MIDI file..."), 'I') + keyText ("pianoRoll.importMidi"), [this] { runAction ("pianoRoll.importMidi"); });
  6371. menu.addItem (theme::mnemonic (tr ("Export as MIDI file..."), 'E') + keyText ("pianoRoll.exportMidi"), [this] { runAction ("pianoRoll.exportMidi"); });
  6372. menu.addItem (theme::mnemonic (tr ("Paste from MIDI clipboard..."), 'P') + keyText ("pianoRoll.pasteMidiClipboard"), midiclipboard::hasMidi(), false,
  6373. [this] { runAction ("pianoRoll.pasteMidiClipboard"); });
  6374. menu.addItem (theme::mnemonic (tr ("Copy to MIDI clipboard"), 'C') + keyText ("pianoRoll.copyMidiClipboard"), [this] { runAction ("pianoRoll.copyMidiClipboard"); });
  6375. return menu;
  6376. }
  6377. juce::PopupMenu PianoRollComponent::editMenu()
  6378. {
  6379. // FL's EEEditMenu, the items that apply to notes (DFM; Shift / Transpose = the arrow keys, round 167j)
  6380. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  6381. const auto grid = gridTicks();
  6382. juce::PopupMenu menu;
  6383. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", ! selection.empty(), false, [this] { copySelection(); deleteSelection(); });
  6384. menu.addItem (theme::mnemonic (tr ("Copy"), 'C') + "\tCtrl+C", [this] { copySelection(); });
  6385. menu.addItem (tr ("Copy ghost notes"), ! visibleGhostNotes().empty(), false, [this] { copyGhostNotes(); }); // (LYNX, round 177d)
  6386. menu.addItem (theme::mnemonic (tr ("Paste"), 'P') + "\tCtrl+V", ! clipboard.empty() || windowclip::hasIncoming (crossclipboard::Kind::notes), false,
  6387. [this] { paste(); });
  6388. menu.addItem (theme::mnemonic (tr ("Duplicate"), 'u') + "\tCtrl+B", [this] { duplicateSelection(); });
  6389. menu.addItem (theme::mnemonic (tr ("Delete"), 'D') + "\tDel", ! selection.empty(), false, [this] { deleteSelection(); });
  6390. menu.addItem (theme::mnemonic (tr ("Delete all"), 'a') + keyText ("pianoRoll.deleteAll"), [this] { runAction ("pianoRoll.deleteAll"); });
  6391. menu.addSeparator();
  6392. menu.addItem (tr ("Shift left") + "\tShift+Left", ! selection.empty(), false, [this, grid] { nudge (-grid, 0); });
  6393. menu.addItem (tr ("Shift right") + "\tShift+Right", ! selection.empty(), false, [this, grid] { nudge (grid, 0); });
  6394. menu.addItem (tr ("Transpose up") + "\tShift+Up", ! selection.empty(), false, [this] { nudge (0, 1); });
  6395. menu.addItem (tr ("Transpose down") + "\tShift+Down", ! selection.empty(), false, [this] { nudge (0, -1); });
  6396. menu.addItem (tr ("Transpose one octave up") + "\tCtrl+Up", ! selection.empty(), false, [this] { nudge (0, 12); });
  6397. menu.addItem (tr ("Transpose one octave down") + "\tCtrl+Down", ! selection.empty(), false, [this] { nudge (0, -12); });
  6398. menu.addSeparator();
  6399. menu.addItem (tr ("Insert space") + keyText ("pianoRoll.insertSpace"), hasTime, false, [this] { runAction ("pianoRoll.insertSpace"); });
  6400. menu.addItem (tr ("Slice & insert space") + keyText ("pianoRoll.sliceInsertSpace"), hasTime, false, [this] { runAction ("pianoRoll.sliceInsertSpace"); });
  6401. menu.addItem (tr ("Delete space") + keyText ("pianoRoll.deleteSpace"), hasTime, false, [this] { runAction ("pianoRoll.deleteSpace"); });
  6402. menu.addItem (tr ("Trim") + keyText ("pianoRoll.trimSpace"), hasTime, false, [this] { runAction ("pianoRoll.trimSpace"); });
  6403. menu.addSeparator();
  6404. menu.addItem (tr ("Insert current controller value") + keyText ("pianoRoll.insertControllerValue"), eventLaneTarget().has_value(), false,
  6405. [this] { runAction ("pianoRoll.insertControllerValue"); });
  6406. return menu;
  6407. }
  6408. juce::PopupMenu PianoRollComponent::stampMenu()
  6409. {
  6410. // the toolbar chord box's items, the chosen one ticked ("Note" = no stamp: single notes)
  6411. juce::PopupMenu menu;
  6412. for (int i = 0; i < chordBox.getNumItems(); ++i)
  6413. {
  6414. const auto id = chordBox.getItemId (i);
  6415. if (id == degreeStampId) // round 190nu: the Scale degree chord, its options beside it
  6416. {
  6417. menu.addItem (chordBox.getItemText (i), true, isDegreeStamp(), [this] { setDegreeStamp (true); });
  6418. menu.addSubMenu (tr ("Scale degree chord options"), degreeOptionsMenu());
  6419. menu.addSeparator();
  6420. continue;
  6421. }
  6422. menu.addItem (chordBox.getItemText (i) + (id == 1 ? keyText ("pianoRoll.stampNone") : juce::String()), true, chordBox.getSelectedId() == id,
  6423. [this, id] { chordBox.setSelectedId (id, juce::sendNotificationSync); });
  6424. }
  6425. return menu;
  6426. }
  6427. juce::PopupMenu PianoRollComponent::viewMenu()
  6428. {
  6429. // FL's EEViewMenu, its "Helpers" items (DFM)
  6430. juce::PopupMenu menu;
  6431. menu.addItem (tr ("Note grid highlights") + keyText ("pianoRoll.gridHighlights"), true, gridHighlights, [this] { runAction ("pianoRoll.gridHighlights"); });
  6432. menu.addSubMenu (tr ("Scale highlighting"), scaleHighlightMenu()); // (round 190jv; FL's EEAutoKeyMenu)
  6433. menu.addItem (tr ("Show chord name for selection") + keyText ("pianoRoll.showChordName"), true, showChordName,
  6434. [this] { runAction ("pianoRoll.showChordName"); });
  6435. menu.addItem (tr ("Background waveform") + keyText ("pianoRoll.backgroundWave"), true, isBackgroundWaveShown(),
  6436. [this] { runAction ("pianoRoll.backgroundWave"); });
  6437. menu.addItem (tr ("Ruler: song bars (LYNX)") + keyText ("pianoRoll.songBarsRuler"), true, songBarsRuler, [this] { runAction ("pianoRoll.songBarsRuler"); });
  6438. // round 190pf (research190oe P13): the rows light the Chord lane's chord at the song position
  6439. menu.addItem (tr ("Highlight the Chord lane's chord (LYNX)"), true, chordlane::pianoRollHighlight(), [this] {
  6440. workflowextras::setExtra ("pianoRoll.chordHighlight", ! chordlane::pianoRollHighlight());
  6441. repaint();
  6442. });
  6443. if (layoutstyle::current() != layoutstyle::Style::clipLaunch) // (round 190on: the Clip-launch layout always offers them)
  6444. menu.addItem (tr ("Stacked controller lanes (LYNX)") + keyText ("pianoRoll.stackedLanes"), true, stackedLanesExtra,
  6445. [this] { runAction ("pianoRoll.stackedLanes"); });
  6446. {
  6447. // round 190j (discussion #136): flat = LYNX's keyboard until round 190oo; "Piano keys" = FL 2026's own keyboard
  6448. // (the white keys meet behind the black ones, with lines only between B / C and E / F: flshots/fl-pr-keys-x3.png),
  6449. // the default since round 190oo (O-2); the lined piano keys stay as they were
  6450. juce::PopupMenu style;
  6451. const auto add = [this, &style] (const juce::String& name, pianokeys::Style value) {
  6452. style.addItem (name, true, keyStyle == value, [this, value] { setKeyStyle (value); });
  6453. };
  6454. add (tr ("Flat keys"), pianokeys::Style::flat);
  6455. add (tr ("Piano keys"), pianokeys::Style::fl);
  6456. add (tr ("Piano keys (lines between the white keys)"), pianokeys::Style::piano);
  6457. menu.addSubMenu (tr ("Keyboard style"), style);
  6458. }
  6459. if (const auto wave = backgroundWave())
  6460. menu.addItem (tr ("Remove the background waveform ({0})", { wave->file.getFileName() }), [this] {
  6461. backgroundWave().reset();
  6462. backgroundWaveOn() = false;
  6463. repaint();
  6464. });
  6465. return menu;
  6466. }
  6467. // FL's View › Scale highlighting (EEAutoKeyMenu, round 190jv): in FL's DFM order — "Root note" and the twelve roots,
  6468. // "Scale", Snap to scale, FL's Default / Black notes (LYNX: "No scale", the black-key rows) and Automatic; FL appends
  6469. // its Reference scales after the last of them, here LYNX's scale list (the toolbar scale box's). The roots apply to a
  6470. // chosen scale, so they wait for one.
  6471. juce::PopupMenu PianoRollComponent::scaleHighlightMenu()
  6472. {
  6473. juce::PopupMenu menu;
  6474. const auto scale = scaleIndex(), root = scaleRoot();
  6475. menu.addSectionHeader (tr ("Root note"));
  6476. for (int r = 0; r < 12; ++r)
  6477. menu.addItem (juce::String (notenames::pitchName (r)), scale > 0, scale > 0 && root == r, [this, r, scale] { setScale (r, scale); });
  6478. // issue #203 (round 190ll): FL draws the roots and the scales in two columns ("Root note" | "Scale"; live190cq
  6479. // curves190bw-05c-scale-highlighting-menu.png), the toolbar's scale box opens this menu too
  6480. menu.addColumnBreak();
  6481. menu.addSectionHeader (tr ("Scale"));
  6482. menu.addItem (tr ("Snap notes to the scale") + keyText ("pianoRoll.scaleSnap"), scale > 0, scaleSnap, [this] { setScaleSnap (! scaleSnap); });
  6483. // FL's radio group Default / Black notes / Automatic (round 190mq, issue #212: Default = no black-key rows)
  6484. menu.addItem (tr ("Default"), true, scaleBox.getSelectedId() == 1 && ! blackKeyRows, [this] {
  6485. blackKeyRows = false;
  6486. setScale (0, 0);
  6487. repaint();
  6488. });
  6489. menu.addItem (tr (notetools::scales()[0].name), true, scaleBox.getSelectedId() == 1 && blackKeyRows, [this] {
  6490. blackKeyRows = true;
  6491. setScale (0, 0);
  6492. repaint();
  6493. });
  6494. menu.addItem (tr ("Automatic"), true, isAutoScale(), [this] { setAutoScale (true); });
  6495. menu.addSeparator();
  6496. for (int s = 1; s < (int) notetools::scales().size(); ++s)
  6497. menu.addItem (tr (notetools::scales()[(std::size_t) s].name), true, scale == s, [this, s, root] { setScale (root, s); });
  6498. return menu;
  6499. }
  6500. // --- round 190nu: the Scale degree chord's ghost and its preview (core/KeyRegions.h) -----------------------------------
  6501. juce::Rectangle<int> PianoRollComponent::degreeGhostArea() const
  6502. {
  6503. if (degreeGhost.tick < 0 || degreeGhost.keys.empty())
  6504. return {};
  6505. const auto lo = *std::min_element (degreeGhost.keys.begin(), degreeGhost.keys.end());
  6506. const auto hi = *std::max_element (degreeGhost.keys.begin(), degreeGhost.keys.end());
  6507. const auto x = (int) tickToX ((double) degreeGhost.tick);
  6508. const auto w = juce::jmax (6, (int) ((double) degreeGhost.length * pixelsPerTick)) + 200; // (and its label)
  6509. return juce::Rectangle<int>::leftTopRightBottom (x - 2, keyToY (hi) - 22, x + w, keyToY (lo) + rowHeight + 22).getIntersection (gridArea());
  6510. }
  6511. void PianoRollComponent::clearDegreeGhost()
  6512. {
  6513. stopDegreeHear();
  6514. if (degreeGhost.tick < 0)
  6515. return;
  6516. repaint (degreeGhostArea());
  6517. degreeGhost = {};
  6518. }
  6519. void PianoRollComponent::updateDegreeGhost (juce::Point<int> at)
  6520. {
  6521. const auto tool = tools.getTool();
  6522. bool right = false;
  6523. if (! isDegreeStamp() || drag != Drag::none || ! gridArea().contains (at) || (tool != EditTool::pencil && tool != EditTool::brush)
  6524. || noteAt (at.x, at.y, right) >= 0)
  6525. return clearDegreeGhost();
  6526. DegreeGhost next;
  6527. next.tick = juce::jmax<std::int64_t> (0, snap (xToTick (at.x), true));
  6528. next.length = newNoteLength();
  6529. const auto clicked = yToKey (at.y);
  6530. next.keys = stampKeys (clicked, next.tick);
  6531. const auto scale = scaleDegreesAt (next.tick);
  6532. if (! scale.valid())
  6533. next.label = tr ("No key here: add a key marker (Time markers) or choose a scale");
  6534. else
  6535. {
  6536. int root = clicked;
  6537. const auto shape = keyregions::diatonicChord (scale, clicked, degreeSize, degreeInversion, root);
  6538. std::vector<int> keys;
  6539. for (const auto i : shape)
  6540. keys.push_back (root + i);
  6541. const auto numeral = keyregions::degreeNumeral (scale, root, keys, degreeSize);
  6542. const auto detected = prtools::detectChord (keys, notenames::currentFlats.load() || keyregions::prefersFlats (scale));
  6543. next.label = juce::String::fromUTF8 (numeral.c_str()) + (detected ? juce::String::fromUTF8 (" \xc2\xb7 ") + juce::String::fromUTF8 (detected->name.c_str()) : juce::String());
  6544. }
  6545. if (next.tick == degreeGhost.tick && next.keys == degreeGhost.keys && next.label == degreeGhost.label)
  6546. return;
  6547. repaint (degreeGhostArea());
  6548. degreeGhost = std::move (next);
  6549. repaint (degreeGhostArea());
  6550. // the preview: the chord sounds once the mouse rests on it (a quarter of a second), not while it moves on
  6551. stopDegreeHear();
  6552. if (degreeHear && scale.valid())
  6553. {
  6554. degreeHearStage = 0;
  6555. degreeHearTimer.startTimer (300);
  6556. }
  6557. }
  6558. void PianoRollComponent::degreeHearStep()
  6559. {
  6560. for (const auto k : degreeSounding)
  6561. engine.sendLiveNote (degreeSoundingChannel, k, 0.0f, false);
  6562. degreeSounding.clear();
  6563. if (degreeHearStage == 0 && degreeGhost.tick >= 0)
  6564. {
  6565. degreeSoundingChannel = engine.getSelectedChannel();
  6566. for (const auto k : degreeGhost.keys)
  6567. {
  6568. engine.sendLiveNote (degreeSoundingChannel, k, noteTemplate.velocity, true);
  6569. degreeSounding.push_back (k);
  6570. }
  6571. degreeHearStage = 1;
  6572. degreeHearTimer.startTimer (700); // (how long it sounds)
  6573. return;
  6574. }
  6575. degreeHearTimer.stopTimer();
  6576. }
  6577. void PianoRollComponent::stopDegreeHear()
  6578. {
  6579. degreeHearTimer.stopTimer();
  6580. for (const auto k : degreeSounding)
  6581. engine.sendLiveNote (degreeSoundingChannel, k, 0.0f, false);
  6582. degreeSounding.clear();
  6583. degreeHearStage = 0;
  6584. }
  6585. juce::PopupMenu PianoRollComponent::degreeOptionsMenu()
  6586. {
  6587. juce::PopupMenu menu;
  6588. const auto pick = [this] (keyregions::DegreeSize size) {
  6589. degreeSize = size;
  6590. degreeGhost.label.clear(); // (the ghost takes the new shape at the next mouse move)
  6591. if (mixeroptions::changed) mixeroptions::changed(); // (saved with the UI options)
  6592. };
  6593. menu.addSectionHeader (tr ("Chord"));
  6594. menu.addItem (tr ("Triad"), true, degreeSize == keyregions::DegreeSize::triad, [pick] { pick (keyregions::DegreeSize::triad); });
  6595. menu.addItem (tr ("6th"), true, degreeSize == keyregions::DegreeSize::sixth, [pick] { pick (keyregions::DegreeSize::sixth); });
  6596. menu.addItem (tr ("7th"), true, degreeSize == keyregions::DegreeSize::seventh, [pick] { pick (keyregions::DegreeSize::seventh); });
  6597. menu.addItem (tr ("9th"), true, degreeSize == keyregions::DegreeSize::ninth, [pick] { pick (keyregions::DegreeSize::ninth); });
  6598. menu.addSectionHeader (tr ("Inversion"));
  6599. const char* names[] = { TR_NOOP ("Root position"), TR_NOOP ("1st inversion"), TR_NOOP ("2nd inversion"), TR_NOOP ("3rd inversion"), TR_NOOP ("4th inversion") };
  6600. const auto most = degreeSize == keyregions::DegreeSize::triad ? 2 : degreeSize == keyregions::DegreeSize::ninth ? 4 : 3;
  6601. for (int i = 0; i <= most; ++i)
  6602. menu.addItem (tr (names[i]), true, degreeInversion == i, [this, i] {
  6603. degreeInversion = i;
  6604. if (mixeroptions::changed) mixeroptions::changed();
  6605. });
  6606. menu.addSeparator();
  6607. menu.addItem (tr ("Hear the chord before clicking"), true, degreeHear, [this] {
  6608. degreeHear = ! degreeHear;
  6609. if (! degreeHear)
  6610. stopDegreeHear();
  6611. if (mixeroptions::changed) mixeroptions::changed();
  6612. });
  6613. return menu;
  6614. }
  6615. // FL's key menu (View › Scale highlighting's, on a key marker: "Root note" and "Scale" side by side; Default and Black
  6616. // 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
  6617. juce::PopupMenu PianoRollComponent::keyChoiceMenu (const keyregions::State& current, std::function<void (keyregions::State)> pick)
  6618. {
  6619. juce::PopupMenu menu;
  6620. const auto isKey = current.kind == keyregions::State::key;
  6621. const auto root = isKey ? current.value.root : juce::jmax (0, scaleTonic());
  6622. const auto scale = isKey ? current.value.flScale : keyregions::majorScale();
  6623. menu.addSectionHeader (tr ("Root note"));
  6624. for (int r = 0; r < 12; ++r)
  6625. menu.addItem (juce::String (notenames::pitchName (r)), true, isKey && root == r,
  6626. [pick, r, scale] { pick ({ keyregions::State::key, { r, scale } }); });
  6627. menu.addColumnBreak();
  6628. menu.addSectionHeader (tr ("Scale"));
  6629. menu.addItem (tr ("Default"), true, current.kind == keyregions::State::editor, [pick] { pick ({ keyregions::State::editor, {} }); });
  6630. menu.addItem (tr ("Black notes"), true, current.kind == keyregions::State::none, [pick] { pick ({ keyregions::State::none, {} }); });
  6631. menu.addSeparator();
  6632. const auto& list = notetools::flReferenceScales();
  6633. for (int k = 0; k < (int) list.size(); ++k) // (in FL's menu order: rollup 0.1.31 step 3)
  6634. {
  6635. const auto i = notetools::flMenuScaleIndex (k);
  6636. menu.addItem (tr (list[(std::size_t) i].name), true, isKey && scale == i, [pick, root, i] { pick ({ keyregions::State::key, { root, i } }); });
  6637. }
  6638. return menu;
  6639. }
  6640. // --- the pattern's time markers (round 168g, docs/analise/REA_rodada168g.md §M13) --------------------------------------
  6641. juce::PopupMenu PianoRollComponent::markersMenu()
  6642. {
  6643. // FL's EEMarkerMenu (the Piano roll shows the Playlist's Time markers items, on the pattern's own markers)
  6644. juce::PopupMenu menu;
  6645. menu.addItem (tr ("Add one...") + keyText ("pianoRoll.markerAdd"), [this] { runAction ("pianoRoll.markerAdd"); });
  6646. menu.addItem (tr ("Add auto") + keyText ("pianoRoll.markerAuto"), [this] { runAction ("pianoRoll.markerAuto"); });
  6647. menu.addItem (tr ("Add time signature change...") + keyText ("pianoRoll.markerSignature"), [this] { runAction ("pianoRoll.markerSignature"); });
  6648. {
  6649. // round 190nu: FL's "Add key marker" (at the time selection's start, else the playhead, as the other markers here)
  6650. // and LYNX's key region over the time selection (its end brings back what was there)
  6651. const auto tick = markerKeyTick();
  6652. const auto here = keyregions::stateAt (currentPattern (engine.getSong()), tick);
  6653. menu.addSubMenu (tr ("Add key marker"), keyChoiceMenu (here, [this, tick] (keyregions::State s) { addKeyMarker (tick, s); }));
  6654. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  6655. const auto from = timeFrom, to = timeTo;
  6656. menu.addSubMenu (tr ("Key region for the time selection"),
  6657. keyChoiceMenu (hasTime ? keyregions::stateAt (currentPattern (engine.getSong()), from) : here,
  6658. [this, from, to] (keyregions::State s) { addKeyRegion (from, to, s); }),
  6659. hasTime);
  6660. }
  6661. const auto any = ! currentPattern (engine.getSong()).markers.empty();
  6662. menu.addSeparator();
  6663. menu.addItem (tr ("Delete all markers"), any, false, [this] {
  6664. engine.editSong ([] (Song& s) { currentPattern (s).markers.clear(); });
  6665. repaint();
  6666. });
  6667. return menu;
  6668. }
  6669. std::int64_t PianoRollComponent::markerKeyTick() const
  6670. {
  6671. // like the Playlist's (FL FUN_0122b0d0 / FUN_01229d20): the time selection's start; else the playhead when it is
  6672. // in view; else the bar line nearest the view's left edge
  6673. if (timeFrom >= 0 && timeTo > timeFrom)
  6674. return timeFrom;
  6675. const auto left = std::max (0.0, scrollTicks);
  6676. const auto right = xToTick (gridArea().getRight());
  6677. if (playheadTick >= left && playheadTick <= right)
  6678. return (std::int64_t) playheadTick;
  6679. const auto bar = engine.getSong().barTicks();
  6680. const auto at = (std::int64_t) left;
  6681. return at % bar > bar / 2 ? (at / bar + 1) * bar : at / bar * bar;
  6682. }
  6683. void PianoRollComponent::editPatternMarker (std::int64_t tick, int existing)
  6684. {
  6685. const auto& markers = currentPattern (engine.getSong()).markers;
  6686. const auto current = existing >= 0 && existing < (int) markers.size() ? juce::String::fromUTF8 (markers[(std::size_t) existing].name.c_str())
  6687. : tr ("Marker");
  6688. // FL's "Marker name" prompt
  6689. auto* window = new juce::AlertWindow (existing >= 0 ? tr ("Rename marker") : tr ("New marker"), {}, juce::MessageBoxIconType::NoIcon, this);
  6690. window->addTextEditor ("name", current);
  6691. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6692. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6693. juce::Component::SafePointer<PianoRollComponent> safe (this);
  6694. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, tick, existing, window] (int result) {
  6695. if (result != 1 || safe == nullptr)
  6696. return;
  6697. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  6698. safe->engine.editSong ([tick, existing, name] (Song& s) {
  6699. auto& p = currentPattern (s);
  6700. if (existing < 0)
  6701. noteedit::addPatternMarker (p, { tick, name, 0, 4 });
  6702. else if (existing < (int) p.markers.size())
  6703. p.markers[(std::size_t) existing].name = name;
  6704. });
  6705. safe->repaint();
  6706. }),
  6707. true);
  6708. }
  6709. void PianoRollComponent::addPatternSignatureByKey()
  6710. {
  6711. const auto& song = engine.getSong();
  6712. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  6713. const auto from = hasTime ? timeFrom : snap ((double) markerKeyTick(), true);
  6714. const auto to = hasTime ? timeTo : (std::int64_t) -1;
  6715. const auto current = noteedit::patternSignatureAt (currentPattern (song), from, song.meter());
  6716. auto* window = new juce::AlertWindow (tr ("Add time signature change..."), {}, juce::MessageBoxIconType::NoIcon, this);
  6717. juce::StringArray numerators, denominators;
  6718. for (int n = 1; n <= 32; ++n)
  6719. numerators.add (juce::String (n));
  6720. for (int d : { 1, 2, 4, 8, 16, 32 })
  6721. denominators.add (juce::String (d));
  6722. window->addComboBox ("numerator", numerators, tr ("Numerator"));
  6723. window->addComboBox ("denominator", denominators, tr ("Denominator"));
  6724. window->getComboBoxComponent ("numerator")->setText (juce::String (current.first), juce::dontSendNotification);
  6725. window->getComboBoxComponent ("denominator")->setText (juce::String (current.second), juce::dontSendNotification);
  6726. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6727. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6728. juce::Component::SafePointer<PianoRollComponent> safe (this);
  6729. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, from, to, window] (int result) {
  6730. if (result != 1 || safe == nullptr)
  6731. return;
  6732. const auto n = window->getComboBoxComponent ("numerator")->getText().getIntValue();
  6733. const auto d = window->getComboBoxComponent ("denominator")->getText().getIntValue();
  6734. safe->engine.editSong ([from, to, n, d] (Song& s) {
  6735. noteedit::addPatternSignatureChange (currentPattern (s), from, to, n, d, s.meter());
  6736. });
  6737. safe->repaint();
  6738. }),
  6739. true);
  6740. }
  6741. int PianoRollComponent::markerAtX (int x) const
  6742. {
  6743. // the flag and the name to its right (the last one drawn wins, as it is on top)
  6744. const auto& markers = currentPattern (engine.getSong()).markers;
  6745. for (int i = (int) markers.size() - 1; i >= 0; --i)
  6746. {
  6747. const auto mx = (int) tickToX ((double) markers[(std::size_t) i].tick);
  6748. if (x >= mx - 3 && x <= mx + 60)
  6749. return i;
  6750. }
  6751. return -1;
  6752. }
  6753. void PianoRollComponent::showPatternMarkerMenu (int index)
  6754. {
  6755. patternMarkerMenu (index).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  6756. }
  6757. juce::PopupMenu PianoRollComponent::patternMarkerMenu (int index)
  6758. {
  6759. juce::PopupMenu menu;
  6760. const auto& markers = currentPattern (engine.getSong()).markers;
  6761. if (index >= 0 && index < (int) markers.size()) // (FL's heading: "C Minor Natural (Aeolian) - Key/Scale at 3:01:00")
  6762. {
  6763. const auto& m = markers[(std::size_t) index];
  6764. auto title = juce::String::fromUTF8 (m.name.c_str());
  6765. if (m.action != 0)
  6766. title += " - " + tr (markers::actionName (m.action));
  6767. menu.addSectionHeader (title);
  6768. }
  6769. menu.addItem (tr ("Rename marker..."), [this, index] { editPatternMarker (0, index); });
  6770. menu.addItem (tr ("Delete marker"), [this, index] {
  6771. engine.editSong ([index] (Song& s) {
  6772. auto& markers = currentPattern (s).markers;
  6773. if (index >= 0 && index < (int) markers.size())
  6774. markers.erase (markers.begin() + index);
  6775. });
  6776. repaint();
  6777. });
  6778. // round 190nu: FL's Action › Key/scale (on any marker: it becomes a key marker, named after its key)
  6779. if (index >= 0 && index < (int) markers.size())
  6780. {
  6781. const auto& m = markers[(std::size_t) index];
  6782. const auto now = keyregions::isKeyMarker (m) ? keyregions::stateOf (m) : keyregions::stateAt (currentPattern (engine.getSong()), m.tick);
  6783. menu.addSubMenu (tr ("Key/scale"), keyChoiceMenu (now, [this, index] (keyregions::State s) {
  6784. engine.editSong ([index, s] (Song& song) {
  6785. auto& list = currentPattern (song).markers;
  6786. if (index >= 0 && index < (int) list.size())
  6787. keyregions::setState (list[(std::size_t) index], s);
  6788. });
  6789. repaint();
  6790. }),
  6791. true, juce::Image(), keyregions::isKeyMarker (m));
  6792. }
  6793. menu.addSeparator();
  6794. menu.addSubMenu (tr ("Time markers"), markersMenu());
  6795. return menu;
  6796. }
  6797. // --- MPE lanes (round 190hy, issue #108; core/NoteCurves.h, docs/analise/REA_rodada190hy-mpe.md) -------------------
  6798. // Each note's own pitch bend / slide / pressure curve, edited as Live 11+ edits its note expression: the lane shows the
  6799. // curves over the notes' lengths (the selected notes brighter), a drag draws the curve of the note under the mouse (a
  6800. // selected one first), a point is dragged to move it and double-clicked to delete it; LYNX's own lane gestures on top
  6801. // (right-drag erases, Alt+click clears). FL 2026 has no per-note curves (FLEngine / Fruity Wrapper strings: none).
  6802. void PianoRollComponent::setMpeView (bool on)
  6803. {
  6804. if (mpeStacked == on)
  6805. return;
  6806. mpeStacked = on;
  6807. // (three lanes need room: the Clip-launch dock's 30 px lane grows while the MPE tab shows)
  6808. if (fitKeysToNotes && ! on)
  6809. velocityHeight = compactVelocityHeight; // (on: layoutEventPane sizes the three lanes)
  6810. resized();
  6811. repaint();
  6812. }
  6813. std::vector<std::pair<juce::Rectangle<int>, int>> PianoRollComponent::mpeLaneAreas() const
  6814. {
  6815. std::vector<std::pair<juce::Rectangle<int>, int>> out;
  6816. const auto lane = velocityArea();
  6817. if (lane.getHeight() < 12)
  6818. return out;
  6819. if (mpeStacked) // (round 190jd: the lanes the "Show Lane:" menu checks, stacked in its order, over the footer)
  6820. {
  6821. auto rest = lane.withTrimmedBottom (mpetab::footerHeight);
  6822. const auto shown = mpetab::shownLanes (mpeShownLanes);
  6823. const auto h = rest.getHeight() / juce::jmax (1, (int) shown.size());
  6824. for (std::size_t k = 0; k < shown.size(); ++k)
  6825. out.push_back ({ k + 1 < shown.size() ? rest.removeFromTop (h) : rest, mpeLaneIdOf (shown[k]) });
  6826. }
  6827. else if (isMpeLane (laneId()))
  6828. out.push_back ({ lane, laneId() });
  6829. return out;
  6830. }
  6831. int PianoRollComponent::mpeLaneAt (juce::Point<int> p, juce::Rectangle<int>* area) const
  6832. {
  6833. for (const auto& [r, id] : mpeLaneAreas())
  6834. if (r.contains (p))
  6835. {
  6836. if (area != nullptr)
  6837. *area = r;
  6838. return id;
  6839. }
  6840. return 0;
  6841. }
  6842. float PianoRollComponent::mpePitchRange() const
  6843. {
  6844. // ±12 semitones, or ±24 / ±48 when a shown note's curve goes further (Live's lane spans the MPE range, ±48)
  6845. auto reach = 0.0f;
  6846. const auto& notes = currentPattern (engine.getSong()).notes;
  6847. for (auto i : channelNotes())
  6848. if (const auto& n = notes[(std::size_t) i]; n.curves.has())
  6849. for (const auto& q : n.curves->lane (NoteCurveLane::pitch))
  6850. reach = juce::jmax (reach, std::abs (q.value));
  6851. return reach <= 1200.0f ? 1200.0f : reach <= 2400.0f ? 2400.0f : notecurves::maxPitchCents;
  6852. }
  6853. float PianoRollComponent::mpeNorm (int lane, float value, float range) const noexcept
  6854. {
  6855. return lane == laneMpePitch ? juce::jlimit (0.0f, 1.0f, 0.5f + value / (2.0f * range)) : juce::jlimit (0.0f, 1.0f, value);
  6856. }
  6857. float PianoRollComponent::mpeValue (int lane, float norm, float range) const noexcept
  6858. {
  6859. norm = juce::jlimit (0.0f, 1.0f, norm);
  6860. if (lane != laneMpePitch)
  6861. return norm;
  6862. const auto cents = (norm - 0.5f) * 2.0f * range;
  6863. return std::abs (cents) < range * 0.015f ? 0.0f : std::round (cents); // (snaps to no bend; whole cents)
  6864. }
  6865. float PianoRollComponent::mpeBase (int lane, const Note& n) noexcept
  6866. {
  6867. return lane == laneMpePitch ? 0.0f : lane == laneMpeSlide ? n.modX : mpe::pressureOfModY (n.modY);
  6868. }
  6869. int PianoRollComponent::mpeNoteAt (int x) const
  6870. {
  6871. const auto tick = xToTick (x);
  6872. const auto& notes = currentPattern (engine.getSong()).notes;
  6873. auto best = -1;
  6874. auto bestSelected = false;
  6875. for (auto i : channelNotes())
  6876. {
  6877. const auto& n = notes[(std::size_t) i];
  6878. if (tick < (double) n.start || tick >= (double) (n.start + n.length))
  6879. continue;
  6880. const auto selected = isSelected (i);
  6881. if (best < 0 || (selected && ! bestSelected)
  6882. || (selected == bestSelected && n.start >= notes[(std::size_t) best].start))
  6883. {
  6884. best = i;
  6885. bestSelected = selected;
  6886. }
  6887. }
  6888. return best;
  6889. }
  6890. int PianoRollComponent::mpePointAt (int note, int lane, juce::Rectangle<int> area, juce::Point<int> p, float range) const
  6891. {
  6892. const auto& notes = currentPattern (engine.getSong()).notes;
  6893. if (note < 0 || note >= (int) notes.size() || ! notes[(std::size_t) note].curves.has())
  6894. return -1;
  6895. const auto& n = notes[(std::size_t) note];
  6896. const auto usable = (float) area.getHeight() - 8.0f;
  6897. const auto& points = n.curves->lane ((NoteCurveLane) (lane - laneMpePitch));
  6898. auto best = -1;
  6899. auto bestDistance = 6.0f;
  6900. for (int k = 0; k < (int) points.size(); ++k)
  6901. {
  6902. const auto x = (float) tickToX ((double) n.start + (double) points[(std::size_t) k].tick);
  6903. const auto y = (float) area.getBottom() - 2.0f - usable * mpeNorm (lane, points[(std::size_t) k].value, range);
  6904. if (const auto d = juce::jmax (std::abs (x - (float) p.x), std::abs (y - (float) p.y)); d < bestDistance)
  6905. {
  6906. bestDistance = d;
  6907. best = k;
  6908. }
  6909. }
  6910. return best;
  6911. }
  6912. void PianoRollComponent::paintMpeLane (juce::Graphics& g, juce::Rectangle<int> area, int lane, float range)
  6913. {
  6914. using namespace theme::colour;
  6915. juce::Graphics::ScopedSaveState state (g);
  6916. g.reduceClipRegion (area);
  6917. const auto& notes = currentPattern (engine.getSong()).notes;
  6918. const auto usable = (float) area.getHeight() - 8.0f;
  6919. const auto yOf = [&] (float norm) { return (float) area.getBottom() - 2.0f - usable * norm; };
  6920. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  6921. if (mpeStacked && lane != laneMpePitch) // (the stacked lanes' dividers)
  6922. {
  6923. g.setColour (border);
  6924. g.drawHorizontalLine (area.getY(), (float) area.getX(), (float) area.getRight());
  6925. }
  6926. if (lane == laneMpePitch) // the "no bend" line, and one per octave
  6927. {
  6928. g.setColour (textPrimary.withAlpha (0.15f));
  6929. g.drawHorizontalLine ((int) yOf (0.5f), (float) area.getX(), (float) area.getRight());
  6930. for (auto c = 1200.0f; c < range; c += 1200.0f)
  6931. for (auto sign : { -1.0f, 1.0f })
  6932. {
  6933. g.setColour (textPrimary.withAlpha (0.06f));
  6934. g.drawHorizontalLine ((int) yOf (mpeNorm (lane, sign * c, range)), (float) area.getX(), (float) area.getRight());
  6935. }
  6936. }
  6937. for (auto i : channelNotes())
  6938. {
  6939. const auto& n = notes[(std::size_t) i];
  6940. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  6941. if (x1 < (float) area.getX() || x0 > (float) area.getRight())
  6942. continue;
  6943. const auto selected = isSelected (i);
  6944. auto colour = selected ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  6945. if (n.muted)
  6946. colour = noteMuted;
  6947. // the note's length, faintly (where its curve lives)
  6948. g.setColour (colour.withAlpha (selected ? 0.10f : 0.05f));
  6949. g.fillRect (juce::Rectangle<float> (x0, (float) area.getY() + 1.0f, juce::jmax (1.0f, x1 - x0), (float) area.getHeight() - 1.0f));
  6950. const auto& points = n.curves->lane (curveLane);
  6951. const auto base = mpeBase (lane, n);
  6952. if (points.empty()) // (no curve: the note's own value, dashed)
  6953. {
  6954. const auto y = yOf (mpeNorm (lane, base, range));
  6955. const float dash[] = { 3.0f, 3.0f };
  6956. g.setColour (colour.withAlpha (selected ? 0.55f : 0.3f));
  6957. g.drawDashedLine (juce::Line<float> (x0, y, x1, y), dash, 2, 1.0f);
  6958. continue;
  6959. }
  6960. juce::Path path;
  6961. path.startNewSubPath (x0, yOf (mpeNorm (lane, points.front().value, range)));
  6962. for (const auto& q : points)
  6963. {
  6964. if ((double) q.tick > (double) n.length)
  6965. break;
  6966. path.lineTo ((float) tickToX ((double) n.start + (double) q.tick), yOf (mpeNorm (lane, q.value, range)));
  6967. }
  6968. path.lineTo (x1, yOf (mpeNorm (lane, n.curves->valueAt (curveLane, (double) n.length, base), range)));
  6969. g.setColour (colour.withAlpha (selected ? 0.95f : 0.6f));
  6970. g.strokePath (path, juce::PathStrokeType (selected ? 1.6f : 1.2f));
  6971. if (selected || points.size() <= 64) // (a recorded take's many points only on the notes being edited)
  6972. for (const auto& q : points)
  6973. if ((double) q.tick <= (double) n.length)
  6974. {
  6975. const auto px = (float) tickToX ((double) n.start + (double) q.tick), py = yOf (mpeNorm (lane, q.value, range));
  6976. g.fillEllipse (px - (selected ? 2.5f : 1.8f), py - (selected ? 2.5f : 1.8f), selected ? 5.0f : 3.6f, selected ? 5.0f : 3.6f);
  6977. }
  6978. }
  6979. if (mpeStacked) // (round 190jd: Live names the stacked lanes in the footer and its left column, not in the lane)
  6980. return;
  6981. // the lane's name and range, top left (as the property lanes write theirs)
  6982. juce::String name = lane == laneMpePitch ? tr ("MPE pitch bend") : lane == laneMpeSlide ? tr ("MPE slide") : tr ("MPE pressure");
  6983. if (lane == laneMpePitch)
  6984. name << " " << juce::String::fromUTF8 ("\xc2\xb1") << tr ("{0} st", { juce::String (juce::roundToInt (range / 100.0f)) });
  6985. g.setColour (textSecondary.withAlpha (0.8f));
  6986. g.setFont (theme::font (theme::type::caption, true));
  6987. textcache::drawText (g, name, area.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  6988. }
  6989. void PianoRollComponent::paintMpePitchOnNotes (juce::Graphics& g, juce::Rectangle<int> grid)
  6990. {
  6991. // as Live's MPE view: the note's pitch over its key row, one row per semitone (its fine pitch included)
  6992. using namespace theme::colour;
  6993. juce::Graphics::ScopedSaveState state (g);
  6994. g.reduceClipRegion (grid);
  6995. const auto& notes = currentPattern (engine.getSong()).notes;
  6996. for (auto i : channelNotes())
  6997. {
  6998. const auto& n = notes[(std::size_t) i];
  6999. if (! n.curves.has() || n.curves->lane (NoteCurveLane::pitch).empty())
  7000. continue;
  7001. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  7002. if (x1 < (float) grid.getX() || x0 > (float) grid.getRight())
  7003. continue;
  7004. const auto centre = (float) keyToY (n.key) + (float) rowHeight * 0.5f;
  7005. const auto yOf = [&] (float cents) { return centre - (n.finePitch + cents) / 100.0f * (float) rowHeight; };
  7006. const auto& points = n.curves->lane (NoteCurveLane::pitch);
  7007. juce::Path path;
  7008. path.startNewSubPath (x0, yOf (points.front().value));
  7009. for (const auto& q : points)
  7010. {
  7011. if ((double) q.tick > (double) n.length)
  7012. break;
  7013. path.lineTo ((float) tickToX ((double) n.start + (double) q.tick), yOf (q.value));
  7014. }
  7015. path.lineTo (x1, yOf (n.curves->valueAt (NoteCurveLane::pitch, (double) n.length, 0.0f)));
  7016. g.setColour (juce::Colours::black.withAlpha (0.45f));
  7017. g.strokePath (path, juce::PathStrokeType (2.6f));
  7018. g.setColour ((isSelected (i) ? accentHover.brighter (0.4f) : textPrimary).withAlpha (0.9f));
  7019. g.strokePath (path, juce::PathStrokeType (1.3f));
  7020. }
  7021. }
  7022. void PianoRollComponent::editNoteCurves (int note, const std::function<void (Note&)>& edit)
  7023. {
  7024. editNotes ([note, &edit] (Pattern& p) {
  7025. if (note >= 0 && note < (int) p.notes.size())
  7026. edit (p.notes[(std::size_t) note]);
  7027. });
  7028. }
  7029. bool PianoRollComponent::mpeMouseDown (const juce::MouseEvent& e)
  7030. {
  7031. juce::Rectangle<int> area;
  7032. const auto lane = mpeLaneAt (e.getPosition(), &area);
  7033. if (lane == 0)
  7034. return mpeStacked; // (round 190jd: the MPE tab's footer under the lanes takes the press)
  7035. mpeDragLane = lane;
  7036. mpeDragRange = mpePitchRange();
  7037. lastMpeX = e.x;
  7038. lastMpeY = e.y;
  7039. mpeDragNote = mpeNoteAt (e.x);
  7040. mpeDragPoint = -1;
  7041. if (mpeStacked && mpeFocusLane != lane)
  7042. {
  7043. mpeFocusLane = lane; // (the footer names the lane edited last, as Live's)
  7044. repaint (mpeFooterArea());
  7045. }
  7046. if (mpeGhost.x >= 0.0f)
  7047. updateMpeGhost ({ -1, -1 });
  7048. if (mpeDragNote < 0)
  7049. return true; // (no note there: nothing to draw on)
  7050. if (! isMpeLane (lane)) // round 190jd: the MPE tab's Velocity / Release Velocity lanes: the note under the mouse
  7051. {
  7052. if (! e.mods.isLeftButtonDown())
  7053. return true;
  7054. drag = Drag::mpeValue;
  7055. mpeMouseDrag (e);
  7056. return true;
  7057. }
  7058. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7059. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) mpeDragNote];
  7060. const auto norm = (float) (area.getBottom() - 2 - e.y) / (float) juce::jmax (1, area.getHeight() - 8);
  7061. const auto value = mpeValue (lane, norm, mpeDragRange);
  7062. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  7063. const auto base = mpeBase (lane, n);
  7064. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click: the note's lane back to its own value
  7065. {
  7066. editNoteCurves (mpeDragNote, [curveLane] (Note& m) { notecurves::clearLane (m.curves, curveLane); });
  7067. mpeDragNote = -1;
  7068. return true;
  7069. }
  7070. if (e.mods.isRightButtonDown()) // right-drag erases the points it crosses
  7071. {
  7072. drag = Drag::mpeErase;
  7073. editNoteCurves (mpeDragNote, [curveLane, tick] (Note& m) { notecurves::erase (m.curves, curveLane, tick - 1.0, tick + 1.0); });
  7074. return true;
  7075. }
  7076. if (mpeStacked && ! drawmode::isOn())
  7077. {
  7078. // 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
  7079. // (and drags it), a click off the line does nothing; Draw Mode (B) draws
  7080. const auto hit = mpeLaneHit (mpeDragNote, lane, area, e.getPosition(), mpeDragRange);
  7081. if (hit.hit == mpetab::Hit::point)
  7082. {
  7083. drag = Drag::mpePoint;
  7084. mpeDragPoint = hit.index;
  7085. return true;
  7086. }
  7087. if (hit.hit != mpetab::Hit::line)
  7088. return true;
  7089. const auto onLine = n.curves.has() ? n.curves->valueAt (curveLane, tick, base) : base;
  7090. mpeCreatedAt = juce::Time::getMillisecondCounter();
  7091. auto added = -1;
  7092. editNoteCurves (mpeDragNote, [curveLane, tick, onLine, base, &added] (Note& m) { added = notecurves::addPoint (m.curves, curveLane, tick, onLine, base); });
  7093. drag = Drag::mpePoint;
  7094. mpeDragPoint = added;
  7095. lastMpeY = juce::roundToInt (hit.lineY); // (the point starts on the line; the drag moves it from there)
  7096. return true;
  7097. }
  7098. if (const auto point = mpePointAt (mpeDragNote, lane, area, e.getPosition(), mpeDragRange); point >= 0)
  7099. {
  7100. drag = Drag::mpePoint; // (a point: dragged)
  7101. mpeDragPoint = point;
  7102. return true;
  7103. }
  7104. drag = Drag::mpeDraw; // (elsewhere: drawing starts with a point here)
  7105. mpeCreatedAt = juce::Time::getMillisecondCounter();
  7106. editNoteCurves (mpeDragNote, [curveLane, tick, value, base] (Note& m) { notecurves::addPoint (m.curves, curveLane, tick, value, base); });
  7107. return true;
  7108. }
  7109. bool PianoRollComponent::mpeMouseDrag (const juce::MouseEvent& e)
  7110. {
  7111. const auto& notes = currentPattern (engine.getSong()).notes;
  7112. if (drag == Drag::mpeValue) // round 190jd: the note under the mouse takes the value (a selected one first)
  7113. {
  7114. juce::Rectangle<int> area;
  7115. for (const auto& [r, id] : mpeLaneAreas())
  7116. if (id == mpeDragLane)
  7117. area = r;
  7118. const auto note = mpeNoteAt (e.x);
  7119. if (area.isEmpty() || note < 0)
  7120. return true;
  7121. mpeDragNote = note;
  7122. const auto v = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - 2 - e.y) / (float) juce::jmax (1, area.getHeight() - 8));
  7123. const auto lane = mpeDragLane;
  7124. editNotes ([note, lane, v] (Pattern& p) {
  7125. if (note >= 0 && note < (int) p.notes.size())
  7126. setMpeValueLaneValue (lane, p.notes[(std::size_t) note], v);
  7127. });
  7128. return true;
  7129. }
  7130. if (mpeDragNote < 0 || mpeDragNote >= (int) notes.size())
  7131. return true;
  7132. if (drag == Drag::mpeBend) // round 190jd: a pitch point on the note, one key row a semitone (Live: "0 st", "1 st" …)
  7133. {
  7134. const auto& n = notes[(std::size_t) mpeDragNote];
  7135. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  7136. const auto cents = mpetab::bendCents (mpeBendStart, (float) (e.y - mpeBendY0), (float) rowHeight, e.mods.isShiftDown());
  7137. const auto point = mpeDragPoint;
  7138. editNoteCurves (mpeDragNote, [point, tick, cents] (Note& m) { notecurves::movePoint (m.curves, NoteCurveLane::pitch, point, tick, cents); });
  7139. lastMpeX = e.x;
  7140. lastMpeY = e.y;
  7141. return true;
  7142. }
  7143. juce::Rectangle<int> area;
  7144. for (const auto& [r, id] : mpeLaneAreas())
  7145. if (id == mpeDragLane)
  7146. area = r;
  7147. if (area.isEmpty())
  7148. return true;
  7149. const auto& n = notes[(std::size_t) mpeDragNote];
  7150. const auto lane = mpeDragLane;
  7151. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7152. const auto valueAtY = [&] (int y) { return mpeValue (lane, (float) (area.getBottom() - 2 - y) / (float) juce::jmax (1, area.getHeight() - 8), mpeDragRange); };
  7153. const auto tickAtX = [&] (int x) { return juce::jlimit (0.0, (double) n.length, xToTick (x) - (double) n.start); };
  7154. const auto t0 = tickAtX (lastMpeX), t1 = tickAtX (e.x);
  7155. const auto v0 = valueAtY (lastMpeY), v1 = valueAtY (e.y);
  7156. const auto base = mpeBase (lane, n);
  7157. if (drag == Drag::mpePoint)
  7158. {
  7159. const auto point = mpeDragPoint;
  7160. editNoteCurves (mpeDragNote, [curveLane, point, t1, v1] (Note& m) { notecurves::movePoint (m.curves, curveLane, point, t1, v1); });
  7161. }
  7162. else if (drag == Drag::mpeDraw)
  7163. {
  7164. // (one point every 3 pixels along the drag)
  7165. const auto step = juce::jmax (1.0, 3.0 / juce::jmax (1.0e-9, pixelsPerTick));
  7166. editNoteCurves (mpeDragNote, [=] (Note& m) { notecurves::drawLine (m.curves, curveLane, t0, v0, t1, v1, step, base); });
  7167. }
  7168. else
  7169. editNoteCurves (mpeDragNote, [=] (Note& m) { notecurves::erase (m.curves, curveLane, juce::jmin (t0, t1) - 1.0, juce::jmax (t0, t1) + 1.0); });
  7170. lastMpeX = e.x;
  7171. lastMpeY = e.y;
  7172. return true;
  7173. }
  7174. bool PianoRollComponent::mpeDoubleClick (const juce::MouseEvent& e)
  7175. {
  7176. juce::Rectangle<int> area;
  7177. const auto lane = mpeLaneAt (e.getPosition(), &area);
  7178. if (lane == 0 || e.mods.isRightButtonDown() || ! isMpeLane (lane)) // (round 190jd: Velocity / Release Velocity have no points)
  7179. return lane != 0 || mpeStacked;
  7180. // the first click of this double click drew the point: that was adding it, not deleting it
  7181. if (juce::Time::getMillisecondCounter() - mpeCreatedAt < 800)
  7182. return true;
  7183. const auto note = mpeNoteAt (e.x);
  7184. const auto range = mpePitchRange();
  7185. if (const auto point = mpePointAt (note, lane, area, e.getPosition(), range); point >= 0)
  7186. {
  7187. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7188. editNoteCurves (note, [curveLane, point] (Note& m) { notecurves::removePoint (m.curves, curveLane, point); });
  7189. }
  7190. return true;
  7191. }
  7192. // --- the MPE tab as Live 12.4's (round 190jd; core/MpeTab.h, /mnt/e/lynx-work/livecheck190iw/ANSWERS.md Q3) -----------
  7193. int PianoRollComponent::mpeLaneIdOf (mpetab::Lane lane) noexcept
  7194. {
  7195. switch (lane)
  7196. {
  7197. case mpetab::Lane::slide: return laneMpeSlide;
  7198. case mpetab::Lane::pressure: return laneMpePressure;
  7199. case mpetab::Lane::velocity: return laneVelocity;
  7200. case mpetab::Lane::releaseVelocity: return laneRelease;
  7201. }
  7202. return laneMpePressure;
  7203. }
  7204. float PianoRollComponent::mpeValueLaneValue (int lane, const Note& n) noexcept
  7205. {
  7206. return lane == laneRelease ? n.release : n.velocity;
  7207. }
  7208. void PianoRollComponent::setMpeValueLaneValue (int lane, Note& n, float v) noexcept
  7209. {
  7210. v = std::round (juce::jlimit (0.0f, 1.0f, v) * 127.0f) / 127.0f; // (Live's whole velocity steps)
  7211. if (lane == laneRelease)
  7212. n.release = v;
  7213. else
  7214. n.velocity = juce::jmax (1.0f / 127.0f, v); // (a note keeps a velocity of at least 1, as Live's)
  7215. }
  7216. void PianoRollComponent::setMpeLanesForSnapshot (mpetab::LaneSet lanes)
  7217. {
  7218. mpeShownLanes = lanes == 0 ? mpetab::defaultLanes : lanes;
  7219. resized();
  7220. repaint();
  7221. }
  7222. juce::Rectangle<int> PianoRollComponent::mpeFooterArea() const
  7223. {
  7224. if (! mpeStacked)
  7225. return {};
  7226. const auto lane = velocityArea();
  7227. return { 0, lane.getBottom() - mpetab::footerHeight, lane.getRight(), mpetab::footerHeight };
  7228. }
  7229. juce::PopupMenu PianoRollComponent::mpeLaneMenu()
  7230. {
  7231. // Live 12.4's ▾ button (q3-live-mpe-show-lane-menu.png): "Show Lane:" and four check items, several at once
  7232. juce::PopupMenu menu;
  7233. menu.addSectionHeader (tr ("Show Lane:"));
  7234. const std::pair<mpetab::Lane, juce::String> items[] { { mpetab::Lane::slide, tr ("Slide") },
  7235. { mpetab::Lane::pressure, tr ("Pressure") },
  7236. { mpetab::Lane::velocity, tr ("Velocity") },
  7237. { mpetab::Lane::releaseVelocity, tr ("Release Velocity") } };
  7238. for (const auto& [lane, name] : items)
  7239. {
  7240. const auto shown = mpetab::shows (mpeShownLanes, lane);
  7241. // (the last lane shown stays: the menu greys it out)
  7242. const auto enabled = ! shown || mpetab::countOf (mpeShownLanes) > 1;
  7243. menu.addItem (name, enabled, shown, [safe = juce::Component::SafePointer<PianoRollComponent> (this), lane] {
  7244. if (safe == nullptr)
  7245. return;
  7246. mpeShownLanes = mpetab::toggled (mpeShownLanes, lane);
  7247. const auto id = mpeLaneIdOf (lane);
  7248. if (mpetab::shows (mpeShownLanes, lane))
  7249. safe->mpeFocusLane = id;
  7250. else if (safe->mpeFocusLane == id)
  7251. safe->mpeFocusLane = mpeLaneIdOf (mpetab::shownLanes (mpeShownLanes).back());
  7252. safe->resized();
  7253. safe->repaint();
  7254. });
  7255. }
  7256. return menu;
  7257. }
  7258. mpetab::HitResult PianoRollComponent::mpeLaneHit (int note, int lane, juce::Rectangle<int> area, juce::Point<int> p, float range) const
  7259. {
  7260. const auto& notes = currentPattern (engine.getSong()).notes;
  7261. if (note < 0 || note >= (int) notes.size() || ! isMpeLane (lane))
  7262. return {};
  7263. const auto& n = notes[(std::size_t) note];
  7264. const auto usable = (float) area.getHeight() - 8.0f;
  7265. const auto yOf = [&] (float v) { return (float) area.getBottom() - 2.0f - usable * mpeNorm (lane, v, range); };
  7266. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  7267. const auto base = mpeBase (lane, n);
  7268. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  7269. std::vector<mpetab::Px> points, line;
  7270. if (n.curves.has() && ! n.curves->lane (curveLane).empty())
  7271. {
  7272. const auto& q = n.curves->lane (curveLane);
  7273. line.push_back ({ x0, yOf (q.front().value) });
  7274. for (const auto& k : q)
  7275. {
  7276. if ((double) k.tick > (double) n.length)
  7277. break;
  7278. const mpetab::Px px { (float) tickToX ((double) n.start + (double) k.tick), yOf (k.value) };
  7279. points.push_back (px);
  7280. line.push_back (px);
  7281. }
  7282. line.push_back ({ x1, yOf (n.curves->valueAt (curveLane, (double) n.length, base)) });
  7283. }
  7284. else
  7285. line = { { x0, yOf (base) }, { x1, yOf (base) } }; // (no curve: the note's own value, the dashed line)
  7286. return mpetab::hitTest (points, line, x0, x1, { (float) p.x, (float) p.y });
  7287. }
  7288. std::pair<int, int> PianoRollComponent::mpePitchPointAt (juce::Point<int> p) const
  7289. {
  7290. const auto& notes = currentPattern (engine.getSong()).notes;
  7291. for (auto i : channelNotes())
  7292. {
  7293. const auto& n = notes[(std::size_t) i];
  7294. if (! isSelected (i) || ! n.curves.has())
  7295. continue;
  7296. const auto& q = n.curves->lane (NoteCurveLane::pitch);
  7297. std::vector<mpetab::Px> points;
  7298. const auto centre = (float) keyToY (n.key) + (float) rowHeight * 0.5f;
  7299. for (const auto& k : q)
  7300. if ((double) k.tick <= (double) n.length)
  7301. points.push_back ({ (float) tickToX ((double) n.start + (double) k.tick), centre - (n.finePitch + k.value) / 100.0f * (float) rowHeight });
  7302. if (const auto hit = mpetab::hitTest (points, {}, 0.0f, 0.0f, { (float) p.x, (float) p.y }); hit.hit == mpetab::Hit::point)
  7303. return { i, hit.index };
  7304. }
  7305. return { -1, -1 };
  7306. }
  7307. bool PianoRollComponent::mpePitchMouseDown (const juce::MouseEvent& e, int hit, bool onEdge)
  7308. {
  7309. // 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
  7310. // note adds a pitch point there (the curve's value, "0 st" on a plain note); an unselected note is selected and moved
  7311. // as in the Notes tab
  7312. if (e.mods.isShiftDown() || flmods::ctrl (e.mods) || e.mods.isAltDown() || ! gridArea().contains (e.getPosition()))
  7313. return false;
  7314. const auto tool = tools.getTool();
  7315. if (tool != EditTool::pencil && tool != EditTool::lasso)
  7316. return false;
  7317. const auto grabbed = mpePitchPointAt (e.getPosition());
  7318. auto note = grabbed.first, point = grabbed.second;
  7319. const auto& notes = currentPattern (engine.getSong()).notes;
  7320. if (note < 0)
  7321. {
  7322. if (hit < 0 || onEdge || ! isSelected (hit))
  7323. return false;
  7324. const auto& n = notes[(std::size_t) hit];
  7325. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  7326. const auto value = n.curves.has() ? n.curves->valueAt (NoteCurveLane::pitch, tick, 0.0f) : 0.0f;
  7327. note = hit;
  7328. editNoteCurves (note, [tick, value, &point] (Note& m) { point = notecurves::addPoint (m.curves, NoteCurveLane::pitch, tick, value, 0.0f); });
  7329. mpeCreatedAt = juce::Time::getMillisecondCounter();
  7330. }
  7331. const auto& after = currentPattern (engine.getSong()).notes;
  7332. if (note < 0 || note >= (int) after.size() || ! after[(std::size_t) note].curves.has())
  7333. return true;
  7334. const auto& q = after[(std::size_t) note].curves->lane (NoteCurveLane::pitch);
  7335. if (point < 0 || point >= (int) q.size())
  7336. return true;
  7337. drag = Drag::mpeBend;
  7338. mpeDragNote = note;
  7339. mpeDragPoint = point;
  7340. mpeBendStart = q[(std::size_t) point].value;
  7341. mpeBendY0 = e.y;
  7342. lastMpeX = e.x;
  7343. lastMpeY = e.y;
  7344. return true;
  7345. }
  7346. bool PianoRollComponent::mpePitchDoubleClick (const juce::MouseEvent& e)
  7347. {
  7348. if (e.mods.isRightButtonDown() || flmods::ctrl (e.mods))
  7349. return false;
  7350. // the first click of this double click added the point: that was adding it, not deleting it
  7351. if (juce::Time::getMillisecondCounter() - mpeCreatedAt < 800)
  7352. return true;
  7353. if (const auto grabbed = mpePitchPointAt (e.getPosition()); grabbed.first >= 0)
  7354. {
  7355. const auto point = grabbed.second;
  7356. editNoteCurves (grabbed.first, [point] (Note& m) { notecurves::removePoint (m.curves, NoteCurveLane::pitch, point); });
  7357. return true;
  7358. }
  7359. bool rightEdge = false, leftEdge = false;
  7360. const auto hit = noteAt (e.x, e.y, rightEdge, leftEdge);
  7361. return hit >= 0 && isSelected (hit); // (a selected note's body is the pitch editor here: no note properties)
  7362. }
  7363. juce::Rectangle<int> PianoRollComponent::mpeGhostBounds() const
  7364. {
  7365. if (mpeGhost.x < 0.0f)
  7366. return {};
  7367. return juce::Rectangle<int> (juce::roundToInt (mpeGhost.x) - 6, juce::roundToInt (mpeGhost.y) - 22, 48, 30);
  7368. }
  7369. void PianoRollComponent::updateMpeGhost (juce::Point<int> p)
  7370. {
  7371. juce::Point<float> ghost { -1.0f, -1.0f };
  7372. juce::String text;
  7373. juce::Rectangle<int> area;
  7374. if (mpeStacked && drag == Drag::none && velocityArea().contains (p) && ! drawmode::isOn())
  7375. if (const auto lane = mpeLaneAt (p, &area); isMpeLane (lane))
  7376. if (const auto note = mpeNoteAt (p.x); note >= 0)
  7377. {
  7378. const auto hit = mpeLaneHit (note, lane, area, p, mpePitchRange());
  7379. if (hit.hit == mpetab::Hit::line)
  7380. {
  7381. ghost = { (float) p.x, hit.lineY };
  7382. const auto norm = juce::jlimit (0.0f, 1.0f, ((float) area.getBottom() - 2.0f - hit.lineY) / (float) juce::jmax (1, area.getHeight() - 8));
  7383. const auto v = mpeValue (lane, norm, mpePitchRange());
  7384. text = juce::String (juce::roundToInt (lane == laneMpeSlide ? (float) mpe::timbreOfModX (v) : v * 127.0f));
  7385. }
  7386. }
  7387. if (ghost == mpeGhost && text == mpeGhostText)
  7388. return;
  7389. const auto before = mpeGhostBounds();
  7390. mpeGhost = ghost;
  7391. mpeGhostText = text;
  7392. // (only the two small boxes: the old ghost and the new one)
  7393. if (! before.isEmpty())
  7394. repaint (before);
  7395. if (const auto now = mpeGhostBounds(); ! now.isEmpty())
  7396. repaint (now);
  7397. }
  7398. juce::String PianoRollComponent::hoverMpeLineForSnapshot (int laneId, double tick)
  7399. {
  7400. for (const auto& [area, id] : mpeLaneAreas())
  7401. if (id == laneId)
  7402. for (auto y = area.getY(); y < area.getBottom(); ++y)
  7403. {
  7404. updateMpeGhost ({ juce::roundToInt (tickToX (tick)), y });
  7405. if (mpeGhost.x >= 0.0f)
  7406. return mpeGhostText;
  7407. }
  7408. return {};
  7409. }
  7410. void PianoRollComponent::paintMpeValueLane (juce::Graphics& g, juce::Rectangle<int> area, int lane)
  7411. {
  7412. // Live's Velocity / Release Velocity lanes in the MPE tab: one stem per note, its value at the top (a dot)
  7413. using namespace theme::colour;
  7414. juce::Graphics::ScopedSaveState state (g);
  7415. g.reduceClipRegion (area);
  7416. g.setColour (border);
  7417. g.drawHorizontalLine (area.getY(), (float) area.getX(), (float) area.getRight());
  7418. const auto& notes = currentPattern (engine.getSong()).notes;
  7419. const auto usable = (float) area.getHeight() - 8.0f;
  7420. for (auto i : channelNotes())
  7421. {
  7422. const auto& n = notes[(std::size_t) i];
  7423. const auto x = (float) tickToX ((double) n.start);
  7424. if (x < (float) area.getX() - 4.0f || x > (float) area.getRight() + 4.0f)
  7425. continue;
  7426. const auto selected = isSelected (i);
  7427. auto colour = selected ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  7428. if (n.muted)
  7429. colour = noteMuted;
  7430. const auto y = (float) area.getBottom() - 2.0f - usable * mpeValueLaneValue (lane, n);
  7431. g.setColour (colour.withAlpha (selected ? 0.95f : 0.6f));
  7432. g.fillRect (juce::Rectangle<float> (x, y, 1.0f, (float) area.getBottom() - y));
  7433. g.drawEllipse (x - 2.5f, y - 2.5f, 5.0f, 5.0f, 1.2f);
  7434. }
  7435. }
  7436. void PianoRollComponent::paintMpeTabFrame (juce::Graphics& g)
  7437. {
  7438. // 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
  7439. // icon (Slide ⇕, Pressure ↓) and scale (127 / 0; Pressure 127 / 64 / 0); the footer row the ▾ "Show Lane" button and
  7440. // the focused lane's name; over a lane's line, the ghost point with its value
  7441. using namespace theme::colour;
  7442. const auto lanes = mpeLaneAreas();
  7443. const auto font = theme::font (theme::type::caption);
  7444. for (const auto& [area, id] : lanes)
  7445. {
  7446. const juce::Rectangle<int> column { 0, area.getY(), keyboardWidth, area.getHeight() };
  7447. if (! g.clipRegionIntersects (column))
  7448. continue;
  7449. g.setColour (border);
  7450. g.drawHorizontalLine (column.getY(), 0.0f, (float) keyboardWidth);
  7451. g.setColour (textSecondary.withAlpha (0.85f));
  7452. // the icon, left
  7453. {
  7454. const auto c = juce::Point<float> (9.0f, (float) column.getCentreY());
  7455. juce::Path icon;
  7456. if (id == laneMpeSlide) // ⇕
  7457. {
  7458. icon.addTriangle (c.x - 3.0f, c.y - 2.0f, c.x + 3.0f, c.y - 2.0f, c.x, c.y - 6.0f);
  7459. icon.addTriangle (c.x - 3.0f, c.y + 2.0f, c.x + 3.0f, c.y + 2.0f, c.x, c.y + 6.0f);
  7460. icon.addRectangle (c.x - 0.5f, c.y - 2.0f, 1.0f, 4.0f);
  7461. }
  7462. else if (id == laneMpePressure) // ↓
  7463. {
  7464. icon.addRectangle (c.x - 0.5f, c.y - 6.0f, 1.0f, 8.0f);
  7465. icon.addTriangle (c.x - 3.5f, c.y + 1.0f, c.x + 3.5f, c.y + 1.0f, c.x, c.y + 6.0f);
  7466. }
  7467. else // Velocity / Release Velocity: a stem with its dot
  7468. {
  7469. icon.addRectangle (c.x - 0.5f, c.y - 3.0f, 1.0f, 9.0f);
  7470. icon.addEllipse (c.x - 2.5f, c.y - 6.0f, 5.0f, 5.0f);
  7471. }
  7472. g.fillPath (icon);
  7473. }
  7474. // the scale, right-aligned against the lane with its ticks
  7475. const auto usable = (float) area.getHeight() - 8.0f;
  7476. const auto yOf = [&] (float norm) { return (float) area.getBottom() - 2.0f - usable * norm; };
  7477. std::vector<std::pair<float, const char*>> marks { { 1.0f, "127" }, { 0.0f, "0" } };
  7478. if (id == laneMpePressure && area.getHeight() >= 36)
  7479. marks.insert (marks.begin() + 1, { 0.5f, "64" });
  7480. g.setFont (font);
  7481. for (const auto& [norm, label] : marks)
  7482. {
  7483. const auto y = yOf (norm);
  7484. g.setColour (textSecondary.withAlpha (0.5f));
  7485. g.fillRect (juce::Rectangle<float> ((float) keyboardWidth - 5.0f, std::round (y), 4.0f, 1.0f));
  7486. g.setColour (textSecondary.withAlpha (0.85f));
  7487. const juce::Rectangle<float> box ((float) keyboardWidth - 36.0f, y - 6.0f, 29.0f, 12.0f);
  7488. textcache::drawText (g, label, box.toNearestInt(), juce::Justification::centredRight, false);
  7489. }
  7490. g.setColour (textSecondary.withAlpha (0.4f));
  7491. g.fillRect ((float) keyboardWidth - 2.0f, yOf (1.0f), 1.0f, yOf (0.0f) - yOf (1.0f) + 1.0f);
  7492. }
  7493. // the footer: ▾ and the focused lane's name (Live: "▾ Slide", "▾ Pressure")
  7494. if (const auto footer = mpeFooterArea(); ! footer.isEmpty() && g.clipRegionIntersects (footer))
  7495. {
  7496. g.setColour (bg2);
  7497. g.fillRect (footer);
  7498. g.setColour (border);
  7499. g.drawHorizontalLine (footer.getY(), 0.0f, (float) footer.getRight());
  7500. const auto cy = (float) footer.getCentreY();
  7501. juce::Path arrow;
  7502. arrow.addTriangle (6.0f, cy - 2.0f, 13.0f, cy - 2.0f, 9.5f, cy + 2.5f);
  7503. g.setColour (textSecondary);
  7504. g.fillPath (arrow);
  7505. auto focus = mpeFocusLane;
  7506. auto found = false;
  7507. for (const auto& lane : lanes)
  7508. found = found || lane.second == focus;
  7509. if (! found && ! lanes.empty())
  7510. focus = lanes.back().second;
  7511. const auto name = focus == laneMpeSlide ? tr ("Slide") : focus == laneMpePressure ? tr ("Pressure")
  7512. : focus == laneRelease ? tr ("Release Velocity") : tr ("Velocity");
  7513. g.setFont (font);
  7514. textcache::drawText (g, name, footer.withTrimmedLeft (18).withWidth (juce::jmax (40, keyboardWidth + 120)), juce::Justification::centredLeft, true);
  7515. }
  7516. // the ghost point on the hovered line, with its value (Live: "63", "15")
  7517. if (mpeGhost.x >= 0.0f && g.clipRegionIntersects (mpeGhostBounds()))
  7518. {
  7519. g.setColour (accentHover.withAlpha (0.9f));
  7520. g.drawEllipse (mpeGhost.x - 3.0f, mpeGhost.y - 3.0f, 6.0f, 6.0f, 1.2f);
  7521. const juce::Rectangle<float> tag (mpeGhost.x + 4.0f, mpeGhost.y - 20.0f, 26.0f, 14.0f);
  7522. g.setColour (bg0.withAlpha (0.9f));
  7523. g.fillRoundedRectangle (tag, 2.0f);
  7524. g.setColour (textPrimary);
  7525. g.setFont (font);
  7526. textcache::drawText (g, mpeGhostText, tag.toNearestInt(), juce::Justification::centred, false);
  7527. }
  7528. }
  7529. } // namespace lynx