PianoRollComponent.cpp 257 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941
  1. #include "ui/FlMods.h"
  2. #include "ui/Motion.h"
  3. #include "ui/FileChoosers.h"
  4. #include "ui/PianoRollComponent.h"
  5. #include "ui/PaintAB.h"
  6. #include "core/ChordReadout.h"
  7. #include "core/KeyMap.h"
  8. #include "core/NoteNames.h"
  9. #include "core/TransportEdit.h"
  10. #include "ui/UiTrace.h"
  11. #include "ui/TextCache.h"
  12. #include "core/EditorPolish.h"
  13. #include "core/EventEdit.h"
  14. #include "core/MarkerPlan.h"
  15. #include "core/NoteEdit.h"
  16. #include "core/NoteTools.h"
  17. #include "core/Mpe.h"
  18. #include "core/NoteCurves.h"
  19. #include "core/Rack.h"
  20. #include <array>
  21. #include "engine/MidiFileIo.h"
  22. #include "engine/Mp3Format.h"
  23. #include "core/PianoRollTools.h"
  24. #include "ui/BrowserComponent.h"
  25. #include "ui/Dialogs.h"
  26. #include "ui/MidiClipboard.h"
  27. #include "ui/MidiToolsPanel.h"
  28. #include "ui/ToolWindow.h"
  29. #include "engine/Text.h"
  30. #include <optional>
  31. #include "ui/AutomationUi.h"
  32. #include "ui/EventEditor.h"
  33. #include "ui/HintBar.h"
  34. #include "platform/Paths.h"
  35. #include "ui/I18n.h"
  36. #include "ui/Theme.h"
  37. namespace lynx
  38. {
  39. namespace
  40. {
  41. bool isBlackKey (int key)
  42. {
  43. const auto n = key % 12;
  44. return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
  45. }
  46. // FL-style name: key 60 = C5.
  47. juce::String keyName (int key)
  48. {
  49. return juce::String (notenames::keyName (key)); // Settings › General › Note names (round 165f)
  50. }
  51. // (round 190ea: never out of range: an empty pattern when a hand-built song has none; an edit keeps one first)
  52. const Pattern& currentPattern (const Song& s)
  53. {
  54. return s.activePattern();
  55. }
  56. Pattern& currentPattern (Song& s)
  57. {
  58. return s.activePattern();
  59. }
  60. // "\t" + the key map's shortcut of `id` for a menu item (empty when unbound or no key map is connected)
  61. juce::String keyText (const std::string& id)
  62. {
  63. return PianoRollComponent::shortcutText ? PianoRollComponent::shortcutText (id) : juce::String();
  64. }
  65. struct NamedIntervals
  66. {
  67. const char* name;
  68. std::vector<int> intervals;
  69. };
  70. const std::vector<NamedIntervals>& chords()
  71. {
  72. static const std::vector<NamedIntervals> list {
  73. { TR_NOOP ("Note"), { 0 } }, { TR_NOOP ("Major"), { 0, 4, 7 } }, { TR_NOOP ("Minor"), { 0, 3, 7 } }, { "Dim", { 0, 3, 6 } },
  74. { "Aug", { 0, 4, 8 } }, { "Sus2", { 0, 2, 7 } }, { "Sus4", { 0, 5, 7 } }, { "7", { 0, 4, 7, 10 } },
  75. { "Maj7", { 0, 4, 7, 11 } }, { "m7", { 0, 3, 7, 10 } }, { "m9", { 0, 3, 7, 10, 14 } }, { TR_NOOP ("Octave"), { 0, 12 } },
  76. };
  77. return list;
  78. }
  79. const std::vector<notetools::ScaleInfo>& scales()
  80. {
  81. return notetools::scales();
  82. }
  83. // a detected chord in the chosen note names (Settings › General, round 165f): "Do m7/Mib"; "" when none
  84. juce::String chordName (const std::vector<int>& keys)
  85. {
  86. // FL's own names (round 181b, core/ChordReadout.h): the same for the panel, this readout and the bubble
  87. if ((int) keys.size() < chordread::minKeys || (int) keys.size() > chordread::maxKeys)
  88. return {};
  89. std::array<std::string, 12> notes;
  90. for (int pc = 0; pc < 12; ++pc)
  91. {
  92. auto name = juce::String (notenames::pitchName (pc));
  93. if (name.endsWithChar ('#'))
  94. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266F);
  95. else if (name.length() > 1 && name.endsWithChar ('b'))
  96. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266D);
  97. notes[(std::size_t) pc] = name.toStdString();
  98. }
  99. chordread::NameOptions options;
  100. options.notes = &notes;
  101. const auto named = chordread::nameKeys (keys, options);
  102. const auto text = juce::String::fromUTF8 (named.text.c_str());
  103. return named.novelty ? tr (text) : text;
  104. }
  105. // View › Background waveform (round 168g): one for every editor, like FL's (PTR_DAT_015e2698 / DAT_016ba824)
  106. struct BackgroundWave
  107. {
  108. juce::File file;
  109. std::vector<float> lo, hi; // per peak block
  110. double sampleRate = 44100.0;
  111. std::int64_t samples = 0;
  112. static constexpr int perPeak = 256;
  113. };
  114. std::shared_ptr<const BackgroundWave>& backgroundWave()
  115. {
  116. static std::shared_ptr<const BackgroundWave> wave;
  117. return wave;
  118. }
  119. bool& backgroundWaveOn()
  120. {
  121. static bool on = false;
  122. return on;
  123. }
  124. bool isScoreFile (const juce::File& f) { return f.hasFileExtension ("fsc"); }
  125. bool isMidiFile (const juce::File& f) { return f.hasFileExtension ("mid;midi"); }
  126. } // namespace
  127. PianoRollComponent::PianoRollComponent (AudioEngine& e)
  128. : engine (e)
  129. {
  130. auto sender = [this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); };
  131. previewNotes.setSender (sender);
  132. listenNotes.setSender (sender);
  133. setWantsKeyboardFocus (false);
  134. setMouseClickGrabsKeyboardFocus (false);
  135. for (auto* bar : { &hBar, &vBar })
  136. {
  137. bar->addListener (this);
  138. bar->setAutoHide (false);
  139. addAndMakeVisible (bar);
  140. }
  141. // the overview strip is the horizontal scroller (FL's Piano Roll has its preview bar on top)
  142. hBar.setVisible (false);
  143. overview.paintContent = [this] (juce::Graphics& g, juce::Rectangle<float> area, double total) { paintOverview (g, area, total); };
  144. overview.onChange = [this] (double start, double length) {
  145. const auto width = (double) gridArea().getWidth();
  146. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, width / juce::jmax (1.0, length));
  147. scrollTicks = juce::jmax (0.0, start);
  148. updateScrollBars();
  149. repaint();
  150. };
  151. overview.onShowAll = [this] { zoomAll(); };
  152. addAndMakeVisible (overview);
  153. grid::fillEditorBox (snapBox);
  154. 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"));
  155. ui::setQuickTip (snapBox, tr ("Piano Roll snap"));
  156. snapBox.setWantsKeyboardFocus (false);
  157. snapBox.setMouseClickGrabsKeyboardFocus (false);
  158. snapBox.onChange = [this] { repaint(); };
  159. addAndMakeVisible (snapBox);
  160. // round 190hr: the reference's grid value and menu (docked only)
  161. liveGridButton.setConnectedEdges (0);
  162. liveGridButton.setTooltip (tr ("Grid: adaptive or fixed, narrower (Ctrl+1) or wider (Ctrl+2), triplet (Ctrl+3), snap (Ctrl+4), fixed / adaptive (Ctrl+5)"));
  163. liveGridButton.onClick = [this] {
  164. liveGridMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&liveGridButton));
  165. };
  166. addChildComponent (liveGridButton);
  167. tools.onChange = [this] (EditTool) {
  168. stopListening();
  169. updateCursor (juce::ModifierKeys::currentModifiers);
  170. };
  171. addAndMakeVisible (tools);
  172. 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"));
  173. channelBox.setWantsKeyboardFocus (false);
  174. channelBox.setMouseClickGrabsKeyboardFocus (false);
  175. channelBox.onChange = [this] {
  176. if (channelBox.getSelectedId() == allChannelsId)
  177. {
  178. setAllChannels (true);
  179. return;
  180. }
  181. const auto channel = channelBox.getSelectedId() - 1;
  182. setAllChannels (false);
  183. if (channel >= 0 && channel < (int) engine.getSong().channels.size() && channel != engine.getSelectedChannel())
  184. engine.setSelectedChannel (channel);
  185. };
  186. channelBox.onStep = [this] (int direction, bool all) {
  187. setAllChannels (false);
  188. stepChannel (direction, ! all);
  189. };
  190. addAndMakeVisible (channelBox);
  191. ghostButton.setClickingTogglesState (true);
  192. ghostButton.setToggleState (showGhosts, juce::dontSendNotification);
  193. ghostButton.setOnColour (theme::colour::bg6);
  194. ghostButton.setIconColourWhenOn (theme::colour::textPrimary);
  195. ghostButton.setFlat (true);
  196. ghostButton.setTooltip (tr ("Ghost notes: show the other channels' notes (Alt+V) and, outlined, this channel's notes in the clips "
  197. "playing at the same time; double right-click one to edit its channel; Ctrl+Alt+V makes them editable"));
  198. ui::setQuickTip (ghostButton, tr ("Ghost notes"), "Alt+V");
  199. ui::setQuickTip (moreButton, tr ("Note tools"));
  200. ui::setQuickTip (scaleSnapButton, tr ("Snap to scale"));
  201. ghostButton.onClick = [this] {
  202. showGhosts = ghostButton.getToggleState();
  203. repaint();
  204. };
  205. ghostButton.onRightClick = [this] { // FL: the ghost notes button's menu picks the channels (round 166d)
  206. ghostChannelsMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&ghostButton));
  207. };
  208. moreButton.setFlat (true);
  209. moreButton.setTooltip (tr ("Note operations, left-edge resizing and MIDI import/export"));
  210. moreButton.onClick = [this] { showMoreMenu(); };
  211. scaleSnapButton.setOnColour (theme::colour::bg6);
  212. scaleSnapButton.setIconColourWhenOn (theme::colour::accent);
  213. scaleSnapButton.setFlat (true);
  214. scaleSnapButton.setTooltip (tr ("Snap notes to the scale: new and moved notes, and incoming MIDI, land on the chosen scale"));
  215. scaleSnapButton.onClick = [this] { setScaleSnap (! scaleSnap); };
  216. // Follow (FL: "Auto scrolling"): the view pages along with the playhead while the pattern plays
  217. followButton.setOnColour (theme::colour::bg6);
  218. followButton.setIconColourWhenOn (theme::colour::accent);
  219. followButton.setFlat (true);
  220. followButton.setClickingTogglesState (false);
  221. followButton.setToggleState (EditorGlobals::get().isFollowing (true), juce::dontSendNotification);
  222. followButton.setTooltip (tr ("Follow: the Piano Roll scrolls along with the playhead while this pattern plays; off, you can look around freely"));
  223. ui::setQuickTip (followButton, tr ("Follow the playhead"));
  224. followButton.onClick = [this] { runAction ("pianoRoll.follow"); };
  225. playButton.setFlat (true);
  226. playButton.setClickingTogglesState (false);
  227. playButton.setIconColourWhenOn (theme::colour::accent); // FL: stays a play icon, in the theme colour while playing
  228. playButton.setTooltip (tr ("Play / pause the pattern [RMB] stop and go back to where playback started (again: to the pattern start)"));
  229. playButton.onClick = [this] { if (onPlayPause) onPlayPause(); };
  230. playButton.onRightClick = [this] { if (onPlayRightClick) onPlayRightClick(); };
  231. for (auto* b : { &playButton, &ghostButton, &scaleSnapButton, &moreButton, &followButton })
  232. {
  233. b->setWantsKeyboardFocus (false);
  234. b->setMouseClickGrabsKeyboardFocus (false);
  235. addAndMakeVisible (*b);
  236. }
  237. for (int i = 0; i < (int) chords().size(); ++i)
  238. chordBox.addItem (tr (chords()[(std::size_t) i].name), i + 1);
  239. chordBox.setSelectedId (1, juce::dontSendNotification);
  240. chordBox.setTooltip (tr ("Clicking creates this chord (the clicked note is the root)"));
  241. // scale: root x type
  242. for (int s = 0; s < (int) scales().size(); ++s)
  243. {
  244. if (s == 0)
  245. {
  246. scaleBox.addItem (tr (scales()[0].name), 1);
  247. continue;
  248. }
  249. for (int root = 0; root < 12; ++root)
  250. scaleBox.addItem (tr ("{0} {1}", { juce::String (notenames::pitchName (root)), tr (scales()[(std::size_t) s].name) }), s * 100 + root + 1);
  251. }
  252. scaleBox.setSelectedId (1, juce::dontSendNotification);
  253. scaleSnapButton.setEnabled (false); // until a scale is chosen
  254. scaleBox.setTooltip (tr ("Highlights the notes of a scale"));
  255. // round 170e: an icon (FL's slide tool is one) instead of the word "Slide"
  256. slideButton.setClickingTogglesState (true);
  257. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)"));
  258. ui::setQuickTip (slideButton, tr ("Slide notes"));
  259. slideButton.setWantsKeyboardFocus (false);
  260. slideButton.setMouseClickGrabsKeyboardFocus (false);
  261. slideButton.setOnColour (theme::colour::bg6);
  262. slideButton.setIconColourWhenOn (theme::colour::accent);
  263. slideButton.setFlat (true);
  264. addAndMakeVisible (slideButton);
  265. ui::setQuickTip (chordBox, tr ("Chord stamp"));
  266. ui::setQuickTip (scaleBox, tr ("Scale"));
  267. chordBox.iconLit = [this] { return chordBox.getSelectedId() > 1; };
  268. scaleBox.iconLit = [this] { return scaleIndex() > 0; };
  269. colourButton.setTooltip (tr ("Note colour: new notes get this colour. Click: choose it, colour the selection (Alt+C), "
  270. "select by colour (Shift+C)"));
  271. ui::setQuickTip (colourButton, tr ("Note colour"));
  272. colourButton.setWantsKeyboardFocus (false);
  273. colourButton.setMouseClickGrabsKeyboardFocus (false);
  274. colourButton.onClick = [this] { showColourMenu(); };
  275. addAndMakeVisible (colourButton);
  276. chordLabel.setJustificationType (juce::Justification::centred);
  277. chordLabel.setFont (theme::font (theme::type::caption, true));
  278. chordLabel.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  279. chordLabel.setTooltip (tr ("Chord: the chord of the keys held on the MIDI keyboard or the typing piano, else of the selected notes"));
  280. chordLabel.setInterceptsMouseClicks (true, false);
  281. addAndMakeVisible (chordLabel);
  282. // "Show chord name for selection" (round 168g): FL shows it as a hint 16 px into the editor's top-left corner
  283. chordBubble.setJustificationType (juce::Justification::centred);
  284. chordBubble.setFont (theme::font (theme::type::body, true));
  285. chordBubble.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  286. chordBubble.setColour (juce::Label::backgroundColourId, theme::colour::bg4.withAlpha (0.94f));
  287. chordBubble.setColour (juce::Label::outlineColourId, theme::colour::accent.withAlpha (0.8f));
  288. chordBubble.setInterceptsMouseClicks (false, false);
  289. addChildComponent (chordBubble);
  290. for (auto* box : { &chordBox, &scaleBox })
  291. {
  292. box->setWantsKeyboardFocus (false);
  293. box->setMouseClickGrabsKeyboardFocus (false);
  294. box->onChange = [this] {
  295. publishScale();
  296. scaleSnapButton.setEnabled (scaleIndex() > 0);
  297. if (rows.count < 128 || foldToScale)
  298. updateKeyRows(); // the folded rows follow the scale
  299. repaint();
  300. };
  301. addAndMakeVisible (box);
  302. }
  303. addNoteLanes();
  304. laneBox.setTooltip (tr ("What the bottom lane edits"));
  305. laneBox.setSelectedId (1, juce::dontSendNotification);
  306. laneBox.setWantsKeyboardFocus (false);
  307. laneBox.setMouseClickGrabsKeyboardFocus (false);
  308. laneBox.onChange = [this] { repaint(); };
  309. addAndMakeVisible (laneBox);
  310. setOpaque (true); // paints every pixel: nothing behind it is redrawn while scrolling
  311. engine.addChangeListener (this);
  312. EditorGlobals::get().addChangeListener (this);
  313. refreshChannelBox();
  314. showingTimer = std::make_unique<ui::TimerWhileShowing> (*this, static_cast<juce::Timer&> (*this), 30); // (stopped while hidden; round 174f)
  315. }
  316. PianoRollComponent::~PianoRollComponent()
  317. {
  318. stopListening();
  319. previewNotes.releaseAll();
  320. EditorGlobals::get().removeChangeListener (this);
  321. engine.removeChangeListener (this);
  322. }
  323. juce::Rectangle<int> PianoRollComponent::gridArea() const
  324. {
  325. return getLocalBounds().withTrimmedLeft (keyboardWidth).withTrimmedTop (headerHeight)
  326. .withTrimmedRight (scrollBarSize).withTrimmedBottom (velocityHeight + eventPaneBarArea().getHeight());
  327. }
  328. juce::Rectangle<int> PianoRollComponent::velocityArea() const
  329. {
  330. const auto grid = gridArea();
  331. return { grid.getX(), grid.getBottom() + eventPaneBarArea().getHeight(), grid.getWidth(), velocityHeight };
  332. }
  333. // --- the event editor's divider (round 190fz; FL's TQuickSplitter, the facts in core/EventPaneSplit.h) ---------------
  334. namespace
  335. {
  336. juce::File eventPaneFile() { return platform::settingsFile ("piano-roll-event-pane.txt"); }
  337. } // namespace
  338. evpane::State& PianoRollComponent::eventPaneState()
  339. {
  340. static evpane::State state = evpane::fromText (eventPaneFile().loadFileAsString().toStdString());
  341. return state;
  342. }
  343. void PianoRollComponent::saveEventPaneState()
  344. {
  345. eventPaneFile().replaceWithText (juce::String (evpane::toText (eventPaneState())));
  346. }
  347. juce::Rectangle<int> PianoRollComponent::eventPaneBarArea() const
  348. {
  349. if (fitKeysToNotes) // the Clip-launch dock keeps its short fixed lane (Live's detail view; no divider there)
  350. return {};
  351. return { 0, eventPaneBarTop, getWidth(), evpane::barThickness };
  352. }
  353. void PianoRollComponent::layoutEventPane()
  354. {
  355. if (fitKeysToNotes)
  356. {
  357. // (round 190hy: the MPE tab's three lanes take up to half of the dock, 22 … 44 px each, so the notes stay in view)
  358. if (mpeStacked)
  359. velocityHeight = juce::jlimit (3 * 22, 3 * 44, (getHeight() - headerHeight) / 2);
  360. eventPaneBarTop = getHeight() - velocityHeight;
  361. return;
  362. }
  363. // the bar's travel: from under the ruler (the grid folded away) to the bottom edge (the event editor folded away);
  364. // the remembered place is a fraction of it, so a taller or shorter window keeps the proportion (FL)
  365. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  366. eventPaneBarTop = evpane::barTopOf (eventPaneState().aspect, top, bottom);
  367. velocityHeight = juce::jmax (0, getHeight() - eventPaneBarTop - evpane::barThickness);
  368. }
  369. void PianoRollComponent::eventPaneChanged()
  370. {
  371. resized();
  372. repaint();
  373. ui::Hint hint; // FL's hint bar shows the place as a percentage while it changes ("80%")
  374. hint.value = juce::String (evpane::percentOf (eventPaneState().aspect)) + "%";
  375. ui::postHint (hint);
  376. }
  377. void PianoRollComponent::moveEventPaneBar (int y)
  378. {
  379. if (fitKeysToNotes)
  380. return;
  381. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  382. eventPaneState().aspect = evpane::aspectOf (evpane::clampBar (y, top, bottom), top, bottom);
  383. eventPaneChanged();
  384. }
  385. void PianoRollComponent::toggleEventPaneAlternate()
  386. {
  387. if (fitKeysToNotes)
  388. return;
  389. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  390. evpane::toggleAlternate (eventPaneState(), evpane::aspectOf (eventPaneBarTop, top, bottom));
  391. eventPaneChanged();
  392. saveEventPaneState();
  393. }
  394. void PianoRollComponent::resetEventPane()
  395. {
  396. if (fitKeysToNotes)
  397. return;
  398. evpane::resetToDefault (eventPaneState());
  399. eventPaneChanged();
  400. saveEventPaneState();
  401. }
  402. double PianoRollComponent::tickToX (double tick) const
  403. {
  404. return keyboardWidth + (tick - scrollTicks) * pixelsPerTick;
  405. }
  406. double PianoRollComponent::xToTick (int x) const
  407. {
  408. return (x - keyboardWidth) / pixelsPerTick + scrollTicks;
  409. }
  410. int PianoRollComponent::keyToY (int key) const
  411. {
  412. return headerHeight + rowFor (key) * rowHeight - scrollY;
  413. }
  414. int PianoRollComponent::rowFor (int key) const noexcept
  415. {
  416. key = juce::jlimit (0, 127, key);
  417. const auto row = rows.rowOfKey[(std::size_t) key];
  418. return row >= 0 ? row : rows.rowOfKey[(std::size_t) rows.step (key, 0)]; // a folded key: the row above it
  419. }
  420. void PianoRollComponent::updateKeyRows()
  421. {
  422. // keep the key at the top of the view where it is when the rows change (fold on/off, another scale)
  423. const auto topKey = yToKey (headerHeight);
  424. rows = ! padRows.empty() ? notetools::keyRowsOf (padRows) : notetools::keyRows (scaleRoot(), scaleIndex(), foldToScale);
  425. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), rowFor (topKey) * rowHeight);
  426. updateScrollBars();
  427. repaint();
  428. }
  429. std::vector<int> PianoRollComponent::wantedPadRows() const
  430. {
  431. const auto& song = engine.getSong();
  432. const auto channel = engine.getSelectedChannel();
  433. if (! EditorGlobals::get().clipLaunchWorkflow || allChannels || channel < 0 || channel >= (int) song.channels.size()
  434. || ! rack::isDrumRack (song.channels[(std::size_t) channel]))
  435. return {};
  436. return rack::filledPadKeys (*rack::rackOf (song.channels[(std::size_t) channel].patcher));
  437. }
  438. void PianoRollComponent::syncPadRows()
  439. {
  440. if (auto wanted = wantedPadRows(); wanted != padRows)
  441. {
  442. padRows = std::move (wanted);
  443. updateKeyRows();
  444. }
  445. }
  446. void PianoRollComponent::setFoldToScale (bool on)
  447. {
  448. foldToScale = on;
  449. updateKeyRows();
  450. }
  451. int PianoRollComponent::yToKey (int y) const
  452. {
  453. const auto row = juce::jlimit (0, juce::jmax (0, rows.count - 1), (y - headerHeight + scrollY) / rowHeight);
  454. return rows.keyOfRow[(std::size_t) row];
  455. }
  456. void PianoRollComponent::setKeyStyle (pianokeys::Style style)
  457. {
  458. if (style == keyStyle)
  459. return;
  460. keyStyle = style;
  461. if (EditorGlobals::get().onOptionsChanged)
  462. EditorGlobals::get().onOptionsChanged(); // (the main window saves it and repaints the other editors)
  463. repaint();
  464. }
  465. int PianoRollComponent::keyboardKeyAt (int x, int y) const
  466. {
  467. const auto key = yToKey (y);
  468. if (keyStyle != pianokeys::Style::piano || folded())
  469. return key;
  470. // "Piano keys": right of a black key the white keys above and below it meet in the middle of its row
  471. const auto next = pianokeys::keyAt (keyStyle, key, y - keyToY (key), rowHeight, x, keyboardWidth * 3 / 5);
  472. return juce::isPositiveAndBelow (next, 128) && rows.shown (next) ? next : key;
  473. }
  474. std::int64_t PianoRollComponent::gridTicks() const
  475. {
  476. if (liveGridOn()) // round 190hr: the reference's grid while docked in the Clip-launch detail view
  477. return liveGrid.snap ? std::max<std::int64_t> (1, livegrid::stepTicks (liveGrid, pixelsPerTick)) : 1;
  478. const auto bar = engine.getSong().barTicks();
  479. const auto& option = grid::resolve (snapBox);
  480. switch (option.kind)
  481. {
  482. case grid::Kind::none: return 1;
  483. case grid::Kind::ticks: return option.ticks;
  484. case grid::Kind::bar: return bar;
  485. case grid::Kind::screen:
  486. case grid::Kind::nearest: break;
  487. }
  488. return noteedit::screenStep (pixelsPerTick, bar);
  489. }
  490. std::vector<std::int64_t> PianoRollComponent::snapCandidates() const
  491. {
  492. // edges of this channel's notes (except the ones being dragged) and of the visible ghosts
  493. std::vector<std::int64_t> out;
  494. const auto& notes = currentPattern (engine.getSong()).notes;
  495. for (int i = 0; i < (int) notes.size(); ++i)
  496. {
  497. const auto& n = notes[(std::size_t) i];
  498. if ((! edits (n) && (! showGhosts || ! ghostShown (n.channel))) || std::find (dragIndices.begin(), dragIndices.end(), i) != dragIndices.end())
  499. continue;
  500. out.push_back (n.start);
  501. out.push_back (n.start + n.length);
  502. }
  503. return out;
  504. }
  505. std::int64_t PianoRollComponent::snap (double tick, bool enabled) const
  506. {
  507. if (! enabled)
  508. return (std::int64_t) std::floor (tick);
  509. if (! liveGridOn() && grid::resolve (snapBox).kind == grid::Kind::nearest)
  510. return noteedit::snapNearest (tick, snapCandidates(), 10.0 / pixelsPerTick, gridTicks());
  511. return noteedit::snapDown (tick, gridTicks());
  512. }
  513. std::int64_t PianoRollComponent::newNoteLength() const
  514. {
  515. const auto fixed = EditorGlobals::get().getDefaultNoteLength();
  516. return fixed > 0 ? fixed : lastLength;
  517. }
  518. std::int64_t PianoRollComponent::viewLengthTicks() const
  519. {
  520. const auto& song = engine.getSong();
  521. const auto bar = song.barTicks();
  522. // pattern + 4 bars of headroom to grow
  523. return currentPattern (song).effectiveLength (song.meter()) + 4 * bar;
  524. }
  525. void PianoRollComponent::updateScrollBars()
  526. {
  527. const auto grid = gridArea();
  528. const auto total = (double) viewLengthTicks();
  529. hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
  530. hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
  531. vBar.setRangeLimits (0.0, (double) rows.count * rowHeight, juce::dontSendNotification);
  532. vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
  533. scrollTicks = hBar.getCurrentRangeStart();
  534. scrollY = (int) vBar.getCurrentRangeStart();
  535. overview.minLength = grid.getWidth() / (120.0 / ticksPerStep);
  536. overview.setRange (total, scrollTicks, grid.getWidth() / pixelsPerTick);
  537. }
  538. void PianoRollComponent::setTitleBarInsets (int left, int right)
  539. {
  540. if (left != titleInsetLeft || right != titleInsetRight)
  541. {
  542. titleInsetLeft = left;
  543. titleInsetRight = right;
  544. resized();
  545. }
  546. }
  547. void PianoRollComponent::resized()
  548. {
  549. layoutEventPane(); // (round 190fz: the grid / event editor heights from the divider's place)
  550. const auto h = toolbarHeight - 6;
  551. auto bar = juce::Rectangle<int> (4 + titleInsetLeft, 3, juce::jmax (0, getWidth() - 8 - titleInsetLeft - titleInsetRight), h);
  552. // groups that don't fit in a narrow window are hidden (the tools and the grid always show). The menu button always
  553. // keeps its place: the optional groups only take what is left beside it (round 190j: on a 1024 px screen the
  554. // groups before it used up the bar and the Piano roll menu could not be opened).
  555. const auto reserved = h + 6;
  556. auto place = [&bar, reserved] (juce::Component& c, int width, bool optional = false) {
  557. const auto fits = ! optional || width <= bar.getWidth() - reserved;
  558. c.setVisible (fits);
  559. c.setBounds (fits ? bar.removeFromLeft (juce::jmin (width, bar.getWidth())) : juce::Rectangle<int>());
  560. bar.removeFromLeft (juce::jmin (6, bar.getWidth()));
  561. };
  562. place (playButton, h);
  563. place (channelBox, 150);
  564. place (tools, tools.getIdealWidth (h));
  565. if (liveGridOn()) // round 190hr: the reference's grid value in place of FL's snap box
  566. {
  567. snapBox.setVisible (false);
  568. liveGridButton.setButtonText (liveGrid.snap ? juce::String (livegrid::stepText (gridTicks(), liveGrid.triplet)) + juce::String::fromUTF8 (" \xe2\x96\xbe")
  569. : tr ("Off") + juce::String::fromUTF8 (" \xe2\x96\xbe"));
  570. place (liveGridButton, 72);
  571. }
  572. else
  573. {
  574. liveGridButton.setVisible (false);
  575. place (snapBox, 128);
  576. }
  577. place (ghostButton, h);
  578. place (followButton, h);
  579. place (slideButton, h, true);
  580. place (colourButton, h, true);
  581. // the chord stamp shrinks to its icon and arrow before it is hidden (discussion #10; FL's stamp is an icon button)
  582. place (chordBox, 100 <= bar.getWidth() - reserved ? 100 : pianoroll::compactChordBoxWidth, true);
  583. place (scaleBox, 164, true);
  584. if (scaleBox.isVisible())
  585. place (scaleSnapButton, h);
  586. else
  587. scaleSnapButton.setVisible (false);
  588. place (moreButton, h);
  589. place (chordLabel, 84, true);
  590. laneBox.setBounds (2, velocityArea().getY() + 4, keyboardWidth - 4, 20);
  591. laneBox.setVisible (velocityHeight >= 24 && ! mpeStacked); // (the event editor folded away: FL hides its target panel too; the MPE tab names its lanes)
  592. overview.setBounds (keyboardWidth, toolbarHeight, getWidth() - keyboardWidth - zoomWheelSize, overviewHeight);
  593. vBar.setBounds (getWidth() - scrollBarSize, headerHeight, scrollBarSize, gridArea().getHeight());
  594. updateScrollBars();
  595. }
  596. void PianoRollComponent::squeezeToolbarForSnapshot (int pixels)
  597. {
  598. setTitleBarInsets (titleInsetLeft, titleInsetRight + pixels);
  599. }
  600. void PianoRollComponent::scrollToNotes (bool fitPattern)
  601. {
  602. const auto& song = engine.getSong();
  603. int low = 128, high = -1;
  604. for (const auto& n : currentPattern (song).notes)
  605. if (edits (n))
  606. {
  607. low = juce::jmin (low, n.key);
  608. high = juce::jmax (high, n.key);
  609. }
  610. refreshChannelBox();
  611. if (fitKeysToNotes && high >= 0 && gridArea().getHeight() > 0) // docked: every note's row in the short view, as far as the key height allows
  612. {
  613. const auto span = std::abs (rowFor (low) - rowFor (high)) + 3;
  614. rowHeight = juce::jlimit (gesture::minKeyHeight, undockedRowHeight, gridArea().getHeight() / span);
  615. }
  616. const auto centreKey = high >= 0 ? (low + high) / 2 : 66;
  617. scrollY = rowFor (centreKey) * rowHeight - gridArea().getHeight() / 2;
  618. scrollTicks = 0.0;
  619. // FL opens the Piano Roll with the whole pattern across the view (at least one bar)
  620. if (fitPattern && gridArea().getWidth() > 0)
  621. {
  622. const auto bar = (double) song.barTicks();
  623. const auto length = juce::jmax (bar, (double) currentPattern (song).effectiveLength (song.meter()));
  624. pixelsPerTick = juce::jlimit (4.0 / ticksPerStep, 64.0 / ticksPerStep, gridArea().getWidth() / length);
  625. }
  626. updateScrollBars();
  627. repaint();
  628. }
  629. // --- selection ---------------------------------------------------------------
  630. std::vector<int> PianoRollComponent::chordIntervals() const
  631. {
  632. const auto index = juce::jlimit (0, (int) chords().size() - 1, chordBox.getSelectedId() - 1);
  633. auto intervals = chords()[(std::size_t) index].intervals;
  634. // FL 2026's top-down stamp (REA round 153): the clicked key is the chord's highest note
  635. if (chordTopDown && intervals.size() > 1)
  636. {
  637. const auto top = *std::max_element (intervals.begin(), intervals.end());
  638. for (auto& i : intervals)
  639. i -= top;
  640. std::reverse (intervals.begin(), intervals.end()); // the clicked (top) note first: it leads the drag
  641. }
  642. return intervals;
  643. }
  644. int PianoRollComponent::scaleIndex() const
  645. {
  646. const auto id = scaleBox.getSelectedId();
  647. return id <= 1 ? 0 : id / 100;
  648. }
  649. int PianoRollComponent::scaleRoot() const
  650. {
  651. const auto id = scaleBox.getSelectedId();
  652. return id <= 1 ? 0 : (id % 100) - 1;
  653. }
  654. bool PianoRollComponent::inScale (int key) const
  655. {
  656. return scaleIndex() > 0 && notetools::inScale (key, scaleRoot(), scaleIndex());
  657. }
  658. int PianoRollComponent::snapKey (int key) const
  659. {
  660. return scalesnap::drawKey (snapScale(), key);
  661. }
  662. scalesnap::Scale PianoRollComponent::snapScale() const
  663. {
  664. return { scaleRoot(), scaleIndex(), scaleSnap };
  665. }
  666. void PianoRollComponent::setScaleSnap (bool on)
  667. {
  668. scaleSnap = on;
  669. scaleSnapButton.setToggleState (on, juce::dontSendNotification);
  670. publishScale();
  671. repaint();
  672. }
  673. void PianoRollComponent::publishScale()
  674. {
  675. engine.setInputScale (scaleSnap ? scaleIndex() : 0, scaleRoot());
  676. }
  677. bool PianoRollComponent::isSelected (int index) const
  678. {
  679. return std::binary_search (selection.begin(), selection.end(), index);
  680. }
  681. std::vector<int> PianoRollComponent::channelNotes() const
  682. {
  683. const auto& notes = currentPattern (engine.getSong()).notes;
  684. std::vector<int> out;
  685. for (int i = 0; i < (int) notes.size(); ++i)
  686. if (edits (notes[(std::size_t) i]) && rows.shown (notes[(std::size_t) i].key)) // (folded-away notes are left alone)
  687. out.push_back (i);
  688. return out;
  689. }
  690. std::vector<int> PianoRollComponent::selectionOrAll() const
  691. {
  692. return selection.empty() ? channelNotes() : selection;
  693. }
  694. void PianoRollComponent::setSelection (std::vector<int> indices)
  695. {
  696. std::sort (indices.begin(), indices.end());
  697. indices.erase (std::unique (indices.begin(), indices.end()), indices.end());
  698. selection = std::move (indices);
  699. repaint();
  700. }
  701. void PianoRollComponent::selectAll()
  702. {
  703. setSelection (channelNotes());
  704. }
  705. bool PianoRollComponent::refuseFrozenEdit()
  706. {
  707. const auto& song = engine.getSong();
  708. const auto channel = engine.getSelectedChannel();
  709. if (channel < 0 || channel >= (int) song.channels.size() || ! song.channels[(std::size_t) channel].freeze.on())
  710. return false;
  711. 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()) }), {} },
  712. 3000);
  713. return true;
  714. }
  715. void PianoRollComponent::editNotes (const std::function<void (Pattern&)>& edit, bool undoable)
  716. {
  717. if (refuseFrozenEdit())
  718. return;
  719. engine.editSong ([&edit] (Song& s) { edit (currentPattern (s)); }, undoable);
  720. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  721. }
  722. void PianoRollComponent::sortNotes()
  723. {
  724. auto tracked = selection;
  725. tracked.push_back (dragNote);
  726. // only reorders: no undo step of its own needed
  727. engine.editSong ([&tracked] (Song& s) { noteedit::sortTracking (currentPattern (s), tracked); }, false);
  728. dragNote = tracked.back();
  729. tracked.pop_back();
  730. setSelection (tracked);
  731. }
  732. juce::Rectangle<float> PianoRollComponent::stretchHandle() const
  733. {
  734. // a tab on the right end of the selection, vertically centred on it (clamped into the grid)
  735. const auto& notes = currentPattern (engine.getSong()).notes;
  736. std::int64_t start = 0, end = 0;
  737. int top = -1, bottom = 128;
  738. bool any = false;
  739. for (auto i : selection)
  740. {
  741. if (i < 0 || i >= (int) notes.size() || ! edits (notes[(std::size_t) i]))
  742. continue;
  743. const auto& n = notes[(std::size_t) i];
  744. start = any ? juce::jmin (start, n.start) : n.start;
  745. end = any ? juce::jmax (end, n.start + n.length) : n.start + n.length;
  746. top = juce::jmax (top, n.key);
  747. bottom = juce::jmin (bottom, n.key);
  748. any = true;
  749. }
  750. if (! any || end <= start)
  751. return {};
  752. const auto grid = gridArea().toFloat();
  753. const auto x = (float) tickToX ((double) end);
  754. const auto y0 = (float) keyToY (top), y1 = (float) (keyToY (bottom) + rowHeight);
  755. const auto cy = juce::jlimit (grid.getY() + 10.0f, juce::jmax (grid.getY() + 10.0f, grid.getBottom() - 10.0f), (y0 + y1) * 0.5f);
  756. const auto r = juce::Rectangle<float> (x + 2.0f, cy - 9.0f, 9.0f, 18.0f);
  757. return grid.intersects (r) ? r : juce::Rectangle<float>();
  758. }
  759. void PianoRollComponent::drumPaintAt (juce::Point<int> p, bool snapOn)
  760. {
  761. // one short hit per grid cell and key, on whatever key is under the mouse (FL's drum painting)
  762. const auto cell = juce::jmax<std::int64_t> (1, snapOn ? gridTicks() : ticksPerStep);
  763. const auto start = juce::jmax<std::int64_t> (0, snapOn ? snap (xToTick (p.x), true) : noteedit::snapDown (xToTick (p.x), cell));
  764. const auto key = snapKey (yToKey (p.y));
  765. if (start == lastDrumCell && key == lastDrumKey)
  766. return;
  767. lastDrumCell = start;
  768. lastDrumKey = key;
  769. const auto channel = engine.getSelectedChannel();
  770. if (polish::hasNoteInCell (currentPattern (engine.getSong()), channel, key, start, cell))
  771. return;
  772. Note n;
  773. noteTemplate.applyTo (n);
  774. n.start = start;
  775. n.length = cell;
  776. n.key = key;
  777. n.channel = channel;
  778. n.colour = noteColour;
  779. editNotes ([&n] (Pattern& pat) { noteedit::paste (pat, { n }, 0); });
  780. if (key != previewKey)
  781. previewEdit (key, n.velocity);
  782. }
  783. // --- painting ------------------------------------------------------------------
  784. void PianoRollComponent::paintOverview (juce::Graphics& g, juce::Rectangle<float> area, double total)
  785. {
  786. // the channel's notes across the whole view length, pitch mapped onto the strip's height; the part past
  787. // the pattern's end is darker; bar lines every bar (every 4 when they get dense)
  788. using namespace theme::colour;
  789. const auto& song = engine.getSong();
  790. const auto& pattern = currentPattern (song);
  791. const auto channel = engine.getSelectedChannel();
  792. const auto scale = area.getWidth() / juce::jmax (1.0, total);
  793. const auto bar = (double) song.barTicks();
  794. const auto end = (float) (pattern.effectiveLength (song.meter()) * scale);
  795. g.setColour (bg2);
  796. g.fillRect (area.withWidth (juce::jmin (area.getWidth(), end)));
  797. const auto every = bar * scale < 6.0 ? 4 : 1;
  798. g.setColour (gridBar.withAlpha (0.6f));
  799. for (int b = every; b * bar < total; b += every)
  800. g.fillRect ((float) (area.getX() + b * bar * scale), area.getY(), 1.0f, area.getHeight());
  801. int low = 128, high = -1;
  802. for (const auto& n : pattern.notes)
  803. if (edits (n))
  804. {
  805. low = juce::jmin (low, n.key);
  806. high = juce::jmax (high, n.key);
  807. }
  808. if (high < 0)
  809. return;
  810. const auto span = (float) juce::jmax (12, high - low + 1);
  811. const auto mid = (low + high) / 2.0f;
  812. const auto inner = area.reduced (0.0f, 2.0f);
  813. auto colour = accent;
  814. if (channel < (int) song.channels.size() && song.channels[(std::size_t) channel].colour != 0)
  815. colour = theme::tame (juce::Colour (song.channels[(std::size_t) channel].colour));
  816. colour = colour.interpolatedWith (textPrimary, 0.35f); // reads on the dark strip at any channel colour
  817. for (const auto& n : pattern.notes)
  818. {
  819. if (! edits (n))
  820. continue;
  821. const auto y = inner.getCentreY() - ((float) n.key - mid) / span * inner.getHeight();
  822. const auto x = area.getX() + (float) (n.start * scale);
  823. g.setColour (n.muted ? colour.withAlpha (0.35f) : colour);
  824. g.fillRect (x, juce::jlimit (inner.getY(), inner.getBottom() - 2.0f, y - 1.0f),
  825. juce::jmax (1.0f, (float) (n.length * scale) - 0.5f), 2.0f);
  826. }
  827. }
  828. void PianoRollComponent::paint (juce::Graphics& g)
  829. {
  830. const uitrace::Scope trace ("PianoRollComponent paint", true, g.getClipBounds());
  831. const auto& song = engine.getSong();
  832. const auto& pattern = currentPattern (song);
  833. const auto channel = engine.getSelectedChannel();
  834. const auto grid = gridArea();
  835. const auto patternLength = pattern.effectiveLength (song.meter());
  836. const auto bar = song.barTicks();
  837. const auto snapGrid = gridTicks();
  838. // the overview follows the notes (edits, undo, another channel or pattern) and the view
  839. {
  840. // (round 190gp: hashed again only when the song, the pattern or the channel changed since the last paint;
  841. // LYNX_PAINT_SAVINGS=0 hashes on every paint, as before)
  842. const auto stamp = engine.getSongStamp();
  843. if (! ui::paintSavings() || stamp != overviewStamp || song.currentPattern != overviewPattern || channel != overviewChannel)
  844. {
  845. overviewStamp = stamp;
  846. overviewPattern = song.currentPattern;
  847. overviewChannel = channel;
  848. auto signature = (std::size_t) song.currentPattern * 1000003u + (std::size_t) channel * 7919u + pattern.notes.size();
  849. for (const auto& n : pattern.notes)
  850. signature = signature * 31u + (std::size_t) (n.start * 131 + n.length * 7 + n.key + n.channel * 257 + (n.muted ? 1 : 0));
  851. if (signature != overviewSignature)
  852. {
  853. overviewSignature = signature;
  854. overview.repaint();
  855. }
  856. }
  857. overview.setRange ((double) viewLengthTicks(), scrollTicks, grid.getWidth() / pixelsPerTick);
  858. }
  859. using namespace theme::colour;
  860. g.fillAll (bg1);
  861. g.setColour (bg3);
  862. g.fillRect (0, 0, getWidth(), toolbarHeight);
  863. g.setColour (border);
  864. g.fillRect (0, toolbarHeight - 1, getWidth(), 1);
  865. auto drawVerticalGrid = [&] (juce::Rectangle<int> area) {
  866. // grid lines: bar > beat > snap (unless too dense)
  867. const auto step = snapGrid * pixelsPerTick >= 6.0 ? snapGrid : (std::int64_t) ppq;
  868. const auto first = (std::int64_t) std::floor (scrollTicks / (double) step);
  869. const auto last = (std::int64_t) std::ceil (xToTick (area.getRight()) / (double) step);
  870. for (auto i = first; i <= last; ++i)
  871. {
  872. const auto tick = i * step;
  873. const auto x = (float) tickToX ((double) tick);
  874. g.setColour (tick % bar == 0 ? gridBar : tick % ppq == 0 ? gridBeat : gridStep);
  875. g.drawVerticalLine ((int) x, (float) area.getY(), (float) area.getBottom());
  876. }
  877. };
  878. // round 190ge: what this paint may change. A moving playhead repaints a 14-pixel column many times a second, and
  879. // every note drawn outside it (a rounded rectangle is a path to build and fill) was work for no pixel: the notes,
  880. // ghosts and velocity markers whose drawing lies wholly outside are skipped (the pixels stay the same)
  881. const auto dirtyArea = g.getClipBounds();
  882. const auto cull = ui::paintSavings(); // (LYNX_PAINT_SAVINGS=0: everything drawn, as before)
  883. const auto outside = [&dirtyArea, cull] (const juce::Rectangle<float>& r, float margin) {
  884. return cull && ! r.expanded (margin).getSmallestIntegerContainer().intersects (dirtyArea);
  885. };
  886. // --- grid ------------------------------------------------------------
  887. {
  888. juce::Graphics::ScopedSaveState state (g);
  889. g.reduceClipRegion (grid);
  890. for (int key = 0; key < 128; ++key)
  891. {
  892. const auto y = keyToY (key);
  893. if (! rows.shown (key) || y > grid.getBottom() || y + rowHeight < grid.getY())
  894. continue;
  895. // Note grid highlights (Alt+B, round 168g): off, every row looks the same (FL's "BlackKeys" option)
  896. auto row = gridHighlights && isBlackKey (key) ? rowBlack : rowWhite;
  897. if (gridHighlights && inScale (key))
  898. row = row.interpolatedWith (info, 0.10f);
  899. if (key == hover.key && drag == Drag::none)
  900. row = row.interpolatedWith (textPrimary, 0.04f); // the row under the mouse
  901. g.setColour (row);
  902. g.fillRect (grid.getX(), y, grid.getWidth(), rowHeight);
  903. if (! padRows.empty() || key % 12 == (folded() ? scaleRoot() : 0)) // folded: the octave line under each root (pads: each row)
  904. {
  905. g.setColour (gridBeat);
  906. g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
  907. }
  908. }
  909. drawVerticalGrid (grid);
  910. paintBackgroundWave (g, grid);
  911. // the time selection (Ctrl+drag on the ruler): Insert / Delete space, Trim
  912. if (timeFrom >= 0 && timeTo > timeFrom)
  913. {
  914. g.setColour (selectionFill.withMultipliedAlpha (0.45f));
  915. g.fillRect (juce::Rectangle<float> ((float) tickToX ((double) timeFrom), (float) grid.getY(),
  916. (float) ((double) (timeTo - timeFrom) * pixelsPerTick), (float) grid.getHeight()));
  917. }
  918. // outside the pattern is darkened
  919. const auto endX = (float) tickToX ((double) patternLength);
  920. g.setColour (bg0.withAlpha (0.55f));
  921. g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
  922. // ghost notes (Alt+V). This channel's notes in the other clips that play at the same time in the
  923. // Playlist: hollow outlines. The other channels of this pattern: solid grey (a bit brighter, with
  924. // their channel colour on the edge, when Ctrl+Alt+V makes them editable)
  925. if (showGhosts)
  926. {
  927. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, channel))
  928. {
  929. if (! rows.shown (n.key))
  930. continue;
  931. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  932. juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
  933. if (r.getRight() < (float) grid.getX() || r.getX() > (float) grid.getRight() || outside (r, 2.0f))
  934. continue;
  935. g.setColour (textPrimary.withAlpha (0.30f));
  936. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  937. }
  938. }
  939. for (const auto& n : pattern.notes)
  940. {
  941. if (edits (n) || ! showGhosts || ! ghostShown (n.channel) || ! rows.shown (n.key))
  942. continue;
  943. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  944. (float) (n.length * pixelsPerTick), (float) rowHeight - 2);
  945. if (outside (r, 2.0f))
  946. continue;
  947. const auto hovered = &n - pattern.notes.data() == hover.ghost;
  948. g.setColour (textPrimary.withAlpha (hovered ? 0.16f : editGhosts ? 0.12f : 0.09f));
  949. g.fillRoundedRectangle (r, 2.0f);
  950. g.setColour (textPrimary.withAlpha (hovered ? 0.35f : editGhosts ? 0.22f : 0.12f));
  951. g.drawRoundedRectangle (r, 2.0f, 1.0f);
  952. if (editGhosts && n.channel >= 0 && n.channel < (int) song.channels.size() && song.channels[(std::size_t) n.channel].colour != 0)
  953. {
  954. g.setColour (theme::tame (juce::Colour (song.channels[(std::size_t) n.channel].colour)).withAlpha (0.7f));
  955. g.fillRect (r.withWidth (2.0f).reduced (0.0f, 1.0f));
  956. }
  957. }
  958. for (int i = 0; i < (int) pattern.notes.size(); ++i)
  959. {
  960. const auto& n = pattern.notes[(std::size_t) i];
  961. if (! edits (n) || ! rows.shown (n.key))
  962. continue;
  963. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  964. juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
  965. if (outside (r, 2.0f)) // (its outline, grips, marks and label all lie inside r)
  966. continue;
  967. const auto selected = isSelected (i);
  968. const auto hovered = i == hover.note && drag == Drag::none;
  969. // a selected muted note keeps a muted look (round 167k: Alt+M on a selection showed no change)
  970. auto fill = selected ? (n.muted ? accentHover.interpolatedWith (noteMuted, 0.6f) : accentHover.brighter (0.15f))
  971. : n.muted ? noteMuted : theme::noteGroupColour (n.colour, n.velocity);
  972. if (hovered)
  973. fill = fill.brighter (0.18f);
  974. g.setColour (fill);
  975. g.fillRoundedRectangle (r, 2.5f);
  976. g.setColour (selected ? textPrimary : hovered ? textPrimary.withAlpha (0.75f) : bg0.withAlpha (0.6f));
  977. g.drawRoundedRectangle (r, 2.5f, 1.0f);
  978. // "All" channels: whose note it is, by the channel's colour on its left edge (issue #12)
  979. if (allChannels && n.channel >= 0 && n.channel < (int) song.channels.size() && r.getWidth() > 5.0f)
  980. {
  981. const auto c = song.channels[(std::size_t) n.channel].colour;
  982. g.setColour ((c != 0 ? theme::tame (juce::Colour (c)) : textPrimary.withAlpha (0.5f)).withAlpha (0.9f));
  983. g.fillRect (r.withWidth (2.5f).reduced (0.0f, 1.5f).translated (1.0f, 0.0f));
  984. }
  985. // the edge under the mouse shows its grip
  986. if (hovered && (hover.zone == gesture::Zone::rightEdge || hover.zone == gesture::Zone::leftEdge))
  987. {
  988. const auto gripX = hover.zone == gesture::Zone::rightEdge ? r.getRight() - 3.0f : r.getX() + 1.0f;
  989. g.setColour (textPrimary);
  990. g.fillRoundedRectangle (gripX, r.getY() + 2.0f, 2.0f, juce::jmax (2.0f, r.getHeight() - 4.0f), 1.0f);
  991. }
  992. if (n.group != 0 && r.getWidth() > 10.0f) // grouped: a small link mark at the top right
  993. {
  994. g.setColour (bg0.withAlpha (0.7f));
  995. g.fillEllipse (r.getRight() - 6.0f, r.getY() + 1.5f, 3.5f, 3.5f);
  996. }
  997. // a Chance below 100 % (round 187c): a small triangle in the top-left corner, as Live 12 marks it ("A small
  998. // triangle is displayed in the upper-left corner of notes with probability values less than 100%")
  999. if ((n.chance < 1.0f || n.chanceGroup != 0) && r.getWidth() > 6.0f && r.getHeight() > 5.0f)
  1000. {
  1001. juce::Path corner;
  1002. const auto size = juce::jmin (6.0f, r.getHeight() - 2.0f);
  1003. 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);
  1004. g.setColour (bg0.withAlpha (0.75f));
  1005. g.fillPath (corner);
  1006. }
  1007. if (n.porta) // porta: slanted stroke at the start, like the glide
  1008. {
  1009. g.setColour (bg0.withAlpha (0.65f));
  1010. g.drawLine (r.getX() + 2.0f, r.getBottom() - 2.0f, r.getX() + 9.0f, r.getY() + 2.0f, 2.0f);
  1011. }
  1012. if (n.slide) // slide arrow at the start of the note
  1013. {
  1014. juce::Path arrow;
  1015. arrow.addTriangle (r.getX() + 2.0f, r.getBottom() - 2.0f, r.getX() + 2.0f, r.getY() + 2.0f, r.getX() + 9.0f, r.getCentreY());
  1016. g.setColour (bg0.withAlpha (0.65f));
  1017. g.fillPath (arrow);
  1018. }
  1019. if (gesture::noteLabelFits (r.getWidth(), rowHeight)) // the note's name, readable on its colour
  1020. {
  1021. g.setColour (fill.getPerceivedBrightness() > 0.55f ? bg0.withAlpha (0.85f) : textPrimary.withAlpha (0.9f));
  1022. g.setFont (theme::font (gesture::labelHeight (rowHeight) - 1.0f));
  1023. textcache::drawText (g, keyName (n.key), r.reduced (n.slide || n.porta ? 11.0f : 4.0f, 0.0f), juce::Justification::centredLeft, true);
  1024. }
  1025. }
  1026. // round 177d: the notes being played into a take grow with the playhead until they are released (then the
  1027. // recorded note takes their place); FL 2026 draws them so, as ordinary notes (REA_rodada177d §1.3, g03)
  1028. if (engine.isLiveRecording())
  1029. for (const auto& n : engine.liveRecording().held)
  1030. {
  1031. if (! edits (n) || ! rows.shown (n.key))
  1032. continue;
  1033. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  1034. juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
  1035. const auto fill = theme::noteGroupColour (n.colour, n.velocity);
  1036. g.setColour (fill);
  1037. g.fillRoundedRectangle (r, 2.5f);
  1038. g.setColour (bg0.withAlpha (0.6f));
  1039. g.drawRoundedRectangle (r, 2.5f, 1.0f);
  1040. if (gesture::noteLabelFits (r.getWidth(), rowHeight))
  1041. {
  1042. g.setColour (fill.getPerceivedBrightness() > 0.55f ? bg0.withAlpha (0.85f) : textPrimary.withAlpha (0.9f));
  1043. g.setFont (theme::font (gesture::labelHeight (rowHeight) - 1.0f));
  1044. textcache::drawText (g, keyName (n.key), r.reduced (4.0f, 0.0f), juce::Justification::centredLeft, true);
  1045. }
  1046. }
  1047. // the selection's stretch handle: a tab at its right end with two grips
  1048. if (const auto handle = stretchHandle(); ! handle.isEmpty() && (drag == Drag::none || drag == Drag::stretch))
  1049. {
  1050. const auto lit = hover.stretch || drag == Drag::stretch;
  1051. g.setColour (lit ? accentHover : accent.withAlpha (0.85f));
  1052. g.fillRoundedRectangle (handle, 3.0f);
  1053. g.setColour (onAccent.withAlpha (0.9f));
  1054. g.fillRect (handle.getCentreX() - 2.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  1055. g.fillRect (handle.getCentreX() + 1.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  1056. if (lit) // the stretched span, from the anchor to the handle
  1057. {
  1058. g.setColour (accent.withAlpha (0.5f));
  1059. const auto x0 = (float) tickToX ((double) (drag == Drag::stretch ? stretchAnchor : 0));
  1060. if (drag == Drag::stretch)
  1061. g.drawVerticalLine ((int) x0, (float) grid.getY(), (float) grid.getBottom());
  1062. g.drawVerticalLine ((int) handle.getX() - 2, (float) grid.getY(), (float) grid.getBottom());
  1063. }
  1064. }
  1065. if (! mpeLaneAreas().empty()) // (round 190hy: as Live's MPE view, each note's pitch curve over it)
  1066. paintMpePitchOnNotes (g, grid);
  1067. if (! rubberBand.isEmpty())
  1068. {
  1069. g.setColour (selectionFill);
  1070. g.fillRect (rubberBand);
  1071. g.setColour (theme::colour::selection);
  1072. g.drawRect (rubberBand);
  1073. }
  1074. if (drag == Drag::knife)
  1075. {
  1076. juce::Path cut;
  1077. cut.startNewSubPath (knifeFrom.toFloat());
  1078. cut.lineTo (knifeTo.toFloat());
  1079. juce::Path dashed;
  1080. const float dash[] = { 5.0f, 3.0f };
  1081. juce::PathStrokeType (1.5f).createDashedStroke (dashed, cut, dash, 2);
  1082. g.setColour (textPrimary);
  1083. g.fillPath (dashed);
  1084. }
  1085. if (playheadTick >= 0.0)
  1086. {
  1087. g.setColour (playhead);
  1088. g.drawVerticalLine ((int) tickToX (playheadTick), (float) grid.getY(), (float) grid.getBottom());
  1089. }
  1090. }
  1091. // --- velocity lane -----------------------------------------------------
  1092. {
  1093. const auto lane = velocityArea();
  1094. g.setColour (bg0);
  1095. g.fillRect (lane);
  1096. juce::Graphics::ScopedSaveState state (g);
  1097. g.reduceClipRegion (lane);
  1098. drawVerticalGrid (lane);
  1099. g.setColour (border);
  1100. g.drawHorizontalLine (lane.getY(), (float) lane.getX(), (float) lane.getRight());
  1101. const auto usable = (float) lane.getHeight() - 8.0f;
  1102. const auto bipolar = laneIsBipolar();
  1103. const auto base = bipolar ? (float) lane.getBottom() - 2.0f - usable * 0.5f : (float) lane.getBottom();
  1104. if (bipolar)
  1105. {
  1106. g.setColour (textPrimary.withAlpha (0.15f));
  1107. g.drawHorizontalLine ((int) base, (float) lane.getX(), (float) lane.getRight());
  1108. }
  1109. if (const auto target = eventLaneTarget()) // pattern events: held values, a dot on each event
  1110. {
  1111. const auto* events = eventedit::findLane (pattern, *target);
  1112. if (events != nullptr && ! events->events.empty())
  1113. {
  1114. juce::Path held;
  1115. const auto yOf = [&] (float v) { return (float) lane.getBottom() - 2.0f - usable * v; };
  1116. auto x = (float) tickToX (0.0);
  1117. auto y = yOf (events->events.front().value);
  1118. held.startNewSubPath (x, y);
  1119. for (const auto& ev : events->events)
  1120. {
  1121. const auto ex = (float) tickToX ((double) ev.tick);
  1122. held.lineTo (ex, y);
  1123. y = yOf (ev.value);
  1124. held.lineTo (ex, y);
  1125. }
  1126. held.lineTo ((float) lane.getRight(), y);
  1127. g.setColour (accent.withAlpha (0.85f));
  1128. g.strokePath (held, juce::PathStrokeType (1.5f));
  1129. for (const auto& ev : events->events)
  1130. g.fillEllipse ((float) tickToX ((double) ev.tick) - 2.5f, yOf (ev.value) - 2.5f, 5.0f, 5.0f);
  1131. }
  1132. else
  1133. {
  1134. g.setColour (textDisabled);
  1135. g.setFont (theme::font (theme::type::small));
  1136. textcache::drawText (g, tr ("No events yet: draw them here"), lane.reduced (8, 4), juce::Justification::centredLeft, true);
  1137. }
  1138. }
  1139. const auto mpeLanes = mpeLaneAreas(); // (round 190hy: the notes' MPE curves instead of their stems)
  1140. if (! mpeLanes.empty())
  1141. {
  1142. const auto range = drag == Drag::mpePoint || drag == Drag::mpeDraw ? mpeDragRange : mpePitchRange();
  1143. for (const auto& [area, id] : mpeLanes)
  1144. paintMpeLane (g, area, id, range);
  1145. }
  1146. else
  1147. {
  1148. // the lane's name in it, as FL writes it next to "Control" (round 149: the box on the left is narrow)
  1149. g.setColour (theme::colour::textSecondary.withAlpha (0.8f));
  1150. g.setFont (theme::font (theme::type::caption, true));
  1151. textcache::drawText (g, laneBox.getText(), lane.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  1152. }
  1153. for (int i = 0; i < (int) pattern.notes.size() && ! eventLaneTarget() && mpeLanes.empty(); ++i)
  1154. {
  1155. const auto& n = pattern.notes[(std::size_t) i];
  1156. if (! edits (n) || ! rows.shown (n.key))
  1157. continue;
  1158. const auto x = (float) tickToX ((double) n.start);
  1159. // (round 190ge: outside the repainted area — the marker's ±6 pixels, the Velocity Range box over the note's
  1160. // length — nothing to draw; a probability group's line reaches another note, so those are always drawn)
  1161. if (! (laneIsChance() && n.chanceGroup != 0)
  1162. && 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))
  1163. continue;
  1164. const auto top = (float) lane.getBottom() - 2.0f - usable * laneValue (n);
  1165. auto colour = isSelected (i) ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  1166. if (n.muted)
  1167. colour = noteMuted;
  1168. const auto hovered = i == hover.note && drag == Drag::none;
  1169. // the velocity lane shows a note's Velocity Range (round 187c) as a shaded box over the note's length, from
  1170. // its velocity to where the range reaches, as Live 12 draws it [LIVE 12.4 shot, live-02]
  1171. if (laneBox.getSelectedId() == laneVelocity && n.velocityRange != 0.0f)
  1172. {
  1173. const auto reach = juce::jlimit (1.0f / 127.0f, 1.0f, n.velocity + n.velocityRange);
  1174. const auto y2 = (float) lane.getBottom() - 2.0f - usable * reach;
  1175. const auto w = juce::jmax (3.0f, (float) (n.length * pixelsPerTick) - 1.0f);
  1176. g.setColour (colour.withAlpha (0.22f));
  1177. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, y2), w, std::abs (y2 - top)));
  1178. g.setColour (colour.withAlpha (0.5f));
  1179. g.drawHorizontalLine ((int) y2, x, x + w);
  1180. }
  1181. // a probability group (round 187c): its members' Chance markers joined by a line (the group has one Chance)
  1182. if (laneIsChance() && n.chanceGroup != 0)
  1183. for (int j = i + 1; j < (int) pattern.notes.size(); ++j)
  1184. if (const auto& m = pattern.notes[(std::size_t) j]; m.chanceGroup == n.chanceGroup && edits (m) && rows.shown (m.key))
  1185. {
  1186. g.setColour (colour.withAlpha (0.5f));
  1187. const auto dash = std::array<float, 2> { 3.0f, 3.0f };
  1188. g.drawDashedLine (juce::Line<float> (x, top, (float) tickToX ((double) m.start), top), dash.data(), 2, n.chanceOne ? 1.0f : 2.0f);
  1189. break;
  1190. }
  1191. g.setColour (hovered ? colour.brighter (0.3f) : colour.withAlpha (0.8f));
  1192. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, base), hovered ? 3.0f : 2.0f, std::abs (base - top)));
  1193. g.fillEllipse (x - 3.0f, top - 3.0f, 7.0f, 7.0f);
  1194. if (hovered)
  1195. g.drawEllipse (x - 5.0f, top - 5.0f, 11.0f, 11.0f, 1.0f);
  1196. }
  1197. if (drag == Drag::velocityLine) // the line being drawn
  1198. {
  1199. g.setColour (textPrimary.withAlpha (0.8f));
  1200. g.drawLine (juce::Line<int> (knifeFrom, knifeTo).toFloat(), 1.5f);
  1201. }
  1202. }
  1203. // --- time ruler --------------------------------------------------------
  1204. {
  1205. const auto ruler = juce::Rectangle<int> (keyboardWidth, rulerTop, grid.getWidth(), timelineHeight);
  1206. g.setColour (bg2);
  1207. g.fillRect (ruler);
  1208. g.setColour (border);
  1209. g.fillRect (ruler.withTop (ruler.getBottom() - 1));
  1210. juce::Graphics::ScopedSaveState state (g);
  1211. g.reduceClipRegion (ruler);
  1212. g.setFont (theme::font (theme::type::caption));
  1213. const auto firstBar = (std::int64_t) std::floor (scrollTicks / (double) bar);
  1214. const auto lastBar = (std::int64_t) std::ceil (xToTick (grid.getRight()) / (double) bar);
  1215. if (timeFrom >= 0 && timeTo > timeFrom) // the time selection on the ruler
  1216. {
  1217. const auto x0 = (float) tickToX ((double) timeFrom), x1 = (float) tickToX ((double) timeTo);
  1218. g.setColour (accent.withAlpha (0.35f));
  1219. g.fillRect (juce::Rectangle<float> (x0, (float) rulerTop, x1 - x0, (float) timelineHeight - 1.0f));
  1220. g.setColour (accent);
  1221. g.fillRect (juce::Rectangle<float> (x0, (float) rulerTop, x1 - x0, 2.0f));
  1222. }
  1223. // View › "Ruler: song bars" (round 177d, LYNX's own; off = FL's pattern bars): the bar numbers the Playlist shows
  1224. // where the pattern's first clip plays
  1225. const auto songOrigin = songBarsRuler ? polish::patternSongOrigin (song, song.currentPattern) : std::nullopt;
  1226. for (auto b = firstBar; b <= lastBar; ++b)
  1227. {
  1228. const auto x = (int) tickToX ((double) (b * bar));
  1229. g.setColour (textSecondary);
  1230. g.drawVerticalLine (x, (float) rulerTop + 10.0f, (float) headerHeight);
  1231. const std::int64_t number = songOrigin.has_value() ? polish::songBarNumber (*songOrigin, b, bar) : (std::int64_t) b + 1;
  1232. if (number > 0)
  1233. textcache::drawText (g, juce::String (number), x + 3, rulerTop + 2, 40, timelineHeight - 4, juce::Justification::centredLeft);
  1234. }
  1235. // the pattern's time markers (round 168g): a flag and the name in the ruler's lower half, like the Playlist's
  1236. for (const auto& m : currentPattern (song).markers)
  1237. {
  1238. const auto x = (float) tickToX ((double) m.tick);
  1239. if (x < (float) keyboardWidth - 120.0f || x > (float) ruler.getRight())
  1240. continue;
  1241. const auto colour = m.isSignature() ? textPrimary : accent;
  1242. g.setColour (colour);
  1243. g.fillRect (juce::Rectangle<float> (x, (float) rulerTop + 11.0f, 1.5f, (float) timelineHeight - 11.0f));
  1244. juce::Path flag;
  1245. flag.addTriangle (x, (float) rulerTop + 11.0f, x + 6.0f, (float) rulerTop + 14.0f, x, (float) rulerTop + 17.0f);
  1246. g.fillPath (flag);
  1247. auto label = juce::String::fromUTF8 (m.name.c_str());
  1248. if (label.isEmpty() && m.action != 0)
  1249. label = tr (markers::actionName (m.action));
  1250. textcache::drawText (g, label, (int) x + 8, rulerTop + 10, 110, timelineHeight - 11, juce::Justification::centredLeft);
  1251. }
  1252. if (playheadTick >= 0.0)
  1253. {
  1254. const auto x = (float) tickToX (playheadTick);
  1255. juce::Path tri;
  1256. tri.addTriangle (x - 5, (float) rulerTop, x + 5, (float) rulerTop, x, (float) rulerTop + 8);
  1257. g.setColour (playhead);
  1258. g.fillPath (tri);
  1259. }
  1260. }
  1261. // --- keyboard ------------------------------------------------------------
  1262. // flat keys; every C is labelled with its octave, the other white keys too when the rows are tall
  1263. // enough; the key under the mouse (and the one sounding) are lit
  1264. {
  1265. const auto keys = juce::Rectangle<int> (0, headerHeight, keyboardWidth, grid.getHeight());
  1266. juce::Graphics::ScopedSaveState state (g);
  1267. g.reduceClipRegion (keys);
  1268. g.setColour (bg0);
  1269. g.fillRect (keys);
  1270. const auto fontHeight = gesture::labelHeight (rowHeight);
  1271. const auto blackWidth = keyboardWidth * 3 / 5;
  1272. static const std::map<int, std::string> noLabels;
  1273. const auto selectedChannel = engine.getSelectedChannel();
  1274. const auto& ownLabels = selectedChannel >= 0 && selectedChannel < (int) song.channels.size()
  1275. ? song.channels[(std::size_t) selectedChannel].keyLabels : noLabels;
  1276. // a Drum Rack's pad names on its keys (round 190ec, Live's note editor); a key label of the user's wins
  1277. std::map<int, std::string> padLabels;
  1278. if (selectedChannel >= 0 && selectedChannel < (int) song.channels.size() && rack::isDrumRack (song.channels[(std::size_t) selectedChannel]))
  1279. {
  1280. padLabels = rack::padNames (*rack::rackOf (song.channels[(std::size_t) selectedChannel].patcher));
  1281. for (const auto& [key, label] : ownLabels)
  1282. padLabels[key] = label;
  1283. }
  1284. const auto& labels = padLabels.empty() ? ownLabels : padLabels;
  1285. // folded to the scale (round 166d) the keys no longer alternate like a piano: one full-width named row each
  1286. const auto list = folded();
  1287. const auto piano = keyStyle == pianokeys::Style::piano && ! list;
  1288. const auto keyColour = [&] (int key) {
  1289. const auto black = isBlackKey (key) && ! list;
  1290. const auto pressed = key == previewKey || isLit (key);
  1291. auto colour = black ? keyBlack : keyWhite;
  1292. if (inScale (key))
  1293. colour = colour.interpolatedWith (info, black ? 0.18f : 0.12f);
  1294. if (key == hover.key && ! pressed)
  1295. colour = colour.interpolatedWith (accent, black ? 0.35f : 0.22f);
  1296. return pressed ? accent : colour;
  1297. };
  1298. for (int key = 0; key < 128; ++key)
  1299. {
  1300. const auto y = keyToY (key);
  1301. if (! rows.shown (key) || y > keys.getBottom() || y + rowHeight < keys.getY())
  1302. continue;
  1303. const auto black = isBlackKey (key) && ! list;
  1304. const auto pressed = key == previewKey || isLit (key);
  1305. const auto hovered = key == hover.key && ! pressed;
  1306. const auto colour = keyColour (key);
  1307. const auto width = black ? blackWidth : keyboardWidth - 1;
  1308. if (piano)
  1309. {
  1310. // "Piano keys" (round 190j, discussion #136): the white keys meet behind the black key, each in its own
  1311. // colour (hover, pressed, scale), with a dark line between every two white keys
  1312. const auto line = bg0.withAlpha (0.85f);
  1313. if (black)
  1314. {
  1315. const auto upper = pianokeys::upperPart (rowHeight);
  1316. g.setColour (keyColour (juce::jmin (127, key + 1)));
  1317. g.fillRect (0, y, keyboardWidth - 1, upper);
  1318. g.setColour (keyColour (juce::jmax (0, key - 1)));
  1319. g.fillRect (0, y + upper, keyboardWidth - 1, rowHeight - upper);
  1320. g.setColour (line);
  1321. g.drawHorizontalLine (y + upper, (float) blackWidth, (float) (keyboardWidth - 1));
  1322. // the black key: a little shorter than its row when there is room, so the white shows around it
  1323. const auto inset = rowHeight >= 12 ? 1 : 0;
  1324. g.setColour (bg0);
  1325. g.fillRect (0, y + inset, blackWidth + 1, rowHeight - 2 * inset);
  1326. g.setColour (colour);
  1327. g.fillRect (0, y + inset, blackWidth, rowHeight - 2 * inset);
  1328. if (! pressed && rowHeight >= 12) // a light edge along the top, as on a real black key
  1329. {
  1330. g.setColour (keyWhite.withAlpha (0.14f));
  1331. g.drawHorizontalLine (y + inset, 0.0f, (float) blackWidth);
  1332. }
  1333. }
  1334. else
  1335. {
  1336. g.setColour (colour);
  1337. g.fillRect (0, y, width, rowHeight);
  1338. if (pianokeys::lineBelow (key))
  1339. {
  1340. g.setColour (line);
  1341. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  1342. }
  1343. }
  1344. }
  1345. else
  1346. {
  1347. g.setColour (colour);
  1348. g.fillRect (0, y, width, rowHeight);
  1349. g.setColour (black ? bg0 : keyWhite.darker (0.3f));
  1350. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  1351. }
  1352. const auto isC = key % 12 == 0;
  1353. // every key named (LYNX, on by default: notenames::everyKey) once the rows are tall enough to read
  1354. const auto everyKey = notenames::everyKey.load (std::memory_order_relaxed) && rowHeight >= 8;
  1355. if (isC || hovered || pressed || everyKey || (! black && rowHeight >= (list ? 8 : 16)))
  1356. {
  1357. g.setFont (theme::font (fontHeight, isC));
  1358. g.setColour (pressed ? onAccent : black ? textPrimary.withAlpha (hovered ? 1.0f : 0.85f) : isC ? bg0 : bg0.withAlpha (everyKey ? 0.72f : 0.55f));
  1359. const auto area = black ? juce::Rectangle<int> (2, y, blackWidth - 4, rowHeight)
  1360. : juce::Rectangle<int> (blackWidth, y, keyboardWidth - blackWidth - 5, rowHeight);
  1361. textcache::drawText (g, keyName (key), area, black ? juce::Justification::centredLeft : juce::Justification::centredRight, false);
  1362. }
  1363. // a key label (FL 2026's custom key labels) replaces the name on the white part of the key
  1364. if (const auto label = labels.find (key); label != labels.end() && rowHeight >= 8)
  1365. {
  1366. const auto area = juce::Rectangle<int> (black ? blackWidth + 2 : 3, y, keyboardWidth - (black ? blackWidth + 2 : 3) - 4, rowHeight);
  1367. g.setColour (black ? keyWhite : colour);
  1368. g.fillRect (area);
  1369. g.setFont (theme::font (fontHeight, false));
  1370. g.setColour (pressed ? onAccent : bg0);
  1371. g.drawFittedText (juce::String::fromUTF8 (label->second.c_str()), area.reduced (1, 0), juce::Justification::centredLeft, 1, 0.8f);
  1372. }
  1373. if (! padRows.empty()) // (a Drum Rack's pad rows: a strip at the right in the key's piano colour, as Live's list)
  1374. {
  1375. g.setColour (isBlackKey (key) ? keyBlack : keyWhite.darker (0.25f));
  1376. g.fillRect (keyboardWidth - 12, y, 11, rowHeight - 1);
  1377. }
  1378. }
  1379. g.setColour (border);
  1380. g.fillRect (keyboardWidth - 1, keys.getY(), 1, keys.getHeight());
  1381. }
  1382. // velocity lane label
  1383. {
  1384. const auto lane = velocityArea();
  1385. g.setColour (bg2);
  1386. g.fillRect (0, lane.getY(), keyboardWidth, lane.getHeight());
  1387. juce::ignoreUnused (lane); // the property combo sits here
  1388. }
  1389. // the event editor's divider (round 190fz): FL's 10 px bar, a dark line at its top and bottom, lighter than the
  1390. // grid, with a grip of five 2 px dots 4 px apart in its middle (FL's SplitterPaint: darker than the bar at rest,
  1391. // lighter when a pane is folded away, the highlight colour while it is dragged; FL shot: triage190j/FL-pianoroll.png)
  1392. if (const auto divider = eventPaneBarArea(); ! divider.isEmpty() && g.clipRegionIntersects (divider))
  1393. {
  1394. g.setColour (bg3);
  1395. g.fillRect (divider);
  1396. g.setColour (bg0);
  1397. g.fillRect (divider.getX(), divider.getY(), divider.getWidth(), 1);
  1398. g.fillRect (divider.getX(), divider.getBottom() - 1, divider.getWidth(), 1);
  1399. const auto top = headerHeight, bottom = juce::jmax (headerHeight, getHeight() - evpane::barThickness);
  1400. const auto atEnd = eventPaneBarTop <= top || eventPaneBarTop >= bottom;
  1401. g.setColour (drag == Drag::eventPaneBar && ! atEnd ? accent : atEnd ? textSecondary : bg1);
  1402. const auto centre = divider.getCentre();
  1403. for (int i = -2; i <= 2; ++i)
  1404. g.fillRect (centre.x + i * 4 - 1, centre.y - 1, 2, 2);
  1405. }
  1406. // the zoom wheel (round 190j): FL's small square with a mark in its middle, at the end of the time scroll bar
  1407. {
  1408. const auto wheel = zoomWheelArea().toFloat().reduced (1.0f);
  1409. const auto over = drag == Drag::keyZoom || zoomWheelHover;
  1410. g.setColour (bg2);
  1411. g.fillRect (zoomWheelArea());
  1412. g.setColour (over ? bg5 : bg4);
  1413. g.fillRoundedRectangle (wheel, 2.0f);
  1414. g.setColour (over ? textPrimary : textSecondary);
  1415. g.fillRect (juce::Rectangle<float> (4.0f, 5.0f).withCentre (wheel.getCentre()));
  1416. }
  1417. // top-left corner: channel name
  1418. g.setColour (bg3);
  1419. g.fillRect (0, 0, keyboardWidth, toolbarHeight);
  1420. g.setColour (bg2);
  1421. g.fillRect (0, toolbarHeight, keyboardWidth, headerHeight - toolbarHeight);
  1422. g.setColour (border);
  1423. g.fillRect (0, headerHeight - 1, keyboardWidth, 1);
  1424. g.fillRect (keyboardWidth - 1, 0, 1, headerHeight);
  1425. if (channel < (int) song.channels.size())
  1426. {
  1427. const auto& ch = song.channels[(std::size_t) channel];
  1428. g.setColour (ch.colour != 0 ? theme::tame (juce::Colour (ch.colour)) : accent);
  1429. g.fillRoundedRectangle (4.0f, (float) toolbarHeight + 6.0f, 3.0f, (float) (headerHeight - toolbarHeight) - 12.0f, 1.0f);
  1430. g.setColour (textPrimary);
  1431. g.setFont (theme::font (theme::type::caption, true));
  1432. textcache::drawFittedText (g, juce::String::fromUTF8 (ch.name.c_str()), 11, toolbarHeight, keyboardWidth - 14, headerHeight - toolbarHeight,
  1433. juce::Justification::centredLeft, 2, 0.8f);
  1434. // Freeze (round 190ay): the frozen mark over the notes' top right corner, with what to do
  1435. if (ch.freeze.on())
  1436. {
  1437. const auto text = tr ("Frozen: Unfreeze to edit");
  1438. g.setFont (theme::font (theme::type::caption, true));
  1439. const auto grid = gridArea();
  1440. const auto width = juce::jmin (grid.getWidth() - 8, 34 + juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), text));
  1441. if (width > 40)
  1442. {
  1443. const auto pill = juce::Rectangle<float> ((float) grid.getRight() - (float) width - 6.0f, (float) grid.getY() + 6.0f, (float) width, 20.0f);
  1444. theme::fillRoundRect (g, pill, theme::radius::md, bg1.withAlpha (0.88f));
  1445. theme::drawFrozenTag (g, juce::Rectangle<float> (pill.getX() + 4.0f, pill.getCentreY() - 6.5f, 14.0f, 13.0f), info.withAlpha (0.85f), bg1);
  1446. g.setColour (textSecondary);
  1447. g.drawText (text, pill.withTrimmedLeft (24.0f).withTrimmedRight (6.0f), juce::Justification::centredLeft, true);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. // --- mouse -------------------------------------------------------------------
  1453. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge) const
  1454. {
  1455. bool left = false;
  1456. return noteAt (x, y, onRightEdge, left);
  1457. }
  1458. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge, bool& onLeftEdge) const
  1459. {
  1460. // the same hit test as the hover (cursor and highlight), so a click does what the cursor showed
  1461. const auto h = hoverAt ({ x, y });
  1462. onRightEdge = h.zone == gesture::Zone::rightEdge;
  1463. onLeftEdge = h.zone == gesture::Zone::leftEdge;
  1464. return gridArea().contains (x, y) ? h.note : -1;
  1465. }
  1466. int PianoRollComponent::ghostAt (int x, int y) const
  1467. {
  1468. if (! showGhosts)
  1469. return -1;
  1470. const auto& notes = currentPattern (engine.getSong()).notes;
  1471. const auto key = yToKey (y);
  1472. for (int i = (int) notes.size() - 1; i >= 0; --i)
  1473. {
  1474. const auto& n = notes[(std::size_t) i];
  1475. if (! edits (n) && n.key == key && ghostShown (n.channel) && x >= tickToX ((double) n.start) && x < tickToX ((double) (n.start + n.length)))
  1476. return i;
  1477. }
  1478. return -1;
  1479. }
  1480. float PianoRollComponent::keyVelocityAt (int x, int key) const
  1481. {
  1482. // FL: a click near the left of a key plays it softly, at its right end at full velocity (black keys are shorter)
  1483. return gesture::keyClickVelocity ((double) x, (double) (isBlackKey (key) ? keyboardWidth * 3 / 5 : keyboardWidth - 1));
  1484. }
  1485. void PianoRollComponent::previewOn (int key, float velocity)
  1486. {
  1487. // one preview note at a time; it remembers its channel, so a channel switch meanwhile can't strand it
  1488. previewNotes.releaseAll();
  1489. previewKey = key;
  1490. previewNotes.press (engine.getSelectedChannel(), key, velocity);
  1491. repaint (0, headerHeight, keyboardWidth, getHeight());
  1492. }
  1493. void PianoRollComponent::previewEdit (int key, float velocity)
  1494. {
  1495. if (gesture::previewsEditedNote (engine.getTransport().playing.load(), previewWhilePlaying))
  1496. previewOn (key, velocity);
  1497. }
  1498. void PianoRollComponent::previewOff()
  1499. {
  1500. previewNotes.releaseAll();
  1501. if (previewKey >= 0)
  1502. {
  1503. previewKey = -1;
  1504. repaint (0, headerHeight, keyboardWidth, getHeight());
  1505. }
  1506. }
  1507. void PianoRollComponent::visibilityChanged()
  1508. {
  1509. if (! isShowing()) // hidden mid-gesture (window closed, tab switched): nothing keeps sounding
  1510. {
  1511. previewOff();
  1512. stopListening();
  1513. }
  1514. }
  1515. // The note properties the bottom lane edits: FL's (velocity, pan, fine pitch, release, Mod X / Y: its "Control" list,
  1516. // FLEngine strings "Note release", "Note modulation X / Y"), then Live 12's Chance and Velocity Range (round 187c, LYNX
  1517. // additions marked "(LYNX)")
  1518. void PianoRollComponent::addNoteLanes()
  1519. {
  1520. laneBox.addItem (tr ("Velocity"), laneVelocity);
  1521. laneBox.addItem (tr ("Pan"), lanePan);
  1522. laneBox.addItem (tr ("Fine pitch"), laneFinePitch);
  1523. laneBox.addItem (tr ("Release"), laneRelease);
  1524. laneBox.addItem (tr ("Mod X"), laneModX);
  1525. laneBox.addItem (tr ("Mod Y"), laneModY);
  1526. laneBox.addItem (tr ("Chance"), laneChance);
  1527. laneBox.addItem (tr ("Velocity range (LYNX)"), laneVelocityRange);
  1528. // MPE stage 2 (round 190hy, issue #108): each note's own pitch bend / slide (CC 74) / pressure curve, as Live 11+'s
  1529. // note expression lanes (LYNX additions: FL 2026 has no per-note curves)
  1530. laneBox.addItem (tr ("MPE pitch bend"), laneMpePitch);
  1531. laneBox.addItem (tr ("MPE slide"), laneMpeSlide);
  1532. laneBox.addItem (tr ("MPE pressure"), laneMpePressure);
  1533. }
  1534. float PianoRollComponent::laneValue (const Note& n) const
  1535. {
  1536. switch (laneBox.getSelectedId())
  1537. {
  1538. case lanePan: return (n.pan + 1.0f) * 0.5f;
  1539. case laneFinePitch: return (n.finePitch + 120.0f) / 240.0f;
  1540. case laneRelease: return n.release;
  1541. case laneModX: return n.modX;
  1542. case laneModY: return n.modY;
  1543. case laneChance: return n.chance;
  1544. case laneVelocityRange: return (n.velocityRange + 1.0f) * 0.5f;
  1545. case laneMpePitch: return 0.5f; // (the MPE lanes edit curves, not one value: round 190hy)
  1546. case laneMpeSlide: return n.modX;
  1547. case laneMpePressure: return mpe::pressureOfModY (n.modY);
  1548. default: return n.velocity;
  1549. }
  1550. }
  1551. void PianoRollComponent::setLaneValue (Note& n, float v) const
  1552. {
  1553. v = juce::jlimit (0.0f, 1.0f, v);
  1554. switch (laneBox.getSelectedId())
  1555. {
  1556. case lanePan: n.pan = std::abs (v - 0.5f) < 0.02f ? 0.0f : v * 2.0f - 1.0f; break; // snaps to center
  1557. case laneFinePitch: n.finePitch = std::round (v * 240.0f - 120.0f); break;
  1558. case laneRelease: n.release = v; break;
  1559. case laneModX: n.modX = v; break;
  1560. case laneModY: n.modY = v; break;
  1561. case laneChance: n.chance = std::round (v * 100.0f) / 100.0f; break; // whole percents, as Live shows them
  1562. case laneVelocityRange: // whole Live velocity steps (1/127); snaps to none
  1563. n.velocityRange = std::abs (v - 0.5f) < 0.02f ? 0.0f : std::round ((v * 2.0f - 1.0f) * 127.0f) / 127.0f;
  1564. break;
  1565. case laneMpePitch:
  1566. case laneMpeSlide:
  1567. case laneMpePressure: break; // (curves: the MPE lanes' own gestures edit them)
  1568. default: n.velocity = v; break;
  1569. }
  1570. }
  1571. bool PianoRollComponent::laneIsBipolar() const
  1572. {
  1573. const auto id = laneBox.getSelectedId();
  1574. return id == lanePan || id == laneFinePitch || id == laneVelocityRange || id == laneMpePitch || id >= eventLaneIdBase;
  1575. }
  1576. bool PianoRollComponent::laneIsChance() const { return laneBox.getSelectedId() == laneChance; }
  1577. void PianoRollComponent::applyVelocity (int fromX, int toX, int y)
  1578. {
  1579. const auto lane = velocityArea();
  1580. applyLaneValue (toX, juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8)), fromX);
  1581. }
  1582. void PianoRollComponent::applyLaneValue (int toX, float value, int fromX)
  1583. {
  1584. const auto lo = juce::jmin (fromX, toX) - 3, hi = juce::jmax (fromX, toX) + 3;
  1585. const auto& notes = currentPattern (engine.getSong()).notes;
  1586. std::vector<int> hits;
  1587. for (auto i : selectionOrAll())
  1588. {
  1589. const auto x = (int) tickToX ((double) notes[(std::size_t) i].start);
  1590. if (x >= lo && x <= hi)
  1591. hits.push_back (i);
  1592. }
  1593. if (! hits.empty())
  1594. editNotes ([this, &hits, value] (Pattern& p) {
  1595. for (auto i : hits)
  1596. setLaneValue (p.notes[(std::size_t) i], value);
  1597. if (laneIsChance())
  1598. notetools::spreadGroupChance (p, hits); // a probability group has one Chance
  1599. });
  1600. }
  1601. void PianoRollComponent::togglePorta()
  1602. {
  1603. const auto target = selectionOrAll();
  1604. if (target.empty())
  1605. return;
  1606. // like mute: if any note lacks porta, enable it on all; otherwise disable
  1607. const auto& notes = currentPattern (engine.getSong()).notes;
  1608. const auto porta = std::any_of (target.begin(), target.end(), [&notes] (int i) { return ! notes[(std::size_t) i].porta; });
  1609. editNotes ([&target, porta] (Pattern& p) {
  1610. for (auto i : target)
  1611. p.notes[(std::size_t) i].porta = porta;
  1612. });
  1613. }
  1614. void PianoRollComponent::setNotesMuted (bool mute)
  1615. {
  1616. const auto target = selectionOrAll();
  1617. if (target.empty())
  1618. return;
  1619. editNotes ([&target, mute] (Pattern& p) {
  1620. for (auto i : target)
  1621. p.notes[(std::size_t) i].muted = mute;
  1622. });
  1623. }
  1624. void PianoRollComponent::paintNoteAt (std::int64_t start, int key, bool monophonic)
  1625. {
  1626. // a brush stroke lays single notes (or the chosen chord) at the default length
  1627. Note n;
  1628. noteTemplate.applyTo (n);
  1629. n.start = juce::jmax<std::int64_t> (0, start);
  1630. n.length = paintLength;
  1631. n.key = key;
  1632. n.channel = engine.getSelectedChannel();
  1633. n.slide = slideButton.getToggleState();
  1634. n.colour = noteColour;
  1635. std::vector<Note> stamp;
  1636. for (auto interval : chordIntervals())
  1637. if (n.key + interval <= 127 && n.key + interval >= 0)
  1638. {
  1639. auto chordNote = n;
  1640. chordNote.key = snapKey (n.key + interval); // with scale snap the chord follows the scale
  1641. if (std::none_of (stamp.begin(), stamp.end(), [&chordNote] (const Note& o) { return o.key == chordNote.key; }))
  1642. stamp.push_back (chordNote);
  1643. }
  1644. editNotes ([&] (Pattern& p) {
  1645. if (monophonic) // Shift (or no Shift with "Monophonic painting"): the new note replaces what this channel plays then
  1646. {
  1647. std::vector<int> overlapping;
  1648. for (int i = 0; i < (int) p.notes.size(); ++i)
  1649. {
  1650. const auto& o = p.notes[(std::size_t) i];
  1651. if (o.channel == n.channel && o.start < n.start + n.length && o.start + o.length > n.start)
  1652. overlapping.push_back (i);
  1653. }
  1654. noteedit::remove (p, overlapping);
  1655. }
  1656. noteedit::paste (p, stamp, 0);
  1657. });
  1658. }
  1659. juce::Rectangle<int> PianoRollComponent::zoomWheelArea() const
  1660. {
  1661. // FL's VZoomSelect: the small square at the right end of the time scroll bar, over the vertical scroll bar
  1662. return { getWidth() - zoomWheelSize, toolbarHeight, zoomWheelSize, overviewHeight };
  1663. }
  1664. int PianoRollComponent::zoomAnchorKey() const
  1665. {
  1666. // FL (FUN_00e83850, REA round 167t): the middle of the notes in view, or the middle of the view
  1667. const auto grid = gridArea();
  1668. const auto top = yToKey (grid.getY()), bottom = yToKey (grid.getBottom() - 1);
  1669. const auto& notes = currentPattern (engine.getSong()).notes;
  1670. std::vector<int> keys;
  1671. for (auto i : channelNotes())
  1672. if (const auto key = notes[(std::size_t) i].key; key <= top && key >= bottom)
  1673. keys.push_back (key);
  1674. return gesture::zoomWheelAnchor (keys, top, bottom);
  1675. }
  1676. void PianoRollComponent::setRowHeightAround (int height, int key, int centreY)
  1677. {
  1678. rowHeight = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, height);
  1679. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), rowFor (key) * rowHeight + rowHeight / 2 - (centreY - headerHeight));
  1680. updateScrollBars();
  1681. repaint();
  1682. }
  1683. void PianoRollComponent::beginKeyZoom (const juce::MouseEvent& e)
  1684. {
  1685. drag = Drag::keyZoom;
  1686. keyZoomKey = zoomWheelArea().contains (e.getPosition()) ? zoomAnchorKey() : yToKey (e.y);
  1687. keyZoomStartRow = rowHeight;
  1688. keyZoomCentreY = keyToY (keyZoomKey) + rowHeight / 2;
  1689. keyZoomDrag.begin (e.y);
  1690. e.source.enableUnboundedMouseMovement (true); // FL hides the pointer while the zoom follows the travel
  1691. }
  1692. void PianoRollComponent::beginTimeZoom (const juce::MouseEvent& e)
  1693. {
  1694. drag = Drag::timeZoom;
  1695. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  1696. timeZoomDrag.begin (width / pixelsPerTick, scrollTicks + width * 0.5 / pixelsPerTick, e.x, e.y);
  1697. e.source.enableUnboundedMouseMovement (true);
  1698. }
  1699. void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
  1700. {
  1701. if (engine.getSong().channels.empty())
  1702. return;
  1703. downMods = e.mods;
  1704. startedOnEmpty = erasedSomething = holdExpired = false;
  1705. const auto onKeyboard = e.x < keyboardWidth && e.y >= headerHeight && e.y < gridArea().getBottom();
  1706. hover = {};
  1707. gliding = false;
  1708. // the zoom wheel (round 190j, discussion #10; FL's VZoomSelect): drag up = taller keys, one level (2 px) per 4 px of
  1709. // travel, per 16 px with Ctrl
  1710. if (zoomWheelArea().contains (e.getPosition()))
  1711. {
  1712. if (e.mods.isLeftButtonDown() || e.mods.isMiddleButtonDown())
  1713. beginKeyZoom (e);
  1714. return;
  1715. }
  1716. // the event editor's divider (round 190fz, FL's TQuickSplitter): left-drag moves it, a double-click or a right-click
  1717. // (swapped on release) gives the alternate size, a middle-click the default place
  1718. if (eventPaneBarArea().contains (e.getPosition()))
  1719. {
  1720. if (e.mods.isMiddleButtonDown())
  1721. resetEventPane();
  1722. else if (e.mods.isRightButtonDown())
  1723. drag = Drag::eventPaneAlternate;
  1724. else if (e.mods.isLeftButtonDown() && e.getNumberOfClicks() >= 2)
  1725. toggleEventPaneAlternate();
  1726. else if (e.mods.isLeftButtonDown())
  1727. {
  1728. drag = Drag::eventPaneBar;
  1729. eventPaneGrab = e.y - eventPaneBarTop;
  1730. repaint (eventPaneBarArea());
  1731. }
  1732. return;
  1733. }
  1734. // FL (TLEventPanelDblClick): a double-click on the event target panel, left of the event editor, swaps it too
  1735. if (! fitKeysToNotes && e.mods.isLeftButtonDown() && e.getNumberOfClicks() >= 2 && e.x < keyboardWidth && e.y >= velocityArea().getY())
  1736. {
  1737. toggleEventPaneAlternate();
  1738. return;
  1739. }
  1740. if (e.mods.isMiddleButtonDown())
  1741. {
  1742. // FL 2026 (round 167t, issue #26): middle-drag on the keyboard and Ctrl+middle-drag on the notes zoom
  1743. // vertically around the key under the mouse; middle-drag on the ruler and Alt+middle-drag on the notes
  1744. // zoom the time (drag up = zoom in, sideways = scroll)
  1745. const auto onNotes = gridArea().contains (e.getPosition());
  1746. const auto onRuler = e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth;
  1747. if (onKeyboard || (onNotes && flmods::ctrl (e.mods) && ! e.mods.isAltDown()))
  1748. {
  1749. beginKeyZoom (e);
  1750. return;
  1751. }
  1752. if (onRuler || (onNotes && e.mods.isAltDown()))
  1753. {
  1754. beginTimeZoom (e);
  1755. return;
  1756. }
  1757. drag = Drag::pan; // elsewhere it pans both ways, in every tool
  1758. panStartTicks = scrollTicks;
  1759. panStartY = scrollY;
  1760. setMouseCursor (editorCursor (gesture::Cursor::pan));
  1761. return;
  1762. }
  1763. if (onKeyboard)
  1764. {
  1765. if (flmods::ctrl (e.mods)) // Ctrl+click / drag: selects the notes of a key (range)
  1766. {
  1767. drag = Drag::keySelect;
  1768. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1769. mouseDrag (e);
  1770. return;
  1771. }
  1772. if (e.mods.isRightButtonDown()) // key labels (FL 2026: right-click a key > Rename)
  1773. {
  1774. showKeyMenu (keyboardKeyAt (e.x, e.y));
  1775. return;
  1776. }
  1777. if (e.mods.isLeftButtonDown())
  1778. {
  1779. drag = Drag::keyboard;
  1780. previewOn (keyboardKeyAt (e.x, e.y), keyVelocityAt (e.x, keyboardKeyAt (e.x, e.y)));
  1781. }
  1782. return;
  1783. }
  1784. // ruler: a right press on a pattern marker opens its menu (FL's TimePanelMouseDown: the marker menu when the press
  1785. // is on the marker lane, REA_rodada168t.md table); the Time markers items are also in the More menu (round 168g)
  1786. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))
  1787. if (const auto mk = markerAtX (e.x); mk >= 0)
  1788. {
  1789. showPatternMarkerMenu (mk);
  1790. return;
  1791. }
  1792. // ruler: a time-range drag selects the notes in it. FL 2026 (one ruler handler for the Piano roll and the Playlist,
  1793. // TimePanelMouseDown 0xe56bf0, REA_rodada168t.md): Ctrl+drag, a double click held and dragged, the Select tool, or
  1794. // a right-drag (on a Mac Cmd or Control: core/ModifierMap.h)
  1795. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth
  1796. && ((e.mods.isLeftButtonDown() && (flmods::ctrl (e.mods) || e.getNumberOfClicks() >= 2 || tools.getTool() == EditTool::lasso))
  1797. || (e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))))
  1798. {
  1799. drag = Drag::rulerSelect;
  1800. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1801. return;
  1802. }
  1803. // ruler: click or drag = position (FL), Alt = off the grid
  1804. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isLeftButtonDown() && ! e.mods.isShiftDown())
  1805. {
  1806. drag = Drag::seek;
  1807. seekAt (e.x, ! e.mods.isAltDown());
  1808. return;
  1809. }
  1810. // Freeze (round 190ay): a frozen channel's notes and their lane are read-only (the keyboard, the ruler and the
  1811. // view gestures above still work)
  1812. if ((velocityArea().contains (e.getPosition()) || gridArea().contains (e.getPosition())) && refuseFrozenEdit())
  1813. return;
  1814. if (velocityArea().contains (e.getPosition()) && mpeMouseDown (e))
  1815. return;
  1816. if (velocityArea().contains (e.getPosition()) && eventLaneTarget())
  1817. {
  1818. // pattern events: drag draws one event per grid step, right-drag erases
  1819. lastVelocityX = e.x;
  1820. drag = e.mods.isRightButtonDown() ? Drag::eventErase : Drag::eventDraw;
  1821. drawEvents (e.x, e.x, e.y, drag == Drag::eventErase);
  1822. return;
  1823. }
  1824. if (velocityArea().contains (e.getPosition()))
  1825. {
  1826. const auto lane = velocityArea();
  1827. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  1828. lastVelocityX = e.x;
  1829. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click resets the notes under the mouse
  1830. {
  1831. drag = Drag::velocity;
  1832. applyLaneValue (e.x, laneValue (Note()), e.x); // (each property's default)
  1833. drag = Drag::none;
  1834. return;
  1835. }
  1836. laneOriginals = currentPattern (engine.getSong()).notes;
  1837. if (e.mods.isRightButtonDown()) // right-drag draws a straight line of values
  1838. {
  1839. drag = Drag::velocityLine;
  1840. laneSetValue = value;
  1841. return;
  1842. }
  1843. if (e.mods.isShiftDown()) // Shift+drag: every note crossed gets the value of the press
  1844. {
  1845. drag = Drag::velocitySet;
  1846. laneSetValue = value;
  1847. applyLaneValue (e.x, value, e.x);
  1848. return;
  1849. }
  1850. drag = Drag::velocity;
  1851. applyVelocity (e.x, e.x, e.y);
  1852. return;
  1853. }
  1854. if (! gridArea().contains (e.getPosition()))
  1855. return;
  1856. // the selection's stretch handle: drag scales the selected notes in time from the selection's start
  1857. if (e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods) && stretchHandle().expanded (2.0f).contains (e.position))
  1858. {
  1859. const auto& notes = currentPattern (engine.getSong()).notes;
  1860. dragIndices.clear();
  1861. dragOriginals.clear();
  1862. for (auto i : selection)
  1863. if (i >= 0 && i < (int) notes.size() && edits (notes[(std::size_t) i]))
  1864. {
  1865. dragIndices.push_back (i);
  1866. dragOriginals.push_back (notes[(std::size_t) i]);
  1867. }
  1868. noteedit::span (dragOriginals, stretchAnchor, stretchEnd);
  1869. dragNote = dragIndices.empty() ? -1 : dragIndices.front();
  1870. drag = Drag::stretch;
  1871. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  1872. return;
  1873. }
  1874. bool rightEdge = false, leftEdge = false;
  1875. const auto hit = noteAt (e.x, e.y, rightEdge, leftEdge);
  1876. const auto tool = tools.getTool();
  1877. // editable ghost notes (Ctrl+Alt+V): a left press on one switches to its channel and grabs the note there
  1878. if (hit < 0 && editGhosts && e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods))
  1879. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  1880. {
  1881. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  1882. if (noteAt (e.x, e.y, rightEdge, leftEdge) >= 0) // now it is one of this channel's notes
  1883. mouseDown (e);
  1884. return;
  1885. }
  1886. // Zoom tool: right-click zooms out around the point (a click zooms in, a drag zooms to the range)
  1887. if (tool == EditTool::zoom && e.mods.isRightButtonDown() && ! flmods::ctrl (e.mods))
  1888. {
  1889. zoomOut (e.x);
  1890. return;
  1891. }
  1892. // every tool: right click deletes (double right-click on a ghost note switches to its channel; with
  1893. // editable ghost notes a right-click deletes the ghost note itself)
  1894. if (e.mods.isRightButtonDown())
  1895. {
  1896. if (hit < 0 && editGhosts)
  1897. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  1898. {
  1899. setSelection ({});
  1900. editNotes ([ghost] (Pattern& p) { noteedit::remove (p, { ghost }); });
  1901. return;
  1902. }
  1903. if (hit < 0 && e.getNumberOfClicks() >= 2)
  1904. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  1905. {
  1906. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  1907. return;
  1908. }
  1909. drag = Drag::erase;
  1910. startedOnEmpty = hit < 0;
  1911. setSelection ({}); // indices change while deleting
  1912. if (hit >= 0)
  1913. {
  1914. erasedSomething = true;
  1915. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  1916. }
  1917. return;
  1918. }
  1919. // every tool: Ctrl+click on a note adds/removes it from the selection; Ctrl+drag selects (Shift adds)
  1920. if (hit >= 0 && flmods::ctrl (e.mods))
  1921. {
  1922. auto s = selection;
  1923. if (isSelected (hit))
  1924. s.erase (std::find (s.begin(), s.end(), hit));
  1925. else
  1926. s.push_back (hit);
  1927. setSelection (s);
  1928. return;
  1929. }
  1930. if ((hit < 0 && flmods::ctrl (e.mods)) || tool == EditTool::lasso
  1931. || (hit < 0 && e.mods.isShiftDown() && tool != EditTool::brush && tool != EditTool::drumPaint))
  1932. {
  1933. drag = Drag::select;
  1934. dragNote = hit; // a click without dragging selects this note (Lasso)
  1935. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1936. rubberBand = {};
  1937. setSelection (selectionBefore);
  1938. return;
  1939. }
  1940. const auto snapOn = ! e.mods.isAltDown();
  1941. switch (tool)
  1942. {
  1943. case EditTool::eraser:
  1944. drag = Drag::erase;
  1945. setSelection ({});
  1946. if (hit >= 0)
  1947. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  1948. return;
  1949. case EditTool::mute:
  1950. drag = Drag::muting;
  1951. touchedNotes.clear();
  1952. if (hit >= 0)
  1953. {
  1954. muteTarget = ! currentPattern (engine.getSong()).notes[(std::size_t) hit].muted;
  1955. touchedNotes.push_back (hit);
  1956. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  1957. }
  1958. else
  1959. muteTarget = true;
  1960. return;
  1961. case EditTool::knife:
  1962. drag = Drag::knife;
  1963. knifeFrom = knifeTo = e.getPosition();
  1964. repaint();
  1965. return;
  1966. case EditTool::zoom:
  1967. drag = Drag::zoomRange;
  1968. rubberBand = {};
  1969. return;
  1970. case EditTool::listen:
  1971. drag = Drag::listen;
  1972. listenAt (e.x);
  1973. return;
  1974. case EditTool::pencil:
  1975. case EditTool::brush:
  1976. case EditTool::drumPaint:
  1977. case EditTool::lasso:
  1978. case EditTool::slip:
  1979. break;
  1980. }
  1981. // Pencil (and Brush on an existing note): Shift+drag on a note drags a copy
  1982. if (hit >= 0 && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  1983. {
  1984. const auto sources = isSelected (hit) ? selection : notetools::groupOf (currentPattern (engine.getSong()), hit);
  1985. const auto grabbedAt = (std::size_t) (std::find (sources.begin(), sources.end(), hit) - sources.begin());
  1986. std::vector<int> added;
  1987. // the copy comes out in the same order as the originals (copy sorts by start)
  1988. std::vector<Note> ordered;
  1989. for (auto i : sources)
  1990. ordered.push_back (currentPattern (engine.getSong()).notes[(std::size_t) i]);
  1991. editNotes ([&] (Pattern& p) {
  1992. added = noteedit::paste (p, ordered, 0);
  1993. notetools::regroup (p, added);
  1994. });
  1995. setSelection (added);
  1996. dragIndices = added;
  1997. dragOriginals = ordered;
  1998. lastScaleDragKeys = -1000;
  1999. dragNote = added[grabbedAt];
  2000. drag = Drag::move;
  2001. grabOffset = ordered[grabbedAt].start - snap (xToTick (e.x), snapOn);
  2002. previewEdit (ordered[grabbedAt].key, ordered[grabbedAt].velocity);
  2003. return;
  2004. }
  2005. if (hit >= 0)
  2006. {
  2007. if (! isSelected (hit)) // a grouped note brings its group along (FL's note groups)
  2008. {
  2009. const auto members = notetools::groupOf (currentPattern (engine.getSong()), hit);
  2010. setSelection (members.size() > 1 ? members : std::vector<int> {});
  2011. }
  2012. const auto& notes = currentPattern (engine.getSong()).notes;
  2013. const auto& n = notes[(std::size_t) hit];
  2014. dragNote = hit;
  2015. dragIndices = selection.empty() ? std::vector<int> { hit } : selection;
  2016. dragOriginals.clear();
  2017. for (auto i : dragIndices)
  2018. dragOriginals.push_back (notes[(std::size_t) i]);
  2019. drag = rightEdge ? Drag::resize : leftEdge ? Drag::resizeLeft : Drag::move;
  2020. lastScaleDragKeys = 0; // (no scale step made yet)
  2021. grabOffset = n.start - snap (xToTick (e.x), snapOn);
  2022. lastLength = n.length;
  2023. noteTemplate.takeFrom (n); // FL: new notes get the clicked note's properties (round 166e)
  2024. previewEdit (n.key, n.velocity);
  2025. return;
  2026. }
  2027. // new note (or the chosen chord, with the clicked note as the root)
  2028. setSelection ({});
  2029. createdAt = juce::Time::getMillisecondCounter();
  2030. if (tool == EditTool::drumPaint)
  2031. {
  2032. drag = Drag::drumPaint;
  2033. lastDrumCell = -1;
  2034. lastDrumKey = -1;
  2035. drumPaintAt (e.getPosition(), snapOn);
  2036. return;
  2037. }
  2038. if (tool == EditTool::brush)
  2039. {
  2040. drag = Drag::paint;
  2041. paintLength = juce::jmax<std::int64_t> (1, newNoteLength());
  2042. const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  2043. paintNoteAt (start, snapKey (yToKey (e.y)), noteedit::monophonicPaint (e.mods.isShiftDown(), monophonicPainting));
  2044. nextPaintTick = start + paintLength;
  2045. previewEdit (snapKey (yToKey (e.y)), noteTemplate.velocity);
  2046. return;
  2047. }
  2048. Note n;
  2049. noteTemplate.applyTo (n);
  2050. n.start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  2051. n.length = newNoteLength();
  2052. n.key = snapKey (yToKey (e.y));
  2053. n.channel = engine.getSelectedChannel();
  2054. n.slide = slideButton.getToggleState();
  2055. n.colour = noteColour;
  2056. std::vector<Note> stamp;
  2057. for (auto interval : chordIntervals())
  2058. if (n.key + interval <= 127 && n.key + interval >= 0)
  2059. {
  2060. auto chordNote = n;
  2061. chordNote.key = snapKey (n.key + interval); // with scale snap the chord follows the scale
  2062. if (std::none_of (stamp.begin(), stamp.end(), [&chordNote] (const Note& o) { return o.key == chordNote.key; }))
  2063. stamp.push_back (chordNote);
  2064. }
  2065. std::vector<int> added;
  2066. editNotes ([&] (Pattern& p) { added = noteedit::paste (p, stamp, 0); });
  2067. dragNote = added.front(); // the root leads the drag
  2068. dragIndices = added;
  2069. dragOriginals = stamp;
  2070. lastScaleDragKeys = -1000;
  2071. if (added.size() > 1)
  2072. setSelection (added);
  2073. drag = Drag::move;
  2074. grabOffset = 0;
  2075. previewEdit (n.key, n.velocity);
  2076. }
  2077. void PianoRollComponent::mouseDrag (const juce::MouseEvent& e)
  2078. {
  2079. const auto snapOn = ! e.mods.isAltDown();
  2080. // after the step below, the hint bar says what the gesture is doing
  2081. const struct PostAfter
  2082. {
  2083. PianoRollComponent& roll;
  2084. const juce::MouseEvent& event;
  2085. ~PostAfter() { roll.postDragHint (event); }
  2086. } postAfter { *this, e };
  2087. switch (drag)
  2088. {
  2089. case Drag::none:
  2090. return;
  2091. case Drag::mpePoint: // round 190hy: the notes' MPE curves
  2092. case Drag::mpeDraw:
  2093. case Drag::mpeErase:
  2094. mpeMouseDrag (e);
  2095. return;
  2096. case Drag::eventPaneBar: // round 190fz: the divider follows the mouse (FL's SplitterChanging rule)
  2097. moveEventPaneBar (e.y - eventPaneGrab);
  2098. return;
  2099. case Drag::eventPaneAlternate: // (swapped when the right button is released)
  2100. return;
  2101. case Drag::pan:
  2102. scrollTicks = juce::jmax (0.0, panStartTicks - e.getDistanceFromDragStartX() / pixelsPerTick);
  2103. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()), panStartY - e.getDistanceFromDragStartY());
  2104. updateScrollBars();
  2105. repaint();
  2106. return;
  2107. case Drag::keyboard:
  2108. {
  2109. const auto key = keyboardKeyAt (e.x, e.y);
  2110. if (key != previewKey)
  2111. previewOn (key, keyVelocityAt (e.x, key));
  2112. return;
  2113. }
  2114. case Drag::keyZoom:
  2115. {
  2116. // up = taller keys (Ctrl: fine); the centre of the clicked key stays where it was
  2117. keyZoomDrag.move (e.y, flmods::ctrl (e.mods));
  2118. rowHeight = keyZoomDrag.height (keyZoomStartRow);
  2119. scrollY = juce::jlimit (0, juce::jmax (0, rows.count * rowHeight - gridArea().getHeight()),
  2120. rowFor (keyZoomKey) * rowHeight + rowHeight / 2 - (keyZoomCentreY - headerHeight));
  2121. updateScrollBars();
  2122. repaint();
  2123. return;
  2124. }
  2125. case Drag::timeZoom:
  2126. {
  2127. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  2128. timeZoomDrag.move (e.x, e.y, flmods::ctrl (e.mods));
  2129. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, width / timeZoomDrag.span);
  2130. scrollTicks = juce::jmax (0.0, timeZoomDrag.centre - width * 0.5 / pixelsPerTick);
  2131. updateScrollBars();
  2132. repaint();
  2133. return;
  2134. }
  2135. case Drag::keySelect:
  2136. {
  2137. const auto k0 = yToKey (e.getMouseDownY()), k1 = yToKey (e.y);
  2138. const auto& notes = currentPattern (engine.getSong()).notes;
  2139. auto s = selectionBefore;
  2140. for (auto i : channelNotes())
  2141. if (const auto k = notes[(std::size_t) i].key; k >= juce::jmin (k0, k1) && k <= juce::jmax (k0, k1))
  2142. s.push_back (i);
  2143. setSelection (s);
  2144. return;
  2145. }
  2146. case Drag::rulerSelect:
  2147. {
  2148. const auto t0 = (double) snap (xToTick (juce::jmin (e.getMouseDownX(), e.x)), snapOn);
  2149. const auto t1 = (double) snap (xToTick (juce::jmax (e.getMouseDownX(), e.x)) + (snapOn ? (double) gridTicks() : 0.0), snapOn);
  2150. const auto& notes = currentPattern (engine.getSong()).notes;
  2151. auto s = selectionBefore;
  2152. for (auto i : channelNotes())
  2153. if (const auto& n = notes[(std::size_t) i]; (double) n.start >= t0 && (double) n.start < t1)
  2154. s.push_back (i);
  2155. rubberBand = juce::Rectangle<int>::leftTopRightBottom ((int) tickToX (t0), gridArea().getY(), (int) tickToX (t1), gridArea().getBottom());
  2156. timeFrom = (std::int64_t) t0; // (round 168g: the range stays as the time selection)
  2157. timeTo = (std::int64_t) t1;
  2158. setSelection (s);
  2159. return;
  2160. }
  2161. case Drag::velocity:
  2162. applyVelocity (lastVelocityX, e.x, e.y);
  2163. lastVelocityX = e.x;
  2164. return;
  2165. case Drag::eventDraw:
  2166. case Drag::eventErase:
  2167. drawEvents (lastVelocityX, e.x, e.y, drag == Drag::eventErase);
  2168. lastVelocityX = e.x;
  2169. return;
  2170. case Drag::velocitySet:
  2171. applyLaneValue (e.x, laneSetValue, lastVelocityX);
  2172. lastVelocityX = e.x;
  2173. return;
  2174. case Drag::velocityLine:
  2175. {
  2176. // from the press to the mouse: notes in between follow the line, the others keep their value
  2177. const auto lane = velocityArea();
  2178. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  2179. const auto x0 = e.getMouseDownX(), x1 = e.x;
  2180. const auto lo = juce::jmin (x0, x1) - 3, hi = juce::jmax (x0, x1) + 3;
  2181. const auto targets = selectionOrAll();
  2182. knifeFrom = { x0, juce::roundToInt ((float) lane.getBottom() - 2.0f - laneSetValue * (float) (lane.getHeight() - 8)) };
  2183. knifeTo = e.getPosition();
  2184. editNotes ([&] (Pattern& p) {
  2185. for (auto i : targets)
  2186. {
  2187. if ((std::size_t) i >= laneOriginals.size() || (std::size_t) i >= p.notes.size())
  2188. continue;
  2189. auto& n = p.notes[(std::size_t) i];
  2190. n = laneOriginals[(std::size_t) i];
  2191. const auto x = (int) tickToX ((double) n.start);
  2192. if (x >= lo && x <= hi)
  2193. setLaneValue (n, (float) gesture::lineValue (x0, laneSetValue, x1, value, x));
  2194. }
  2195. if (laneIsChance())
  2196. notetools::spreadGroupChance (p, targets);
  2197. });
  2198. repaint();
  2199. return;
  2200. }
  2201. case Drag::select:
  2202. case Drag::zoomRange:
  2203. {
  2204. if (e.getDistanceFromDragStart() < 3 && rubberBand.isEmpty())
  2205. return;
  2206. const auto area = gridArea();
  2207. rubberBand = juce::Rectangle<int> (e.getMouseDownPosition(), e.getPosition()).getIntersection (area);
  2208. if (drag == Drag::zoomRange)
  2209. {
  2210. rubberBand = rubberBand.withY (area.getY()).withHeight (area.getHeight());
  2211. repaint();
  2212. return;
  2213. }
  2214. const auto t0 = xToTick (rubberBand.getX()), t1 = xToTick (rubberBand.getRight());
  2215. const auto kTop = yToKey (rubberBand.getY()), kBottom = yToKey (rubberBand.getBottom());
  2216. const auto& notes = currentPattern (engine.getSong()).notes;
  2217. auto s = selectionBefore;
  2218. for (auto i : channelNotes())
  2219. {
  2220. const auto& n = notes[(std::size_t) i];
  2221. if ((double) (n.start + n.length) > t0 && (double) n.start < t1 && n.key <= kTop && n.key >= kBottom)
  2222. s.push_back (i);
  2223. }
  2224. setSelection (s);
  2225. return;
  2226. }
  2227. case Drag::erase:
  2228. {
  2229. // right press-and-hold on empty grid, then drag: a temporary Knife
  2230. if (e.mods.isRightButtonDown() && startedOnEmpty && ! erasedSomething && ! holdExpired)
  2231. {
  2232. if (e.getLengthOfMousePress() >= 350)
  2233. {
  2234. drag = Drag::knife;
  2235. knifeFrom = e.getMouseDownPosition();
  2236. knifeTo = e.getPosition();
  2237. repaint();
  2238. return;
  2239. }
  2240. if (e.getDistanceFromDragStart() > 3)
  2241. holdExpired = true; // moved right away: it is an erase stroke
  2242. }
  2243. bool edge = false;
  2244. const auto hit = noteAt (e.x, e.y, edge);
  2245. if (hit >= 0)
  2246. {
  2247. erasedSomething = true;
  2248. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  2249. }
  2250. return;
  2251. }
  2252. case Drag::muting:
  2253. {
  2254. bool edge = false;
  2255. const auto hit = noteAt (e.x, e.y, edge);
  2256. if (hit >= 0 && std::find (touchedNotes.begin(), touchedNotes.end(), hit) == touchedNotes.end())
  2257. {
  2258. touchedNotes.push_back (hit);
  2259. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  2260. }
  2261. return;
  2262. }
  2263. case Drag::knife:
  2264. knifeTo = e.getPosition();
  2265. repaint();
  2266. return;
  2267. case Drag::listen:
  2268. listenAt (e.x);
  2269. return;
  2270. case Drag::seek:
  2271. seekAt (e.x, snapOn);
  2272. return;
  2273. case Drag::drumPaint:
  2274. drumPaintAt (e.getPosition(), snapOn);
  2275. return;
  2276. case Drag::stretch:
  2277. {
  2278. if (dragOriginals.empty() || stretchEnd <= stretchAnchor)
  2279. return;
  2280. // the new end of the selection: on the grid (the nearest line), or free with Alt
  2281. const auto minimum = snapOn ? juce::jmax<std::int64_t> (1, gridTicks()) : (std::int64_t) 10;
  2282. auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  2283. end = juce::jmax (stretchAnchor + minimum, end);
  2284. const auto stretched = polish::stretchNotes (dragOriginals, stretchAnchor, stretchEnd, end);
  2285. editNotes ([this, &stretched] (Pattern& p) {
  2286. for (std::size_t j = 0; j < dragIndices.size() && j < stretched.size(); ++j)
  2287. if ((std::size_t) dragIndices[j] < p.notes.size())
  2288. p.notes[(std::size_t) dragIndices[j]] = stretched[j];
  2289. });
  2290. repaint();
  2291. return;
  2292. }
  2293. case Drag::paint:
  2294. {
  2295. // lays notes to the right, one per default length, at the pitch under the mouse
  2296. const auto tick = snap (xToTick (e.x), snapOn);
  2297. for (int guard = 0; tick >= nextPaintTick && guard < 64; ++guard)
  2298. {
  2299. paintNoteAt (nextPaintTick, snapKey (yToKey (e.y)), noteedit::monophonicPaint (e.mods.isShiftDown(), monophonicPainting));
  2300. nextPaintTick += paintLength;
  2301. }
  2302. if (snapKey (yToKey (e.y)) != previewKey)
  2303. previewEdit (snapKey (yToKey (e.y)), noteTemplate.velocity);
  2304. return;
  2305. }
  2306. case Drag::move:
  2307. {
  2308. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  2309. auto deltaTicks = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset) - grabbed.start;
  2310. auto deltaKeys = snapKey (yToKey (e.y)) - grabbed.key;
  2311. auto rawKeys = yToKey (e.y) - grabbed.key; // (the mouse's own row, before any snap)
  2312. // locks: Shift pressed after the click keeps the pitch, Ctrl keeps the time
  2313. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  2314. deltaKeys = rawKeys = 0;
  2315. if (flmods::ctrl (e.mods) && ! flmods::ctrl (downMods))
  2316. deltaTicks = 0;
  2317. const auto& current = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  2318. // snap to scale (core/ScaleSnap.h, round 190an): the grabbed note follows the mouse onto the scale and the
  2319. // whole group moves that many scale steps; on the note's own row the pitch is left alone, also off the scale
  2320. const auto scale = snapScale();
  2321. const auto onScale = scale.active() && ! folded();
  2322. const auto scaleSteps = onScale ? scalesnap::dragSteps (scale, grabbed.key, grabbed.key + rawKeys) : 0;
  2323. if (current.start == grabbed.start + deltaTicks
  2324. && (onScale ? scaleSteps == lastScaleDragKeys : current.key == grabbed.key + deltaKeys))
  2325. return;
  2326. lastScaleDragKeys = scaleSteps;
  2327. const auto oldKey = current.key;
  2328. // from the original positions: the group keeps its shape even when hitting the limits
  2329. // folded to the scale (round 166d): the notes move by rows (scale degrees), so they stay on shown keys
  2330. const auto deltaRows = folded() ? rowFor (grabbed.key) - rowFor (grabbed.key + deltaKeys) : 0;
  2331. editNotes ([this, &deltaTicks, &deltaKeys, scale, scaleSteps, onScale, deltaRows] (Pattern& p) {
  2332. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  2333. p.notes[(std::size_t) dragIndices[j]] = dragOriginals[j];
  2334. if (folded())
  2335. {
  2336. auto noKeys = 0;
  2337. noteedit::move (p, dragIndices, deltaTicks, noKeys);
  2338. if (deltaRows != 0)
  2339. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  2340. p.notes[(std::size_t) dragIndices[j]].key = rows.step (dragOriginals[j].key, deltaRows);
  2341. return;
  2342. }
  2343. if (! onScale)
  2344. {
  2345. noteedit::move (p, dragIndices, deltaTicks, deltaKeys);
  2346. return;
  2347. }
  2348. // snap to scale: the time moves as a group, the pitch by scale steps (a chord stays a chord of the scale)
  2349. auto noKeys = 0;
  2350. noteedit::move (p, dragIndices, deltaTicks, noKeys);
  2351. scalesnap::moveBySteps (p, dragIndices, scaleSteps, scale);
  2352. });
  2353. const auto& moved = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  2354. if (moved.key != oldKey)
  2355. previewEdit (moved.key, moved.velocity);
  2356. return;
  2357. }
  2358. case Drag::resize:
  2359. {
  2360. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  2361. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  2362. const auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  2363. const auto delta = juce::jmax (minimum, end - grabbed.start) - grabbed.length;
  2364. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].length == grabbed.length + delta)
  2365. return;
  2366. lastLength = grabbed.length + delta;
  2367. editNotes ([this, delta, minimum] (Pattern& p) {
  2368. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  2369. p.notes[(std::size_t) dragIndices[j]].length = juce::jmax (minimum, dragOriginals[j].length + delta);
  2370. });
  2371. return;
  2372. }
  2373. case Drag::resizeLeft:
  2374. {
  2375. // the start moves, the end stays (selected notes together)
  2376. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  2377. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  2378. auto delta = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn)) - grabbed.start;
  2379. for (const auto& o : dragOriginals)
  2380. delta = juce::jlimit (-o.start, o.length - juce::jmin (minimum, o.length), delta);
  2381. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].start == grabbed.start + delta)
  2382. return;
  2383. editNotes ([this, delta] (Pattern& p) {
  2384. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  2385. {
  2386. auto& n = p.notes[(std::size_t) dragIndices[j]];
  2387. n.start = dragOriginals[j].start + delta;
  2388. n.length = dragOriginals[j].length - delta;
  2389. }
  2390. });
  2391. lastLength = grabbed.length - delta;
  2392. return;
  2393. }
  2394. }
  2395. }
  2396. void PianoRollComponent::postDragHint (const juce::MouseEvent& e)
  2397. {
  2398. const auto& notes = currentPattern (engine.getSong()).notes;
  2399. const auto count = juce::String ((int) std::max<std::size_t> (1, dragIndices.size()));
  2400. auto steps = [] (std::int64_t ticks) {
  2401. const auto value = (double) ticks / ticksPerStep;
  2402. return (value > 0 ? "+" : "") + juce::String (value, std::abs (value - std::round (value)) < 1e-9 ? 0 : 2);
  2403. };
  2404. ui::Hint hint;
  2405. switch (drag)
  2406. {
  2407. case Drag::move:
  2408. {
  2409. const auto at = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin());
  2410. if (dragNote < 0 || dragNote >= (int) notes.size() || at >= dragOriginals.size())
  2411. return;
  2412. const auto& now = notes[(std::size_t) dragNote];
  2413. const auto& was = dragOriginals[at];
  2414. hint.text = tr ("Moving {0} note(s): then [Shift] keeps the pitch [Ctrl] keeps the time [Alt] no snap", { count });
  2415. hint.value = keyName (now.key) + " " + juce::String (now.key - was.key >= 0 ? "+" : "") + juce::String (now.key - was.key) + " st "
  2416. + steps (now.start - was.start) + " " + tr ("steps");
  2417. break;
  2418. }
  2419. case Drag::resize:
  2420. case Drag::resizeLeft:
  2421. if (dragNote < 0 || dragNote >= (int) notes.size())
  2422. return;
  2423. hint.text = tr ("Resizing {0} note(s) [Alt] no snap", { count });
  2424. hint.value = juce::String ((double) notes[(std::size_t) dragNote].length / ticksPerStep, 2) + " " + tr ("steps");
  2425. break;
  2426. case Drag::eventDraw:
  2427. case Drag::eventErase:
  2428. {
  2429. const auto lane = velocityArea();
  2430. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  2431. hint.text = drag == Drag::eventErase ? tr ("Deleting events") : tr ("Drawing events: {0}", { laneBox.getText() });
  2432. const auto target = eventLaneTarget();
  2433. hint.value = target && target->kind == AutomationTargetKind::tempo ? juce::String (tempoFromValue (value), 3) + " BPM" // (issue #86: as FL's hint)
  2434. : juce::String (juce::roundToInt (value * 100.0f)) + "%";
  2435. break;
  2436. }
  2437. case Drag::mpePoint:
  2438. case Drag::mpeDraw:
  2439. case Drag::mpeErase:
  2440. {
  2441. juce::Rectangle<int> area;
  2442. const auto id = mpeDragLane;
  2443. mpeLaneAt ({ lastMpeX, lastMpeY }, &area);
  2444. hint.text = drag == Drag::mpeErase ? tr ("Erasing the curve's points") : drag == Drag::mpePoint ? tr ("Moving the curve's point")
  2445. : tr ("Drawing the note's curve");
  2446. if (drag != Drag::mpeErase && ! area.isEmpty())
  2447. {
  2448. const auto norm = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - 2 - lastMpeY) / (float) juce::jmax (1, area.getHeight() - 8));
  2449. const auto v = mpeValue (id, norm, mpeDragRange);
  2450. hint.value = id == laneMpePitch ? tr ("{0} st", { juce::String (v / 100.0f, 2) })
  2451. : juce::String (juce::roundToInt (id == laneMpeSlide ? (float) mpe::timbreOfModX (v) : v * 127.0f));
  2452. }
  2453. break;
  2454. }
  2455. case Drag::velocity:
  2456. case Drag::velocitySet:
  2457. case Drag::velocityLine:
  2458. {
  2459. const auto lane = velocityArea();
  2460. const auto value = drag == Drag::velocitySet ? laneSetValue
  2461. : juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  2462. hint.text = tr ("Setting {0}", { laneBox.getText() });
  2463. hint.value = juce::String (juce::roundToInt (value * 100.0f)) + "%";
  2464. break;
  2465. }
  2466. case Drag::select:
  2467. case Drag::keySelect:
  2468. case Drag::rulerSelect:
  2469. hint.text = tr ("Selecting [Shift] adds to the selection");
  2470. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  2471. break;
  2472. case Drag::erase: hint.text = tr ("Deleting what the mouse crosses"); break;
  2473. case Drag::muting: hint.text = tr ("Muting / unmuting what the mouse crosses"); break;
  2474. case Drag::knife: hint.text = tr ("Cutting along the line [Alt] no snap"); break;
  2475. case Drag::paint: hint.text = tr ("Painting notes [Alt] no snap"); break;
  2476. case Drag::drumPaint: hint.text = tr ("Drum brush: one hit per grid cell, on the key under the mouse [Alt] no snap"); break;
  2477. case Drag::stretch:
  2478. {
  2479. std::int64_t from = 0, to = 0;
  2480. std::vector<Note> now;
  2481. for (auto i : dragIndices)
  2482. if (i >= 0 && i < (int) notes.size())
  2483. now.push_back (notes[(std::size_t) i]);
  2484. noteedit::span (now, from, to);
  2485. hint.text = tr ("Stretching {0} note(s) in time [Alt] no snap", { count });
  2486. hint.value = "x" + juce::String ((double) (to - stretchAnchor) / (double) juce::jmax<std::int64_t> (1, stretchEnd - stretchAnchor), 2);
  2487. break;
  2488. }
  2489. case Drag::keyZoom: hint.text = tr ("Key height"); hint.value = tr ("Zoom level {0}", { juce::String (gesture::zoomLevel (rowHeight)) }) + " " + juce::String (rowHeight) + " px"; break;
  2490. case Drag::timeZoom: hint.text = tr ("Zooming: drag up = closer, sideways = scroll [Ctrl] zoom only"); break;
  2491. case Drag::keyboard:
  2492. hint.text = tr ("Hearing the key: further right on a key = louder");
  2493. hint.value = keyName (previewKey) + " " + tr ("vel {0}", { juce::String (juce::roundToInt (keyVelocityAt (e.x, previewKey) * 127.0f)) });
  2494. break;
  2495. case Drag::pan:
  2496. case Drag::seek: hint.text = tr ("Position [Alt] no snap"); break;
  2497. case Drag::listen:
  2498. case Drag::zoomRange:
  2499. case Drag::eventPaneBar: // (eventPaneChanged posts the percentage)
  2500. case Drag::eventPaneAlternate:
  2501. case Drag::none: return;
  2502. }
  2503. ui::postHint (hint);
  2504. }
  2505. void PianoRollComponent::mouseUp (const juce::MouseEvent& e)
  2506. {
  2507. ui::clearPostedHint();
  2508. if (drag == Drag::eventPaneBar) // round 190fz: remembered once the drag ends
  2509. saveEventPaneState();
  2510. if (drag == Drag::eventPaneAlternate)
  2511. {
  2512. drag = Drag::none;
  2513. toggleEventPaneAlternate();
  2514. }
  2515. if (drag == Drag::knife)
  2516. cutWithKnife (knifeFrom, knifeTo, ! e.mods.isAltDown());
  2517. if (drag == Drag::zoomRange)
  2518. {
  2519. if (rubberBand.getWidth() > 4)
  2520. zoomToTicks (xToTick (rubberBand.getX()), xToTick (rubberBand.getRight()));
  2521. else
  2522. zoomIn (e.x); // a click zooms in around the point (right-click zooms out)
  2523. }
  2524. if (drag == Drag::select && rubberBand.isEmpty() && dragNote >= 0)
  2525. {
  2526. // Lasso click on a note: selects it (Shift: adds / removes)
  2527. auto s = selectionBefore;
  2528. if (auto it = std::find (s.begin(), s.end(), dragNote); it != s.end())
  2529. s.erase (it);
  2530. else
  2531. s.push_back (dragNote);
  2532. setSelection (s);
  2533. }
  2534. if (drag == Drag::listen)
  2535. stopListening();
  2536. if (drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft || drag == Drag::paint || drag == Drag::drumPaint
  2537. || drag == Drag::stretch)
  2538. sortNotes();
  2539. previewOff();
  2540. drag = Drag::none;
  2541. dragNote = -1;
  2542. dragIndices.clear();
  2543. dragOriginals.clear();
  2544. touchedNotes.clear();
  2545. laneOriginals.clear();
  2546. rubberBand = {};
  2547. hover = {};
  2548. updateHover (e.getPosition(), e.mods); // the cursor of what is under the mouse now
  2549. repaint();
  2550. }
  2551. void PianoRollComponent::mouseMove (const juce::MouseEvent& e)
  2552. {
  2553. if (const auto over = zoomWheelArea().contains (e.getPosition()); over != zoomWheelHover)
  2554. {
  2555. zoomWheelHover = over;
  2556. repaint (zoomWheelArea());
  2557. }
  2558. updateHover (e.getPosition(), e.mods);
  2559. }
  2560. void PianoRollComponent::mouseExit (const juce::MouseEvent&)
  2561. {
  2562. lastMouse = { -1, -1 };
  2563. if (std::exchange (zoomWheelHover, false))
  2564. repaint (zoomWheelArea());
  2565. if (! (hover == Hover {}))
  2566. {
  2567. hover = {};
  2568. repaint();
  2569. }
  2570. }
  2571. void PianoRollComponent::modifierKeysChanged (const juce::ModifierKeys& mods)
  2572. {
  2573. // Ctrl / Shift / Alt change what a click would do: the cursor follows without moving the mouse
  2574. if (drag == Drag::none && lastMouse.x >= 0)
  2575. updateCursor (mods);
  2576. }
  2577. PianoRollComponent::Hover PianoRollComponent::hoverAt (juce::Point<int> p) const
  2578. {
  2579. Hover h;
  2580. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  2581. {
  2582. h.key = keyboardKeyAt (p.x, p.y);
  2583. return h;
  2584. }
  2585. if (velocityArea().contains (p))
  2586. {
  2587. // the stem nearest to the mouse (within a few pixels)
  2588. const auto& notes = currentPattern (engine.getSong()).notes;
  2589. auto best = 5.0;
  2590. for (auto i : channelNotes())
  2591. if (const auto d = std::abs (tickToX ((double) notes[(std::size_t) i].start) - p.x); d < best)
  2592. {
  2593. best = d;
  2594. h.note = i;
  2595. }
  2596. return h;
  2597. }
  2598. if (! gridArea().contains (p))
  2599. return h;
  2600. h.key = yToKey (p.y);
  2601. if (stretchHandle().expanded (2.0f).contains (p.toFloat()))
  2602. {
  2603. h.stretch = true;
  2604. return h;
  2605. }
  2606. const auto& notes = currentPattern (engine.getSong()).notes;
  2607. gesture::EdgeRules rules;
  2608. rules.allowLeft = resizeFromLeft;
  2609. // back to front: the note drawn on top wins
  2610. for (int i = (int) notes.size() - 1; i >= 0; --i)
  2611. {
  2612. const auto& n = notes[(std::size_t) i];
  2613. if (! edits (n) || n.key != h.key)
  2614. continue;
  2615. if (const auto zone = gesture::zoneAt (p.x, tickToX ((double) n.start), tickToX ((double) (n.start + n.length)), rules);
  2616. zone != gesture::Zone::outside)
  2617. {
  2618. h.note = i;
  2619. h.zone = zone;
  2620. return h;
  2621. }
  2622. }
  2623. h.ghost = ghostAt (p.x, p.y);
  2624. return h;
  2625. }
  2626. gesture::Target PianoRollComponent::targetAt (const Hover& h) const
  2627. {
  2628. return h.note >= 0 ? gesture::targetFor (h.zone) : gesture::Target::empty;
  2629. }
  2630. void PianoRollComponent::updateHover (juce::Point<int> p, juce::ModifierKeys mods)
  2631. {
  2632. lastMouse = p;
  2633. const auto h = hoverAt (p);
  2634. if (! (h == hover))
  2635. {
  2636. // repaint only what changed: the old and new note rows, the keyboard, the lane
  2637. auto dirty = [this] (const Hover& o) {
  2638. if (o.key >= 0)
  2639. repaint (0, keyToY (o.key) - 1, getWidth(), rowHeight + 2);
  2640. const auto& notes = currentPattern (engine.getSong()).notes;
  2641. for (auto i : { o.note, o.ghost })
  2642. if (i >= 0 && i < (int) notes.size())
  2643. {
  2644. repaint (0, keyToY (notes[(std::size_t) i].key) - 1, getWidth(), rowHeight + 2);
  2645. repaint (velocityArea());
  2646. }
  2647. };
  2648. dirty (hover);
  2649. hover = h;
  2650. dirty (hover);
  2651. }
  2652. if (drag == Drag::none)
  2653. updateCursor (mods);
  2654. }
  2655. void PianoRollComponent::updateCursor (juce::ModifierKeys mods)
  2656. {
  2657. const auto p = lastMouse;
  2658. auto cursor = gesture::Cursor::normal;
  2659. if (eventPaneBarArea().contains (p)) // the event editor's divider (FL: crVSplit)
  2660. {
  2661. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  2662. return;
  2663. }
  2664. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  2665. cursor = flmods::ctrl (mods) ? gesture::Cursor::select : gesture::Cursor::point;
  2666. else if (velocityArea().contains (p))
  2667. cursor = gesture::Cursor::draw;
  2668. else if (gridArea().contains (p) && hover.stretch && ! flmods::ctrl (mods))
  2669. cursor = gesture::Cursor::resizeH;
  2670. else if (gridArea().contains (p) && editGhosts && hover.note < 0 && hover.ghost >= 0 && ! flmods::ctrl (mods))
  2671. cursor = gesture::Cursor::move;
  2672. else if (gridArea().contains (p))
  2673. {
  2674. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  2675. const auto tool = tools.getTool();
  2676. cursor = gesture::cursorFor (gesture::leftAction (tool, targetAt (hover), m, false), tool);
  2677. }
  2678. else if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth && flmods::ctrl (mods))
  2679. cursor = gesture::Cursor::select;
  2680. else if (zoomWheelArea().contains (p))
  2681. cursor = gesture::Cursor::resizeV; // (FL: crSizeNS)
  2682. setMouseCursor (editorCursor (cursor));
  2683. }
  2684. ui::Hint PianoRollComponent::hintAt (juce::Point<int> p)
  2685. {
  2686. ui::Hint hint;
  2687. const auto mods = juce::ModifierKeys::currentModifiers;
  2688. const auto& song = engine.getSong();
  2689. const auto& notes = currentPattern (song).notes;
  2690. if (zoomWheelArea().contains (p))
  2691. {
  2692. hint.text = tr ("Key height: drag up / down or turn the wheel [Ctrl] fine");
  2693. hint.value = tr ("Zoom level {0}", { juce::String (gesture::zoomLevel (rowHeight)) });
  2694. return hint;
  2695. }
  2696. if (eventPaneBarArea().contains (p)) // round 190fz: FL's hint is "Right-click / shift+enter for alternate size"
  2697. {
  2698. hint.text = tr ("Event editor size: drag [RMB] or [Shift][Enter] alternate size [MMB] default size");
  2699. hint.value = juce::String (evpane::percentOf (eventPaneState().aspect)) + "%";
  2700. return hint;
  2701. }
  2702. const auto h = hoverAt (p);
  2703. auto noteValue = [&] (int i) {
  2704. const auto& n = notes[(std::size_t) i];
  2705. return keyName (n.key) + " " + juce::String (juce::roundToInt (n.velocity * 100.0f)) + "%";
  2706. };
  2707. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  2708. {
  2709. hint.text = tr ("Keyboard: [LMB] hear the key (further right = louder) [Ctrl][LMB] select its notes [MMB] drag: taller / shorter keys");
  2710. hint.value = keyName (h.key) + " " + tr ("vel {0}", { juce::String (juce::roundToInt (keyVelocityAt (p.x, h.key) * 127.0f)) });
  2711. return hint;
  2712. }
  2713. if (velocityArea().contains (p) && mpeLaneAt (p) != 0)
  2714. {
  2715. 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");
  2716. if (const auto note = mpeNoteAt (p.x); note >= 0)
  2717. hint.value = noteValue (note);
  2718. return hint;
  2719. }
  2720. if (velocityArea().contains (p))
  2721. {
  2722. 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",
  2723. { laneBox.getText() });
  2724. if (h.note >= 0)
  2725. hint.value = noteValue (h.note);
  2726. return hint;
  2727. }
  2728. if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth)
  2729. {
  2730. 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");
  2731. return hint;
  2732. }
  2733. if (! gridArea().contains (p))
  2734. return hint;
  2735. if (h.stretch)
  2736. {
  2737. hint.text = tr ("Stretch handle: [LMB] drag stretches or squeezes the selected notes in time (from the selection's start) [Alt] no snap");
  2738. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  2739. return hint;
  2740. }
  2741. if (h.note < 0 && h.ghost >= 0)
  2742. {
  2743. const auto ghostChannel = notes[(std::size_t) h.ghost].channel;
  2744. const auto name = ghostChannel >= 0 && ghostChannel < (int) song.channels.size()
  2745. ? juce::String::fromUTF8 (song.channels[(std::size_t) ghostChannel].name.c_str())
  2746. : juce::String();
  2747. hint.text = editGhosts ? tr ("Ghost note of {0} (editable): [LMB] edit it (switches to {0}) [RMB] deletes it [Ctrl][Alt][V] read-only ghosts",
  2748. { name })
  2749. : tr ("Ghost note of {0}: double [RMB] edits that channel [Alt][V] hides ghost notes [Ctrl][Alt][V] makes them editable",
  2750. { name });
  2751. hint.value = keyName (notes[(std::size_t) h.ghost].key);
  2752. return hint;
  2753. }
  2754. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  2755. hint.text = actionHint (gesture::leftAction (tools.getTool(), targetAt (h), m, false), false);
  2756. hint.value = h.note >= 0 ? noteValue (h.note) : keyName (h.key);
  2757. return hint;
  2758. }
  2759. void PianoRollComponent::mouseDoubleClick (const juce::MouseEvent& e)
  2760. {
  2761. if (velocityArea().contains (e.getPosition()) && mpeDoubleClick (e))
  2762. return;
  2763. if (! gridArea().contains (e.getPosition()) || e.mods.isRightButtonDown() || flmods::ctrl (e.mods))
  2764. return;
  2765. // the first click of this double click created the note: that was drawing, not opening it
  2766. if (juce::Time::getMillisecondCounter() - createdAt < 800)
  2767. return;
  2768. bool edge = false;
  2769. const auto hit = noteAt (e.x, e.y, edge);
  2770. if (hit < 0)
  2771. return;
  2772. const auto indices = isSelected (hit) ? selection : std::vector<int> { hit };
  2773. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) hit];
  2774. const auto area = juce::Rectangle<int> ((int) tickToX ((double) n.start), keyToY (n.key), juce::jmax (8, (int) (n.length * pixelsPerTick)), rowHeight);
  2775. showNoteInspector (engine, indices, hit, localAreaToGlobal (area));
  2776. }
  2777. std::unique_ptr<juce::Component> PianoRollComponent::makeNoteInspectorForSnapshot (bool singleNote)
  2778. {
  2779. if (selection.empty())
  2780. selectAll();
  2781. if (selection.empty())
  2782. return nullptr;
  2783. return makeNoteInspector (engine, singleNote ? std::vector<int> { selection.front() } : selection, selection.front());
  2784. }
  2785. ui::Hint PianoRollComponent::hoverForSnapshot()
  2786. {
  2787. rowHeight = 18;
  2788. pixelsPerTick = 64.0 / ticksPerStep;
  2789. scrollToNotes (false);
  2790. const auto notes = channelNotes();
  2791. if (notes.empty())
  2792. return {};
  2793. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) notes.front()];
  2794. const auto at = juce::Point<int> ((int) tickToX ((double) (n.start + n.length)) - 2, keyToY (n.key) + rowHeight / 2);
  2795. updateHover (at, {});
  2796. return hintAt (at);
  2797. }
  2798. // --- tools ---------------------------------------------------------------------------
  2799. void PianoRollComponent::cutWithKnife (juce::Point<int> from, juce::Point<int> to, bool snapOn)
  2800. {
  2801. const auto& notes = currentPattern (engine.getSong()).notes;
  2802. std::vector<std::pair<int, std::int64_t>> cuts;
  2803. if (from.getDistanceFrom (to) < 3)
  2804. {
  2805. // a click: cuts the note under the cursor
  2806. bool edge = false;
  2807. if (const auto hit = noteAt (from.x, from.y, edge); hit >= 0)
  2808. cuts.push_back ({ hit, snap (xToTick (from.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn) });
  2809. }
  2810. else
  2811. {
  2812. // a line: every note row it crosses is cut where the line passes
  2813. const auto top = juce::jmin (from.y, to.y), bottom = juce::jmax (from.y, to.y);
  2814. for (int i = 0; i < (int) notes.size(); ++i)
  2815. {
  2816. const auto& n = notes[(std::size_t) i];
  2817. if (! edits (n))
  2818. continue;
  2819. const auto rowY = keyToY (n.key) + rowHeight / 2;
  2820. if (rowY < top - rowHeight / 2 || rowY > bottom + rowHeight / 2)
  2821. continue;
  2822. const auto y = juce::jlimit (top, bottom, rowY);
  2823. 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);
  2824. const auto tick = snap (xToTick ((int) std::round (x)) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn);
  2825. if (tick > n.start && tick < n.start + n.length)
  2826. cuts.push_back ({ i, tick });
  2827. }
  2828. }
  2829. if (cuts.empty())
  2830. return;
  2831. setSelection ({});
  2832. editNotes ([&cuts] (Pattern& p) {
  2833. for (auto [index, tick] : cuts)
  2834. noteedit::split (p, index, tick);
  2835. });
  2836. sortNotes();
  2837. }
  2838. void PianoRollComponent::zoomToTicks (double from, double to)
  2839. {
  2840. if (to - from < 1.0)
  2841. return;
  2842. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, gridArea().getWidth() / (to - from));
  2843. scrollTicks = juce::jmax (0.0, from);
  2844. updateScrollBars();
  2845. repaint();
  2846. }
  2847. void PianoRollComponent::zoomIn (int anchorX)
  2848. {
  2849. const auto anchor = xToTick (anchorX);
  2850. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * 2.0);
  2851. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  2852. updateScrollBars();
  2853. repaint();
  2854. }
  2855. void PianoRollComponent::zoomOut (int anchorX)
  2856. {
  2857. const auto anchor = xToTick (anchorX);
  2858. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick / 2.0);
  2859. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  2860. updateScrollBars();
  2861. repaint();
  2862. }
  2863. void PianoRollComponent::seekAt (int x, bool snapOn)
  2864. {
  2865. const auto& song = engine.getSong();
  2866. const auto tick = snapOn ? (double) snap (xToTick (x), true) : xToTick (x);
  2867. const auto target = transportedit::patternSeekTarget (song, song.currentPattern, tick, engine.getTransport().positionTicks.load());
  2868. if (target < 0.0)
  2869. {
  2870. // Song mode and no clip of this pattern: play the pattern on its own from there
  2871. engine.editSong ([] (Song& s) { s.mode = PlayMode::pattern; }, false);
  2872. engine.seek (juce::jmax (0.0, tick));
  2873. EditorGlobals::get().markSeek ((std::int64_t) juce::jmax (0.0, tick), false); // FL: Stop goes back here (issue #169)
  2874. return;
  2875. }
  2876. engine.seek (target);
  2877. EditorGlobals::get().markSeek ((std::int64_t) target, song.mode == PlayMode::song);
  2878. }
  2879. void PianoRollComponent::listenAt (int x)
  2880. {
  2881. // plays the channel's notes that sound at the tick under the mouse
  2882. const auto tick = (std::int64_t) xToTick (x);
  2883. const auto& notes = currentPattern (engine.getSong()).notes;
  2884. const auto channel = engine.getSelectedChannel();
  2885. std::vector<int> keys;
  2886. std::vector<float> velocities;
  2887. for (const auto& n : notes)
  2888. if (n.channel == channel && ! n.muted && n.start <= tick && n.start + n.length > tick
  2889. && std::find (keys.begin(), keys.end(), n.key) == keys.end())
  2890. {
  2891. keys.push_back (n.key);
  2892. velocities.push_back (n.velocity);
  2893. }
  2894. for (auto k : listenKeys)
  2895. if (std::find (keys.begin(), keys.end(), k) == keys.end())
  2896. listenNotes.release (listenChannel, k);
  2897. if (channel != listenChannel)
  2898. listenNotes.releaseAll();
  2899. for (std::size_t i = 0; i < keys.size(); ++i)
  2900. if (! listenNotes.isHeld (channel, keys[i]))
  2901. listenNotes.press (channel, keys[i], velocities[i]);
  2902. listenKeys = keys;
  2903. listenChannel = channel;
  2904. }
  2905. void PianoRollComponent::stopListening()
  2906. {
  2907. listenNotes.releaseAll();
  2908. listenKeys.clear();
  2909. }
  2910. void PianoRollComponent::refreshChannelBox()
  2911. {
  2912. const auto& song = engine.getSong();
  2913. std::vector<bool> hasNotes (song.channels.size(), false);
  2914. for (const auto& n : currentPattern (song).notes)
  2915. if (n.channel >= 0 && n.channel < (int) hasNotes.size())
  2916. hasNotes[(std::size_t) n.channel] = true;
  2917. juce::StringArray names;
  2918. names.add (tr ("All")); // (issue #12: every channel's notes; drawn bold)
  2919. for (std::size_t c = 0; c < song.channels.size(); ++c)
  2920. names.add ((hasNotes[c] ? juce::String::fromUTF8 ("\xe2\x97\x8f ") : juce::String (" ")) + juce::String::fromUTF8 (song.channels[c].name.c_str()));
  2921. // only rebuilds when something changed (rebuilding closes an open menu)
  2922. bool same = channelBox.getNumItems() == names.size();
  2923. for (int i = 0; same && i < names.size(); ++i)
  2924. same = channelBox.getItemText (i) == names[i];
  2925. if (! same)
  2926. {
  2927. // the bold "All" at the top, as a custom item (a ComboBox item has no font of its own)
  2928. struct BoldItem final : juce::PopupMenu::CustomComponent
  2929. {
  2930. explicit BoldItem (juce::String t) : text (std::move (t)) {}
  2931. void getIdealSize (int& w, int& h) override
  2932. {
  2933. w = 160;
  2934. h = 24;
  2935. }
  2936. void paint (juce::Graphics& g) override
  2937. {
  2938. if (isItemHighlighted())
  2939. {
  2940. g.setColour (theme::colour::accent.withAlpha (0.35f));
  2941. g.fillRect (getLocalBounds());
  2942. }
  2943. g.setColour (theme::colour::textPrimary);
  2944. g.setFont (theme::font (theme::type::body, true));
  2945. g.drawText (text, getLocalBounds().withTrimmedLeft (12), juce::Justification::centredLeft, true);
  2946. }
  2947. juce::String text;
  2948. };
  2949. channelBox.clear (juce::dontSendNotification);
  2950. juce::PopupMenu::Item all (names[0]);
  2951. all.itemID = allChannelsId;
  2952. all.customComponent = new BoldItem (names[0]);
  2953. channelBox.getRootMenu()->addItem (std::move (all));
  2954. channelBox.getRootMenu()->addSeparator();
  2955. for (int i = 1; i < names.size(); ++i)
  2956. channelBox.addItem (names[i], i);
  2957. }
  2958. channelBox.setSelectedId (allChannels ? allChannelsId : engine.getSelectedChannel() + 1, juce::dontSendNotification);
  2959. }
  2960. void PianoRollComponent::setAllChannels (bool on)
  2961. {
  2962. if (allChannels == on)
  2963. return;
  2964. allChannels = on;
  2965. selection.clear();
  2966. stopListening();
  2967. refreshChannelBox();
  2968. repaint();
  2969. }
  2970. void PianoRollComponent::stepChannel (int direction, bool withNotesOnly)
  2971. {
  2972. const auto& song = engine.getSong();
  2973. const auto count = (int) song.channels.size();
  2974. if (count == 0)
  2975. return;
  2976. std::vector<bool> hasNotes ((std::size_t) count, false);
  2977. for (const auto& n : currentPattern (song).notes)
  2978. if (n.channel >= 0 && n.channel < count)
  2979. hasNotes[(std::size_t) n.channel] = true;
  2980. auto channel = engine.getSelectedChannel();
  2981. for (int step = 0; step < count; ++step)
  2982. {
  2983. channel += direction;
  2984. if (channel < 0 || channel >= count)
  2985. return; // stops at the ends
  2986. if (! withNotesOnly || hasNotes[(std::size_t) channel])
  2987. {
  2988. engine.setSelectedChannel (channel);
  2989. return;
  2990. }
  2991. }
  2992. }
  2993. void PianoRollComponent::runOperation (const std::function<std::vector<int> (Pattern&, const std::vector<int>&)>& op)
  2994. {
  2995. const auto target = selectionOrAll();
  2996. if (target.empty())
  2997. return;
  2998. const auto hadSelection = ! selection.empty();
  2999. std::vector<int> result;
  3000. editNotes ([&] (Pattern& p) { result = op (p, target); });
  3001. setSelection (hadSelection ? result : std::vector<int> {});
  3002. sortNotes();
  3003. }
  3004. void PianoRollComponent::showMoreMenu()
  3005. {
  3006. moreMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&moreButton));
  3007. }
  3008. juce::PopupMenu PianoRollComponent::moreMenu()
  3009. {
  3010. const auto grid = gridTicks();
  3011. const auto bar = engine.getSong().barTicks();
  3012. juce::PopupMenu menu;
  3013. menu.addSubMenu (theme::mnemonic (tr ("File"), 'F'), fileMenu());
  3014. menu.addSubMenu (theme::mnemonic (tr ("Edit"), 'E'), editMenu());
  3015. menu.addSubMenu (theme::mnemonic (tr ("View"), 'V'), viewMenu());
  3016. menu.addSubMenu (tr ("Time markers"), markersMenu());
  3017. menu.addSeparator();
  3018. menu.addSectionHeader (tr ("Note operations (selection, or all notes)"));
  3019. 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); }); });
  3020. 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> {}; }); });
  3021. menu.addItem (tr ("Make legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  3022. 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; }); });
  3023. menu.addItem (tr ("Quantise starts") + keyText ("pianoRoll.quantizeStarts"), [this] { quantizeOperation (0); });
  3024. menu.addItem (tr ("Quantise starts 50% (halfway to the grid)") + keyText ("pianoRoll.quantizeHalf"), [this] { quantizeOperation (2); });
  3025. menu.addItem (tr ("Quantise starts and lengths") + keyText ("pianoRoll.quickQuantize"), [this] { quantizeOperation (1); });
  3026. 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; }); });
  3027. 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; }); });
  3028. menu.addSeparator();
  3029. menu.addSubMenu (theme::mnemonic (tr ("Tools"), 'T'), toolsMenu());
  3030. menu.addSubMenu (theme::mnemonic (tr ("Select"), 'S'), selectMenu());
  3031. {
  3032. juce::PopupMenu zoom;
  3033. zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("pianoRoll.zoomIn"); });
  3034. zoom.addItem (tr ("Zoom out") + "\tPageDown", [this] { runAction ("pianoRoll.zoomOut"); });
  3035. zoom.addItem (tr ("Zoom: one bar") + "\tShift+1", [this] { runAction ("pianoRoll.zoom1"); });
  3036. zoom.addItem (tr ("Zoom: four bars") + "\tShift+2", [this] { runAction ("pianoRoll.zoom2"); });
  3037. zoom.addItem (tr ("Zoom: sixteen bars") + "\tShift+3", [this] { runAction ("pianoRoll.zoom3"); });
  3038. zoom.addItem (tr ("Zoom to show everything") + "\tShift+4", [this] { runAction ("pianoRoll.zoomAll"); });
  3039. zoom.addItem (tr ("Zoom to the selection") + "\tShift+5", [this] { runAction ("pianoRoll.zoomSelection"); });
  3040. zoom.addItem (tr ("Centre the view on the playhead") + "\tShift+0", [this] { runAction ("pianoRoll.centrePlayhead"); });
  3041. zoom.addSeparator();
  3042. zoom.addItem (tr ("Taller keys") + "\tCtrl+Alt+Wheel", [this] { rowHeight = juce::jmin (gesture::maxKeyHeight, rowHeight + 2); updateScrollBars(); repaint(); });
  3043. zoom.addItem (tr ("Shorter keys"), [this] { rowHeight = juce::jmax (gesture::minKeyHeight, rowHeight - 2); updateScrollBars(); repaint(); });
  3044. menu.addSubMenu (tr ("Zoom"), zoom);
  3045. }
  3046. menu.addSeparator();
  3047. menu.addItem (tr ("Snap notes to the scale") + keyText ("pianoRoll.scaleSnap"), scaleIndex() > 0, scaleSnap, [this] { setScaleSnap (! scaleSnap); });
  3048. menu.addItem (tr ("Fold to the scale (hide the other keys and their notes)"), scaleIndex() > 0, foldToScale,
  3049. [this] { setFoldToScale (! foldToScale); });
  3050. menu.addItem (tr ("Chord stamp: the clicked key is the top note"), true, chordTopDown, [this] { chordTopDown = ! chordTopDown; });
  3051. // the chord stamp's list (round 190j, discussion #10): the toolbar's chord box is hidden in a narrow window, so
  3052. // the stamp is always in this menu too
  3053. menu.addSubMenu (tr ("Chord stamp"), stampMenu(), true, juce::Image(), chordBox.getSelectedId() > 1);
  3054. menu.addItem (tr ("Stamp: none (single notes)") + keyText ("pianoRoll.stampNone"), chordBox.getSelectedId() != 1, false,
  3055. [this] { runAction ("pianoRoll.stampNone"); });
  3056. menu.addItem (tr ("Move the notes onto the scale"), scaleIndex() > 0, false, [this] {
  3057. const auto root = scaleRoot(), scale = scaleIndex();
  3058. runOperation ([root, scale] (Pattern& p, const std::vector<int>& t) { notetools::snapNotesToScale (p, t, root, scale); return t; });
  3059. });
  3060. menu.addSeparator();
  3061. menu.addItem (tr ("Note names on every key"), true, notenames::everyKey.load(), [this] {
  3062. notenames::everyKey.store (! notenames::everyKey.load());
  3063. if (onNoteNamesChanged != nullptr)
  3064. onNoteNamesChanged(); // (saved with the settings)
  3065. repaint();
  3066. });
  3067. menu.addItem (tr ("Resize notes from the left edge too") + "\tCtrl+Alt+Home", true, resizeFromLeft, [this] { resizeFromLeft = ! resizeFromLeft; });
  3068. // issue #183: FL keeps placed and dragged notes silent while the song / pattern plays; this hears them anyway
  3069. menu.addItem (tr ("Preview notes while playing"), true, previewWhilePlaying, [] {
  3070. previewWhilePlaying = ! previewWhilePlaying;
  3071. if (EditorGlobals::get().onOptionsChanged)
  3072. EditorGlobals::get().onOptionsChanged(); // (saved with the UI settings)
  3073. });
  3074. menu.addItem (tr ("Show ghost notes") + "\tAlt+V", true, showGhosts,
  3075. [this] { ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync); });
  3076. menu.addItem (tr ("Ghost notes are editable") + "\tCtrl+Alt+V", true, editGhosts, [this] {
  3077. editGhosts = ! editGhosts;
  3078. if (editGhosts && ! showGhosts)
  3079. ghostButton.setToggleState (true, juce::sendNotificationSync);
  3080. repaint();
  3081. });
  3082. menu.addSubMenu (tr ("Ghost channels"), ghostChannelsMenu());
  3083. menu.addSeparator();
  3084. menu.addSubMenu ("MIDI", midiMenu());
  3085. return menu;
  3086. }
  3087. bool PianoRollComponent::ghostShown (int channel) const noexcept
  3088. {
  3089. const auto& channels = engine.getSong().channels;
  3090. return channel < 0 || channel >= (int) channels.size() || ! channels[(std::size_t) channel].ghostHidden;
  3091. }
  3092. void PianoRollComponent::setGhostChannels (const std::function<bool (int channel, bool shown)>& show)
  3093. {
  3094. engine.editSong ([&show] (Song& s) {
  3095. for (int c = 0; c < (int) s.channels.size(); ++c)
  3096. s.channels[(std::size_t) c].ghostHidden = ! show (c, ! s.channels[(std::size_t) c].ghostHidden);
  3097. }, false);
  3098. engine.markModified();
  3099. if (! showGhosts) // choosing what to ghost shows the ghosts
  3100. ghostButton.setToggleState (true, juce::sendNotificationSync);
  3101. repaint();
  3102. }
  3103. juce::PopupMenu PianoRollComponent::ghostChannelsMenu()
  3104. {
  3105. // FL 2026's ghost notes button menu (round 166d [SHOT], right-click on it): "Ghost channels", All, None, then every
  3106. // channel with a check mark (the edited one in bold); a click toggles that channel's ghost notes
  3107. struct ChannelItem final : juce::PopupMenu::CustomComponent
  3108. {
  3109. ChannelItem (juce::String t, bool tick, bool bold) : text (std::move (t)), ticked (tick), strong (bold) {}
  3110. void getIdealSize (int& w, int& h) override
  3111. {
  3112. w = juce::jlimit (140, 420, 40 + juce::GlyphArrangement::getStringWidthInt (theme::font (theme::type::body, true), text));
  3113. h = 22;
  3114. }
  3115. void paint (juce::Graphics& g) override
  3116. {
  3117. if (isItemHighlighted())
  3118. {
  3119. g.setColour (theme::colour::accent.withAlpha (0.35f));
  3120. g.fillRect (getLocalBounds());
  3121. }
  3122. auto area = getLocalBounds();
  3123. const auto tickArea = area.removeFromLeft (24).toFloat();
  3124. if (ticked)
  3125. icons::draw (g, Icon::check, tickArea.withSizeKeepingCentre (12.0f, 12.0f), theme::colour::textPrimary);
  3126. g.setColour (ticked ? theme::colour::textPrimary : theme::colour::textSecondary);
  3127. g.setFont (theme::font (theme::type::body, strong));
  3128. g.drawText (text, area.withTrimmedRight (8), juce::Justification::centredLeft, true);
  3129. }
  3130. juce::String text;
  3131. bool ticked, strong;
  3132. };
  3133. juce::PopupMenu menu;
  3134. menu.addSectionHeader (tr ("Ghost channels"));
  3135. menu.addItem (tr ("All"), [this] { setGhostChannels ([] (int, bool) { return true; }); });
  3136. menu.addItem (tr ("None"), [this] { setGhostChannels ([] (int, bool) { return false; }); });
  3137. menu.addSeparator();
  3138. const auto& song = engine.getSong();
  3139. const auto current = engine.getSelectedChannel();
  3140. for (int c = 0; c < (int) song.channels.size(); ++c)
  3141. {
  3142. const auto name = juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str());
  3143. juce::PopupMenu::Item item (name);
  3144. item.customComponent = new ChannelItem (name, ghostShown (c), c == current);
  3145. item.action = [this, c] { setGhostChannels ([c] (int k, bool shown) { return k == c ? ! shown : shown; }); };
  3146. menu.addItem (std::move (item));
  3147. }
  3148. return menu;
  3149. }
  3150. void PianoRollComponent::openMidiTools()
  3151. {
  3152. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  3153. auto panel = std::make_unique<MidiToolsPanel> (
  3154. engine,
  3155. [safe] {
  3156. MidiToolsPanel::Target t;
  3157. if (safe != nullptr)
  3158. {
  3159. t.pattern = safe->engine.getSong().currentPattern;
  3160. t.indices = safe->midiToolNotes (t.selected);
  3161. t.grid = safe->midiToolGrid();
  3162. t.from = safe->timeSelectionFrom(); // round 190fm: Generate writes into the time selection
  3163. t.to = safe->timeSelectionTo();
  3164. t.channel = safe->engine.getSelectedChannel();
  3165. }
  3166. return t;
  3167. },
  3168. [safe] (const std::vector<int>& indices) {
  3169. if (safe != nullptr)
  3170. safe->selectMidiToolResult (indices);
  3171. });
  3172. struct Padded final : juce::Component // (the panel with a margin, on the window's background)
  3173. {
  3174. explicit Padded (std::unique_ptr<MidiToolsPanel> p) : panel (std::move (p))
  3175. {
  3176. addAndMakeVisible (*panel);
  3177. setSize (MidiToolsPanel::panelWidth + 16, MidiToolsPanel::panelHeight + 12);
  3178. }
  3179. void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
  3180. void resized() override { panel->setBounds (getLocalBounds().reduced (8, 6)); }
  3181. std::unique_ptr<MidiToolsPanel> panel;
  3182. };
  3183. openToolWindow (std::make_unique<Padded> (std::move (panel)), tr ("MIDI Tools"), "midiTools");
  3184. }
  3185. juce::PopupMenu PianoRollComponent::toolsMenu()
  3186. {
  3187. // FL's piano roll Tools menu (REA round 143, EXEC capture): its groups and keys, in its order
  3188. juce::PopupMenu menu;
  3189. const auto grid = gridTicks();
  3190. auto tool = [this, &menu] (NoteTool t, const char* key) {
  3191. menu.addItem (tr (noteToolTitle (t)) + "..." + (key != nullptr ? juce::String ("\t") + key : juce::String()), [this, t] { openNoteTool (t); });
  3192. };
  3193. menu.addSectionHeader (tr ("Built-in"));
  3194. tool (NoteTool::riffMachine, "Alt+E");
  3195. menu.addItem (tr ("Generate chord progression...") + "\tAlt+P", [this] { openNoteTool (NoteTool::chordProgression); });
  3196. menu.addSeparator();
  3197. menu.addItem (tr ("Quick legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  3198. tool (NoteTool::articulate, "Alt+L");
  3199. menu.addSeparator();
  3200. menu.addItem (tr ("Quick quantize") + keyText ("pianoRoll.quickQuantize"), [this] { quantizeOperation (1); });
  3201. menu.addItem (tr ("Quick quantize start times") + keyText ("pianoRoll.quantizeStarts"), [this] { quantizeOperation (0); });
  3202. menu.addItem (tr ("Quick quantize 50% (halfway to the grid)") + keyText ("pianoRoll.quantizeHalf"), [this] { quantizeOperation (2); });
  3203. tool (NoteTool::quantize, "Alt+Q");
  3204. menu.addSeparator();
  3205. menu.addItem (tr ("Quick chop") + "\tCtrl+U", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); }); });
  3206. tool (NoteTool::chop, "Alt+U");
  3207. menu.addSeparator();
  3208. menu.addItem (tr ("Glue notes") + "\tCtrl+G", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; }); });
  3209. menu.addSeparator();
  3210. tool (NoteTool::arpeggiate, "Alt+A");
  3211. tool (NoteTool::strum, "Alt+S");
  3212. tool (NoteTool::flam, "Alt+F");
  3213. tool (NoteTool::claw, "Alt+W");
  3214. tool (NoteTool::limit, "Alt+K");
  3215. tool (NoteTool::flip, "Alt+Y");
  3216. tool (NoteTool::randomise, "Alt+R");
  3217. menu.addSeparator();
  3218. tool (NoteTool::scaleLevels, "Alt+X");
  3219. tool (NoteTool::lfo, "Alt+O");
  3220. // FL's second column ("Scripts": Python tools shipped with FL); LYNX has its own built-in versions
  3221. menu.addSectionHeader (tr ("More tools"));
  3222. tool (NoteTool::euclidean, nullptr);
  3223. tool (NoteTool::humanize, nullptr);
  3224. tool (NoteTool::noteRepeat, nullptr);
  3225. // Live 12's MIDI Transformations as a docked-style panel (round 190s; LYNX addition beside FL's tools above)
  3226. menu.addItem (tr ("MIDI Tools") + "...", [this] { openMidiTools(); });
  3227. {
  3228. juce::PopupMenu velocity;
  3229. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  3230. const auto& song = engine.getSong();
  3231. setSelection (pick (song.activePattern(), channelNotes()));
  3232. };
  3233. velocity.addItem (tr ("Loudest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, true); }); });
  3234. velocity.addItem (tr ("Quietest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, false); }); });
  3235. velocity.addSeparator();
  3236. 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 } })
  3237. velocity.addItem (tr ("Velocity {0}", { juce::String (label) }), [choose, lo = lo, hi = hi] {
  3238. choose ([lo, hi] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, lo, hi); });
  3239. });
  3240. if (! selection.empty())
  3241. {
  3242. const auto& notes = engine.getSong().activePattern().notes;
  3243. const auto v = selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].velocity : 0.0f;
  3244. velocity.addSeparator();
  3245. velocity.addItem (tr ("Same velocity as the selected note ({0}%)", { juce::String (juce::roundToInt (v * 100.0f)) }), [choose, v] {
  3246. choose ([v] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, v - 0.005f, v + 0.005f); });
  3247. });
  3248. }
  3249. menu.addSubMenu (tr ("Select by velocity"), velocity);
  3250. }
  3251. {
  3252. // Live 12's note Chance (round 187c, LYNX additions): probability groups, a reset and a new draw for the project
  3253. juce::PopupMenu chance;
  3254. const auto several = selection.size() > 1;
  3255. chance.addItem (tr ("Group the selected notes: play all"), several, false, [this] {
  3256. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::groupChance (p, t, false); return t; });
  3257. });
  3258. chance.addItem (tr ("Group the selected notes: play one"), several, false, [this] {
  3259. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::groupChance (p, t, true); return t; });
  3260. });
  3261. chance.addItem (tr ("Ungroup the chance of the selected notes"), [this] {
  3262. runOperation ([] (Pattern& p, const std::vector<int>& t) { notetools::ungroupChance (p, t); return t; });
  3263. });
  3264. chance.addSeparator();
  3265. chance.addItem (tr ("Reset chance and velocity range"), [this] {
  3266. runOperation ([] (Pattern& p, const std::vector<int>& t) {
  3267. notetools::ungroupChance (p, t);
  3268. for (auto i : t)
  3269. if (i >= 0 && i < (int) p.notes.size())
  3270. p.notes[(std::size_t) i].chance = 1.0f, p.notes[(std::size_t) i].velocityRange = 0.0f;
  3271. return t;
  3272. });
  3273. });
  3274. chance.addItem (tr ("New chance seed (draws again for the whole project)"), [this] {
  3275. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt64();
  3276. engine.editSong ([seed] (Song& s) { s.chanceSeed = seed == 0 ? 1u : seed; });
  3277. repaint();
  3278. });
  3279. chance.addSeparator();
  3280. chance.addItem (tr ("Show the chance lane"), true, laneIsChance(), [this] {
  3281. laneBox.setSelectedId (laneChance);
  3282. });
  3283. menu.addSubMenu (tr ("Chance (LYNX)"), chance);
  3284. }
  3285. menu.addSeparator();
  3286. menu.addItem (tr ("Edit events..."), [this] {
  3287. openEventEditor (engine, { AutomationTargetKind::channelVolume, engine.getSelectedChannel() });
  3288. });
  3289. // FL's second column: "Scripts", the Piano roll's Python scripts (round 190as)
  3290. menu.addColumnBreak();
  3291. menu.addSectionHeader (tr ("Scripts"));
  3292. addScriptItems (menu);
  3293. return menu;
  3294. }
  3295. void PianoRollComponent::openNoteTool (NoteTool tool)
  3296. {
  3297. const auto target = selectionOrAll();
  3298. if (target.empty() && ! noteToolGenerates (tool))
  3299. return;
  3300. showNoteTool (engine, tool, target, gridTicks(), [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  3301. if (safe != nullptr)
  3302. safe->setSelection ({});
  3303. });
  3304. }
  3305. void PianoRollComponent::zoomAroundCentre (double factor)
  3306. {
  3307. const auto grid = gridArea();
  3308. const auto centre = xToTick (grid.getCentreX());
  3309. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * factor);
  3310. scrollTicks = juce::jmax (0.0, centre - (grid.getCentreX() - keyboardWidth) / pixelsPerTick);
  3311. updateScrollBars();
  3312. repaint();
  3313. }
  3314. void PianoRollComponent::zoomToBars (int bars)
  3315. {
  3316. const auto bar = (double) engine.getSong().barTicks();
  3317. const auto from = std::floor (scrollTicks / bar) * bar;
  3318. zoomToTicks (from, from + bars * bar);
  3319. }
  3320. void PianoRollComponent::zoomAll()
  3321. {
  3322. const auto& song = engine.getSong();
  3323. zoomToTicks (0.0, (double) currentPattern (song).effectiveLength (song.meter()));
  3324. }
  3325. void PianoRollComponent::zoomToSelection()
  3326. {
  3327. const auto target = selectionOrAll();
  3328. if (target.empty())
  3329. return zoomAll();
  3330. const auto& notes = currentPattern (engine.getSong()).notes;
  3331. std::int64_t from = INT64_MAX, to = 0;
  3332. int low = 127, high = 0;
  3333. for (auto i : target)
  3334. {
  3335. const auto& n = notes[(std::size_t) i];
  3336. from = juce::jmin (from, n.start);
  3337. to = juce::jmax (to, n.start + n.length);
  3338. low = juce::jmin (low, n.key);
  3339. high = juce::jmax (high, n.key);
  3340. }
  3341. const auto margin = (double) ticksPerStep;
  3342. zoomToTicks (juce::jmax (0.0, (double) from - margin), (double) to + margin);
  3343. scrollY = juce::jmax (0, rowFor ((low + high) / 2) * rowHeight - gridArea().getHeight() / 2);
  3344. updateScrollBars();
  3345. repaint();
  3346. }
  3347. void PianoRollComponent::centreOnPlayhead()
  3348. {
  3349. const auto& song = engine.getSong();
  3350. const auto length = (double) juce::jmax<std::int64_t> (1, currentPattern (song).effectiveLength (song.meter()));
  3351. auto tick = transportedit::patternPlayhead (song, song.currentPattern, engine.getTransport().positionTicks.load());
  3352. if (tick < 0.0)
  3353. tick = std::fmod (engine.getTransport().positionTicks.load(), length);
  3354. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick / 2.0);
  3355. updateScrollBars();
  3356. repaint();
  3357. }
  3358. void PianoRollComponent::ColourSwatch::paintButton (juce::Graphics& g, bool over, bool down)
  3359. {
  3360. auto r = getLocalBounds().toFloat().reduced (3.0f);
  3361. g.setColour (theme::noteGroupColour (colourIndex, 0.85f));
  3362. g.fillRoundedRectangle (r, 3.0f);
  3363. g.setColour (over || down ? theme::colour::textPrimary : theme::colour::bg0.withAlpha (0.7f));
  3364. g.drawRoundedRectangle (r, 3.0f, 1.0f);
  3365. g.setColour (theme::colour::bg0.withAlpha (0.85f));
  3366. g.setFont (theme::font (theme::type::caption, true));
  3367. g.drawText (juce::String (colourIndex + 1), r, juce::Justification::centred, false);
  3368. }
  3369. void PianoRollComponent::colourSelection (int colour)
  3370. {
  3371. const auto target = selection;
  3372. if (target.empty())
  3373. return;
  3374. editNotes ([&] (Pattern& p) { notetools::setColour (p, target, colour); });
  3375. repaint();
  3376. }
  3377. void PianoRollComponent::selectByColour (int colour)
  3378. {
  3379. setSelection (notetools::selectByColour (currentPattern (engine.getSong()), channelNotes(), colour));
  3380. }
  3381. void PianoRollComponent::showColourMenu()
  3382. {
  3383. juce::PopupMenu menu;
  3384. menu.addSectionHeader (tr ("Colour for new notes"));
  3385. for (int c = 0; c < noteColourCount; ++c)
  3386. menu.addColouredItem (c + 1, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, c == noteColour);
  3387. menu.addSeparator();
  3388. menu.addItem (1000, tr ("Colour the selected notes with it") + "\tAlt+C", ! selection.empty());
  3389. {
  3390. juce::PopupMenu colourAs;
  3391. for (int c = 0; c < noteColourCount; ++c)
  3392. colourAs.addColouredItem (2001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, false);
  3393. menu.addSubMenu (tr ("Colour the selected notes"), colourAs, ! selection.empty());
  3394. }
  3395. {
  3396. juce::PopupMenu select;
  3397. const auto& pattern = currentPattern (engine.getSong());
  3398. for (int c = 0; c < noteColourCount; ++c)
  3399. select.addColouredItem (3001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f),
  3400. ! notetools::selectByColour (pattern, channelNotes(), c).empty(), false);
  3401. menu.addSubMenu (tr ("Select by colour") + "\tShift+C", select);
  3402. }
  3403. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&colourButton), [safe = juce::Component::SafePointer (this)] (int id) {
  3404. if (safe == nullptr || id <= 0)
  3405. return;
  3406. if (id <= noteColourCount)
  3407. {
  3408. safe->noteColour = id - 1;
  3409. safe->colourButton.colourIndex = id - 1;
  3410. safe->colourButton.repaint();
  3411. }
  3412. else if (id == 1000)
  3413. safe->colourSelection (safe->noteColour);
  3414. else if (id > 2000 && id <= 2000 + noteColourCount)
  3415. safe->colourSelection (id - 2001);
  3416. else if (id > 3000 && id <= 3000 + noteColourCount)
  3417. safe->selectByColour (id - 3001);
  3418. });
  3419. }
  3420. juce::PopupMenu PianoRollComponent::selectMenu()
  3421. {
  3422. // FL's piano roll Select submenu (its manual): all, invert, odd, random, muted, overlapping, stacked, by colour
  3423. juce::PopupMenu menu;
  3424. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  3425. setSelection (pick (currentPattern (engine.getSong()), channelNotes()));
  3426. };
  3427. menu.addItem (theme::mnemonic (tr ("All"), 'a') + "\tCtrl+A", [this] { selectAll(); });
  3428. menu.addItem (theme::mnemonic (tr ("Invert selection"), 'I') + "\tShift+I", [this] { runAction ("pianoRoll.invertSelection"); });
  3429. menu.addItem (theme::mnemonic (tr ("Deselect"), 'D') + "\tEsc", ! selection.empty(), false, [this] { setSelection ({}); });
  3430. menu.addSeparator();
  3431. // FL's Select items with their keys (round 168g): they add to the selection
  3432. menu.addItem (theme::mnemonic (tr ("Select one at random"), 'r') + keyText ("pianoRoll.selectRandomOne"), [this] { runAction ("pianoRoll.selectRandomOne"); });
  3433. menu.addItem (theme::mnemonic (tr ("Select more at random"), 'r') + keyText ("pianoRoll.selectRandomMore"), [this] { runAction ("pianoRoll.selectRandomMore"); });
  3434. menu.addItem (theme::mnemonic (tr ("Select odd (swung) notes"), 'o') + keyText ("pianoRoll.selectOddSteps"), [this] { runAction ("pianoRoll.selectOddSteps"); });
  3435. menu.addSeparator();
  3436. menu.addItem (tr ("Odd notes (every other one)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOdd (p, t); }); });
  3437. menu.addItem (tr ("Even notes"), [choose] {
  3438. choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::invertSelection (t, notetools::selectOdd (p, t)); });
  3439. });
  3440. menu.addItem (tr ("Random (half of the notes)"), [choose] {
  3441. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
  3442. choose ([seed] (const Pattern& p, const std::vector<int>& t) { return notetools::selectRandom (p, t, 0.5f, seed); });
  3443. });
  3444. menu.addItem (theme::mnemonic (tr ("Muted notes"), 'm'), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectMuted (p, t); }); });
  3445. menu.addItem (tr ("Overlapping notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOverlapping (p, t); }); });
  3446. menu.addItem (tr ("Stacked notes (hidden duplicates)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectStacked (p, t); }); });
  3447. menu.addItem (theme::mnemonic (tr ("Same colour as the selection"), 'c') + "\tShift+C", [this] { runAction ("pianoRoll.selectByColour"); });
  3448. menu.addSeparator();
  3449. menu.addItem (tr ("Group the selected notes") + "\tShift+G", selection.size() > 1, false, [this] { runAction ("pianoRoll.groupNotes"); });
  3450. menu.addItem (tr ("Ungroup the selected notes") + "\tAlt+G", ! selection.empty(), false, [this] { runAction ("pianoRoll.ungroupNotes"); });
  3451. return menu;
  3452. }
  3453. void PianoRollComponent::showKeyMenu (int key)
  3454. {
  3455. const auto channel = engine.getSelectedChannel();
  3456. if (channel < 0 || channel >= (int) engine.getSong().channels.size() || key < 0 || key > 127)
  3457. return;
  3458. const auto& labels = engine.getSong().channels[(std::size_t) channel].keyLabels;
  3459. const auto current = labels.find (key);
  3460. auto setLabels = [this, channel] (std::function<void (std::map<int, std::string>&)> edit) {
  3461. engine.editSong ([channel, edit] (Song& s) {
  3462. if (channel < (int) s.channels.size())
  3463. edit (s.channels[(std::size_t) channel].keyLabels);
  3464. });
  3465. repaint();
  3466. };
  3467. juce::PopupMenu menu;
  3468. menu.addSectionHeader (keyName (key));
  3469. menu.addItem (tr ("Rename this key..."), [key, setLabels, text = current != labels.end() ? current->second : std::string()] {
  3470. auto* window = new juce::AlertWindow (tr ("Key label"), tr ("The name shown on {0} for this channel", { keyName (key) }), juce::MessageBoxIconType::NoIcon);
  3471. window->addTextEditor ("label", juce::String::fromUTF8 (text.c_str()));
  3472. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3473. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3474. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, key, setLabels] (int result) {
  3475. if (result != 1)
  3476. return;
  3477. const auto label = window->getTextEditorContents ("label").trim().toStdString();
  3478. setLabels ([key, label] (std::map<int, std::string>& l) {
  3479. if (label.empty())
  3480. l.erase (key);
  3481. else
  3482. l[key] = label;
  3483. });
  3484. }),
  3485. true);
  3486. });
  3487. menu.addItem (tr ("Remove this key's label"), current != labels.end(), false,
  3488. [setLabels, key] { setLabels ([key] (std::map<int, std::string>& l) { l.erase (key); }); });
  3489. menu.addSeparator();
  3490. menu.addItem (tr ("Label the keys with the General MIDI drum map"), [setLabels] {
  3491. setLabels ([] (std::map<int, std::string>& l) {
  3492. for (int k = 35; k <= 81; ++k)
  3493. if (const auto* name = notetools::generalMidiDrumName (k))
  3494. l[k] = name;
  3495. });
  3496. });
  3497. menu.addItem (tr ("Remove all key labels of this channel"), ! labels.empty(), false,
  3498. [setLabels] { setLabels ([] (std::map<int, std::string>& l) { l.clear(); }); });
  3499. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  3500. }
  3501. void PianoRollComponent::updateChordReadout()
  3502. {
  3503. auto keys = engine.heldInputKeys();
  3504. if (keys.size() < 2)
  3505. {
  3506. keys.clear();
  3507. const auto& notes = currentPattern (engine.getSong()).notes;
  3508. for (auto i : selection)
  3509. if (i >= 0 && i < (int) notes.size())
  3510. keys.push_back (notes[(std::size_t) i].key);
  3511. }
  3512. const auto text = chordName (keys);
  3513. if (chordLabel.getText() != text)
  3514. chordLabel.setText (text, juce::dontSendNotification);
  3515. updateChordBubble();
  3516. }
  3517. void PianoRollComponent::updateChordBubble()
  3518. {
  3519. const auto now = juce::Time::getMillisecondCounter();
  3520. if (selection != chordPanelSelection)
  3521. {
  3522. // the toolbar's chord panel follows the selection whether this bubble is on or not (FL: FUN_00d32da0)
  3523. chordPanelSelection = selection;
  3524. if (onSelectedKeys)
  3525. {
  3526. const auto& notes = currentPattern (engine.getSong()).notes;
  3527. std::vector<int> keys;
  3528. for (auto i : selection)
  3529. if (i >= 0 && i < (int) notes.size() && ! notes[(std::size_t) i].muted)
  3530. keys.push_back (notes[(std::size_t) i].key);
  3531. onSelectedKeys (keys);
  3532. }
  3533. }
  3534. if (! showChordName)
  3535. {
  3536. chordBubble.setVisible (false);
  3537. chordBubbleSelection = selection;
  3538. return;
  3539. }
  3540. if (selection != chordBubbleSelection)
  3541. {
  3542. // FL (FUN_00e5a850 → FUN_00d32da0, on every selection change): the different keys of the selected notes, muted
  3543. // ones left out; 2 to 10 of them name a chord
  3544. chordBubbleSelection = selection;
  3545. const auto& notes = currentPattern (engine.getSong()).notes;
  3546. std::vector<int> keys;
  3547. for (auto i : selection)
  3548. if (i >= 0 && i < (int) notes.size() && ! notes[(std::size_t) i].muted)
  3549. keys.push_back (notes[(std::size_t) i].key);
  3550. std::sort (keys.begin(), keys.end());
  3551. keys.erase (std::unique (keys.begin(), keys.end()), keys.end());
  3552. const auto text = keys.size() >= 2 && keys.size() <= 10 ? chordName (keys) : juce::String();
  3553. if (text.isNotEmpty())
  3554. {
  3555. chordBubble.setText (text, juce::dontSendNotification);
  3556. const auto font = chordBubble.getFont();
  3557. const auto width = juce::roundToInt (juce::GlyphArrangement::getStringWidth (font, text)) + 20;
  3558. const auto grid = gridArea();
  3559. chordBubble.setBounds (grid.getX() + 16, grid.getY() + 16, width, juce::roundToInt (font.getHeight()) + 10);
  3560. chordBubble.setVisible (true);
  3561. chordBubble.toFront (false);
  3562. chordBubbleUntil = now + 2000; // (FL keeps its chord readout at least 2 s: FUN_00d32da0 +0xac)
  3563. }
  3564. else
  3565. chordBubble.setVisible (false);
  3566. }
  3567. else if (chordBubble.isVisible() && now > chordBubbleUntil)
  3568. chordBubble.setVisible (false);
  3569. }
  3570. // Round 190hr: the reference's grid menu [STR AGridContextMenu: Widest … Narrowest (adaptive), Fixed with its values,
  3571. // Triplet; DOC: Snap to Grid Ctrl+4, Fixed / Adaptive Ctrl+5]. Each pick changes this editor's grid at once.
  3572. juce::PopupMenu PianoRollComponent::liveGridMenu()
  3573. {
  3574. const juce::Component::SafePointer<PianoRollComponent> safe (this);
  3575. const auto change = [safe] (std::function<void (livegrid::Grid&)> fn) {
  3576. return [safe, fn] {
  3577. if (safe == nullptr)
  3578. return;
  3579. fn (safe->liveGrid);
  3580. safe->resized();
  3581. safe->repaint();
  3582. };
  3583. };
  3584. juce::PopupMenu menu;
  3585. menu.addSectionHeader (tr ("Adaptive Grid"));
  3586. for (int d = 0; d < livegrid::densityCount; ++d)
  3587. menu.addItem (tr (livegrid::densityName (d)), true, ! liveGrid.fixed && liveGrid.density == d, change ([d] (livegrid::Grid& g) {
  3588. g.fixed = false;
  3589. g.density = d;
  3590. g.snap = true;
  3591. }));
  3592. menu.addSectionHeader (tr ("Fixed Grid"));
  3593. for (int i = 0; i < livegrid::fixedCount; ++i)
  3594. {
  3595. const auto f = livegrid::fixedValues[i];
  3596. 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);
  3597. menu.addItem (text, true, liveGrid.fixed && liveGrid.fixedIndex == i, change ([i] (livegrid::Grid& g) {
  3598. g.fixed = true;
  3599. g.fixedIndex = i;
  3600. g.snap = true;
  3601. }));
  3602. }
  3603. menu.addSeparator();
  3604. menu.addItem (tr ("Triplet Grid") + "\tCtrl+3", true, liveGrid.triplet, change ([] (livegrid::Grid& g) { g.triplet = ! g.triplet; }));
  3605. menu.addItem (tr ("Snap to Grid") + "\tCtrl+4", true, liveGrid.snap, change ([] (livegrid::Grid& g) { g.snap = ! g.snap; }));
  3606. menu.addSeparator();
  3607. menu.addItem (tr ("Narrow Grid") + "\tCtrl+1", true, false, change ([] (livegrid::Grid& g) { livegrid::narrower (g); }));
  3608. menu.addItem (tr ("Widen Grid") + "\tCtrl+2", true, false, change ([] (livegrid::Grid& g) { livegrid::wider (g); }));
  3609. menu.addSeparator();
  3610. menu.addItem (tr ("Quantize") + "\tCtrl+U", onLiveQuantize != nullptr, false, [safe] { if (safe != nullptr && safe->onLiveQuantize != nullptr) safe->onLiveQuantize(); });
  3611. menu.addItem (tr ("Quantize Settings...") + "\tCtrl+Shift+U", onLiveQuantizeSettings != nullptr, false, [safe] {
  3612. if (safe != nullptr && safe->onLiveQuantizeSettings != nullptr)
  3613. safe->onLiveQuantizeSettings();
  3614. });
  3615. return menu;
  3616. }
  3617. bool PianoRollComponent::runAction (const std::string& id)
  3618. {
  3619. auto is = [&id] (const char* name) { return id == name; };
  3620. // round 190hr: the reference's grid and quantize keys, only while docked in the Clip-launch detail view
  3621. if (id.rfind ("pianoRoll.live", 0) == 0)
  3622. {
  3623. if (! liveGridOn())
  3624. return false;
  3625. if (is ("pianoRoll.liveGridNarrower")) livegrid::narrower (liveGrid);
  3626. else if (is ("pianoRoll.liveGridWider")) livegrid::wider (liveGrid);
  3627. else if (is ("pianoRoll.liveGridTriplet")) liveGrid.triplet = ! liveGrid.triplet;
  3628. else if (is ("pianoRoll.liveGridSnap")) liveGrid.snap = ! liveGrid.snap;
  3629. else if (is ("pianoRoll.liveGridFixed")) liveGrid.fixed = ! liveGrid.fixed;
  3630. else if (is ("pianoRoll.liveQuantize") && onLiveQuantize != nullptr) onLiveQuantize();
  3631. else if (is ("pianoRoll.liveQuantizeSettings") && onLiveQuantizeSettings != nullptr) onLiveQuantizeSettings();
  3632. else
  3633. return false;
  3634. resized();
  3635. repaint();
  3636. return true;
  3637. }
  3638. if (is ("pianoRoll.arpeggiate")) openNoteTool (NoteTool::arpeggiate);
  3639. else if (is ("pianoRoll.strum")) openNoteTool (NoteTool::strum);
  3640. else if (is ("pianoRoll.flip")) openNoteTool (NoteTool::flip);
  3641. else if (is ("pianoRoll.randomise")) openNoteTool (NoteTool::randomise);
  3642. else if (is ("pianoRoll.scaleLevels")) openNoteTool (NoteTool::scaleLevels);
  3643. else if (is ("pianoRoll.limit")) openNoteTool (NoteTool::limit);
  3644. else if (is ("pianoRoll.quantize")) openNoteTool (NoteTool::quantize);
  3645. else if (is ("pianoRoll.chop")) openNoteTool (NoteTool::chop);
  3646. else if (is ("pianoRoll.flam")) openNoteTool (NoteTool::flam);
  3647. else if (is ("pianoRoll.claw")) openNoteTool (NoteTool::claw);
  3648. else if (is ("pianoRoll.lfo")) openNoteTool (NoteTool::lfo);
  3649. else if (is ("pianoRoll.articulate")) openNoteTool (NoteTool::articulate);
  3650. else if (is ("pianoRoll.riffMachine")) openNoteTool (NoteTool::riffMachine);
  3651. else if (is ("pianoRoll.chordProgression")) openNoteTool (NoteTool::chordProgression);
  3652. else if (is ("pianoRoll.runLastScript")) runLastScript();
  3653. else if (is ("pianoRoll.zoomIn")) zoomAroundCentre (1.25);
  3654. else if (is ("pianoRoll.zoomOut")) zoomAroundCentre (1.0 / 1.25);
  3655. else if (is ("pianoRoll.zoom1")) zoomToBars (1);
  3656. else if (is ("pianoRoll.zoom2")) zoomToBars (4);
  3657. else if (is ("pianoRoll.zoom3")) zoomToBars (16);
  3658. else if (is ("pianoRoll.zoomAll")) zoomAll();
  3659. else if (is ("pianoRoll.zoomSelection")) zoomToSelection();
  3660. else if (is ("pianoRoll.centrePlayhead")) centreOnPlayhead();
  3661. else if (is ("pianoRoll.follow")) EditorGlobals::get().setFollowing (true, ! EditorGlobals::get().isFollowing (true));
  3662. else if (is ("pianoRoll.eventPaneAlternate")) toggleEventPaneAlternate(); // FL's Shift+Enter (round 190fz)
  3663. else if (is ("pianoRoll.quantizeStarts")) quantizeOperation (0);
  3664. else if (is ("pianoRoll.quickQuantize")) quantizeOperation (1);
  3665. else if (is ("pianoRoll.quantizeHalf")) quantizeOperation (2);
  3666. else if (is ("pianoRoll.colourSelected")) colourSelection (noteColour);
  3667. else if (is ("pianoRoll.selectByColour"))
  3668. {
  3669. // the colour of the selected note (FL: the selection's colour), else the current note colour
  3670. const auto& notes = currentPattern (engine.getSong()).notes;
  3671. selectByColour (! selection.empty() && selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].colour : noteColour);
  3672. }
  3673. else if (is ("pianoRoll.invertSelection")) setSelection (notetools::invertSelection (channelNotes(), selection));
  3674. // round 168g: FL's View / Select / Stamp / Edit / File items
  3675. else if (is ("pianoRoll.gridHighlights"))
  3676. {
  3677. gridHighlights = ! gridHighlights;
  3678. if (EditorGlobals::get().onOptionsChanged)
  3679. EditorGlobals::get().onOptionsChanged();
  3680. repaint();
  3681. }
  3682. else if (is ("pianoRoll.backgroundWave")) setBackgroundWaveShown (! isBackgroundWaveShown());
  3683. else if (is ("pianoRoll.songBarsRuler"))
  3684. {
  3685. songBarsRuler = ! songBarsRuler;
  3686. if (EditorGlobals::get().onOptionsChanged)
  3687. EditorGlobals::get().onOptionsChanged();
  3688. repaint();
  3689. }
  3690. else if (is ("pianoRoll.showChordName"))
  3691. {
  3692. showChordName = ! showChordName;
  3693. chordBubbleSelection.clear(); // shows the current selection's chord at once
  3694. if (EditorGlobals::get().onOptionsChanged)
  3695. EditorGlobals::get().onOptionsChanged();
  3696. updateChordBubble();
  3697. }
  3698. else if (is ("pianoRoll.selectRandomOne") || is ("pianoRoll.selectRandomMore"))
  3699. setSelection (noteedit::selectRandomMore (currentPattern (engine.getSong()), channelNotes(), selection, is ("pianoRoll.selectRandomMore"),
  3700. (std::uint32_t) juce::Random::getSystemRandom().nextInt()));
  3701. else if (is ("pianoRoll.selectOddSteps"))
  3702. setSelection (noteedit::selectOddSteps (currentPattern (engine.getSong()), channelNotes(), selection, ticksPerStep));
  3703. else if (is ("pianoRoll.stampNone")) chordBox.setSelectedId (1, juce::sendNotificationSync);
  3704. else if (is ("pianoRoll.scaleSnap"))
  3705. {
  3706. if (scaleIndex() > 0) // (like its menu item and button: only with a scale chosen)
  3707. setScaleSnap (! scaleSnap);
  3708. }
  3709. else if (is ("pianoRoll.insertSpace")) spaceOperation (0);
  3710. else if (is ("pianoRoll.sliceInsertSpace")) spaceOperation (1);
  3711. else if (is ("pianoRoll.deleteSpace")) spaceOperation (2);
  3712. else if (is ("pianoRoll.trimSpace")) spaceOperation (3);
  3713. else if (is ("pianoRoll.deleteAll")) deleteAllNotes();
  3714. else if (is ("pianoRoll.insertControllerValue")) insertControllerValue();
  3715. else if (is ("pianoRoll.importMidi") || is ("pianoRoll.openScore"))
  3716. {
  3717. // FL: Import MIDI and Open score share one file window (FUN_0120b340): .fsc, .mid or both
  3718. const auto score = is ("pianoRoll.openScore");
  3719. chooser = lynx::ui::makeFileChooser (score ? tr ("Open score") : tr ("Import MIDI"), juce::File(),
  3720. score ? "*.fsc;*.mid;*.midi" : "*.mid;*.midi");
  3721. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  3722. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  3723. if (safe != nullptr && fc.getResult().existsAsFile())
  3724. safe->loadFile (fc.getResult());
  3725. });
  3726. }
  3727. else if (is ("pianoRoll.exportMidi"))
  3728. {
  3729. const auto& song = engine.getSong();
  3730. const auto name = juce::String::fromUTF8 (song.activePattern().name.c_str());
  3731. chooser = lynx::ui::makeFileChooser (tr ("Export MIDI"), juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (name + ".mid"),
  3732. "*.mid");
  3733. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  3734. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  3735. auto file = fc.getResult();
  3736. if (safe == nullptr || file == juce::File())
  3737. return;
  3738. if (! file.hasFileExtension ("mid;midi"))
  3739. file = file.withFileExtension (".mid");
  3740. juce::String error;
  3741. if (! MidiFileIo::savePattern (safe->engine.getSong(), safe->engine.getSong().currentPattern, file, error))
  3742. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  3743. });
  3744. }
  3745. else if (is ("pianoRoll.saveScore"))
  3746. {
  3747. const auto channel = engine.getSelectedChannel();
  3748. const auto& song = engine.getSong();
  3749. auto name = channel >= 0 && channel < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str())
  3750. : juce::String ("Score");
  3751. chooser = lynx::ui::makeFileChooser (tr ("Save score as"),
  3752. juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (juce::File::createLegalFileName (name) + ".fsc"),
  3753. "*.fsc;*.mid");
  3754. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  3755. [safe = juce::Component::SafePointer<PianoRollComponent> (this)] (const juce::FileChooser& fc) {
  3756. auto file = fc.getResult();
  3757. if (safe == nullptr || file == juce::File())
  3758. return;
  3759. if (! file.hasFileExtension ("fsc;mid;midi"))
  3760. file = file.withFileExtension (".fsc");
  3761. if (! safe->saveScore (file))
  3762. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Save score as"),
  3763. tr ("There are no notes to save, or the file could not be written."));
  3764. });
  3765. }
  3766. else if (is ("pianoRoll.copyMidiClipboard")) copyToMidiClipboard();
  3767. else if (is ("pianoRoll.pasteMidiClipboard")) pasteFromMidiClipboard();
  3768. else if (is ("pianoRoll.markerAdd")) editPatternMarker (markerKeyTick(), -1);
  3769. else if (is ("pianoRoll.markerAuto"))
  3770. {
  3771. const auto tick = snap ((double) markerKeyTick(), true);
  3772. if (std::none_of (currentPattern (engine.getSong()).markers.begin(), currentPattern (engine.getSong()).markers.end(),
  3773. [tick] (const Marker& m) { return m.tick == tick; })) // (FL keeps the marker there, no undo step)
  3774. engine.editSong ([tick] (Song& s) { noteedit::addPatternAutoMarker (currentPattern (s), tick); });
  3775. repaint();
  3776. }
  3777. else if (is ("pianoRoll.markerSignature")) addPatternSignatureByKey();
  3778. else if (is ("pianoRoll.browseScores"))
  3779. {
  3780. if (onBrowseScores)
  3781. onBrowseScores();
  3782. }
  3783. else if (is ("pianoRoll.groupNotes") || is ("pianoRoll.ungroupNotes"))
  3784. {
  3785. const auto target = selection;
  3786. if (target.empty())
  3787. return true;
  3788. const auto group = is ("pianoRoll.groupNotes");
  3789. editNotes ([&] (Pattern& p) {
  3790. if (group)
  3791. notetools::groupNotes (p, target);
  3792. else
  3793. notetools::ungroupNotes (p, target);
  3794. });
  3795. repaint();
  3796. }
  3797. else
  3798. return false;
  3799. return true;
  3800. }
  3801. void PianoRollComponent::wheelNoteProperty (int note, float deltaY, bool fine, juce::Point<int> mouse)
  3802. {
  3803. // FL 2026 [SHOT round 166e]: the whole selection wherever the mouse is, else the one note
  3804. const auto targets = note < 0 ? selection : std::vector<int> { note };
  3805. if (targets.empty())
  3806. return;
  3807. const auto now = juce::Time::getMillisecondCounter();
  3808. const auto newBurst = now - lastWheelEdit > 700; // one undo step per burst of wheel moves
  3809. lastWheelEdit = now;
  3810. editNotes ([&] (Pattern& p) {
  3811. for (auto i : targets)
  3812. {
  3813. auto& n = p.notes[(std::size_t) i];
  3814. setLaneValue (n, (float) gesture::wheelStepValue (laneValue (n), deltaY, fine));
  3815. }
  3816. if (laneIsChance())
  3817. notetools::spreadGroupChance (p, targets);
  3818. }, newBurst);
  3819. // hear it (FL previews the single note; the selection's nearest note too is LYNX's own, issue #16) and a single
  3820. // note becomes the template for new notes (FL)
  3821. const auto& notes = currentPattern (engine.getSong()).notes;
  3822. const auto heard = note >= 0 ? note : noteedit::nearestNote (notes, targets, xToTick (mouse.x), yToKey (mouse.y), pixelsPerTick, rowHeight);
  3823. if (heard < 0 || heard >= (int) notes.size())
  3824. return;
  3825. const auto& n = notes[(std::size_t) heard];
  3826. if (note >= 0)
  3827. noteTemplate.takeFrom (n);
  3828. previewEdit (n.key, n.velocity);
  3829. const auto serial = ++wheelPreviewSerial;
  3830. juce::Timer::callAfterDelay (180, [safe = juce::Component::SafePointer<PianoRollComponent> (this), serial] {
  3831. if (safe != nullptr && safe->wheelPreviewSerial == serial && safe->drag == Drag::none)
  3832. safe->previewOff();
  3833. });
  3834. }
  3835. void PianoRollComponent::glideBy (double ticks, double pixels, bool immediate)
  3836. {
  3837. if (! gliding)
  3838. {
  3839. glideX.jumpTo (scrollTicks);
  3840. glideY.jumpTo (scrollY);
  3841. gliding = true;
  3842. }
  3843. const auto grid = gridArea();
  3844. glideX.target = juce::jlimit (0.0, juce::jmax (0.0, (double) viewLengthTicks() - grid.getWidth() / pixelsPerTick), glideX.target + ticks);
  3845. glideY.target = juce::jlimit (0.0, juce::jmax (0.0, (double) rows.count * rowHeight - grid.getHeight()), glideY.target + pixels);
  3846. if (immediate || ! ui::motion::enabled()) // (Settings › General › Animations off: the wheel jumps)
  3847. {
  3848. scrollTicks = glideX.target;
  3849. scrollY = (int) std::round (glideY.target);
  3850. gliding = false;
  3851. updateScrollBars();
  3852. glideX.jumpTo (scrollTicks);
  3853. glideY.jumpTo (scrollY);
  3854. repaint();
  3855. return;
  3856. }
  3857. vblank.start(); // the next frames at the display's refresh (round 190gv: no vertical blanks while still)
  3858. glideFrame();
  3859. }
  3860. void PianoRollComponent::glideFrame()
  3861. {
  3862. if (! gliding)
  3863. return;
  3864. // someone else moved the view (scroll bar, zoom, pan): the glide gives way
  3865. if (std::abs (scrollTicks - glideX.current) > 1e-6 || std::abs ((double) scrollY - std::round (glideY.current)) > 0.5)
  3866. {
  3867. gliding = false;
  3868. return;
  3869. }
  3870. scrollTicks = glideX.step (0.45, 0.5 / pixelsPerTick);
  3871. scrollY = (int) std::round (glideY.step (0.45, 1.0));
  3872. glideY.current = scrollY;
  3873. updateScrollBars();
  3874. glideX.current = scrollTicks; // the scroll bar may have clamped it
  3875. gliding = glideX.isMoving() || glideY.isMoving();
  3876. repaint();
  3877. }
  3878. void PianoRollComponent::mouseMagnify (const juce::MouseEvent& e, float scale)
  3879. {
  3880. gliding = false;
  3881. const auto factor = gesture::pinchZoomFactor (scale);
  3882. if (e.mods.isAltDown()) // taller / shorter keys, keeping the key under the pointer in place
  3883. {
  3884. const auto key = yToKey (e.y);
  3885. const auto offset = e.y - keyToY (key);
  3886. const auto height = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, juce::roundToInt (rowHeight * factor));
  3887. rowHeight = height != rowHeight ? height : juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, rowHeight + (factor > 1.0 ? 1 : factor < 1.0 ? -1 : 0));
  3888. scrollY = juce::jmax (0, rowFor (key) * rowHeight + offset - (e.y - headerHeight));
  3889. }
  3890. else
  3891. {
  3892. const auto anchorPixels = (double) juce::jmax (0, e.x - keyboardWidth);
  3893. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * factor);
  3894. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  3895. pixelsPerTick = zoomed;
  3896. }
  3897. updateScrollBars();
  3898. repaint();
  3899. }
  3900. void PianoRollComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& rawWheel)
  3901. {
  3902. const auto wheel = flmods::normalisedWheel (rawWheel); // Windows touchpads: pieces of a notch (round 170e)
  3903. const auto ctrl = flmods::ctrl (e.mods), alt = e.mods.isAltDown(), shift = e.mods.isShiftDown();
  3904. const auto overGrid = gridArea().contains (e.getPosition()) || velocityArea().contains (e.getPosition());
  3905. // the wheel over the zoom wheel: one zoom level a notch (FL: the only wheel gesture of the vertical zoom)
  3906. if (zoomWheelArea().contains (e.getPosition()))
  3907. {
  3908. if (wheel.deltaY != 0.0f)
  3909. {
  3910. const auto key = zoomAnchorKey();
  3911. setRowHeightAround (rowHeight + (wheel.deltaY > 0 ? 2 : -2), key, keyToY (key) + rowHeight / 2);
  3912. }
  3913. return;
  3914. }
  3915. // Alt+wheel: the velocity (or the lane's property) of the selected notes wherever the mouse is, with nothing
  3916. // selected of the note nearest to the mouse (FL 2026, round 166e); Ctrl+Alt: fine steps
  3917. if (alt && ! shift && overGrid && wheel.deltaY != 0.0f)
  3918. {
  3919. auto note = -1;
  3920. if (selection.empty())
  3921. {
  3922. note = hoverAt (e.getPosition()).note;
  3923. if (note < 0)
  3924. note = noteedit::nearestNote (currentPattern (engine.getSong()).notes, channelNotes(), xToTick (e.x), yToKey (e.y), pixelsPerTick,
  3925. velocityArea().contains (e.getPosition()) ? 0.0 : rowHeight);
  3926. }
  3927. if (note >= 0 || ! selection.empty())
  3928. {
  3929. wheelNoteProperty (note, wheel.deltaY, ctrl, e.getPosition());
  3930. return;
  3931. }
  3932. }
  3933. if (shift && alt) // nudge the selection by the grid
  3934. {
  3935. if (wheel.deltaY != 0.0f && ! selection.empty())
  3936. {
  3937. const auto now = juce::Time::getMillisecondCounter();
  3938. const auto newBurst = now - lastWheelEdit > 700;
  3939. lastWheelEdit = now;
  3940. const auto ticks = (wheel.deltaY > 0 ? 1 : -1) * gridTicks();
  3941. editNotes ([this, ticks] (Pattern& p) {
  3942. auto deltaTicks = ticks;
  3943. auto deltaKeys = 0;
  3944. noteedit::move (p, selection, deltaTicks, deltaKeys);
  3945. }, newBurst);
  3946. sortNotes();
  3947. }
  3948. return;
  3949. }
  3950. gliding = false;
  3951. if (ctrl && alt)
  3952. {
  3953. // vertical zoom keeping the key under the mouse in place
  3954. const auto key = yToKey (e.y);
  3955. const auto offset = e.y - keyToY (key);
  3956. rowHeight = juce::jlimit (gesture::minKeyHeight, gesture::maxKeyHeight, rowHeight + (wheel.deltaY > 0 ? 2 : -2));
  3957. scrollY = juce::jmax (0, rowFor (key) * rowHeight + offset - (e.y - headerHeight));
  3958. }
  3959. else if (ctrl)
  3960. {
  3961. // zoom keeping the tick under the mouse in place
  3962. const auto anchorPixels = (double) juce::jmax (0, e.x - keyboardWidth);
  3963. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  3964. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  3965. pixelsPerTick = zoomed;
  3966. }
  3967. else
  3968. {
  3969. // plain wheel: up/down (Shift: left/right); a horizontal wheel or trackpad swipe scrolls sideways
  3970. const auto vertical = gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 3.0 * rowHeight);
  3971. const auto sideways = gesture::wheelScrollPixels (wheel.deltaX, wheel.isSmooth, 60.0);
  3972. if (shift)
  3973. glideBy (gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 80.0) / pixelsPerTick, 0.0, wheel.isSmooth);
  3974. else
  3975. glideBy (sideways / pixelsPerTick, vertical, wheel.isSmooth); // a trackpad moves the view at once
  3976. return;
  3977. }
  3978. updateScrollBars();
  3979. repaint();
  3980. }
  3981. // --- keyboard ----------------------------------------------------------------
  3982. void PianoRollComponent::deleteSelection()
  3983. {
  3984. if (selection.empty())
  3985. return;
  3986. const auto doomed = selection;
  3987. setSelection ({});
  3988. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  3989. }
  3990. void PianoRollComponent::copySelection()
  3991. {
  3992. clipboard = noteedit::copy (currentPattern (engine.getSong()), selectionOrAll());
  3993. }
  3994. // Pain point 26 (round 177d, LYNX's own; FL's ghost notes can only be looked at): the ghost notes on show (the other
  3995. // channels' notes in this pattern, and this channel's notes in the clips that play at the same time) go to the note
  3996. // clipboard, so Ctrl+V pastes them into the channel being edited, where they were drawn.
  3997. std::vector<Note> PianoRollComponent::visibleGhostNotes() const
  3998. {
  3999. std::vector<Note> out;
  4000. if (! showGhosts || allChannels)
  4001. return out;
  4002. const auto& song = engine.getSong();
  4003. for (const auto& n : currentPattern (song).notes)
  4004. if (! edits (n) && ghostShown (n.channel))
  4005. out.push_back (n);
  4006. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, engine.getSelectedChannel()))
  4007. out.push_back (n);
  4008. std::stable_sort (out.begin(), out.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  4009. return out;
  4010. }
  4011. void PianoRollComponent::copyGhostNotes()
  4012. {
  4013. auto ghosts = visibleGhostNotes();
  4014. if (ghosts.empty())
  4015. return;
  4016. const auto count = (int) ghosts.size();
  4017. clipboard = std::move (ghosts);
  4018. ui::postHint ({ tr ("Copied {0} ghost notes: Ctrl+V pastes them into this channel", { juce::String (count) }) }, 2500);
  4019. }
  4020. void PianoRollComponent::paste()
  4021. {
  4022. if (clipboard.empty())
  4023. return;
  4024. // as in FL: pastes at the same position, already selected for dragging
  4025. std::vector<int> added;
  4026. const auto channel = allChannels ? -1 : engine.getSelectedChannel(); // ("All": each note keeps its channel)
  4027. editNotes ([&added, channel] (Pattern& p) {
  4028. added = noteedit::paste (p, clipboard, 0, channel);
  4029. notetools::regroup (p, added); // copies of grouped notes form groups of their own
  4030. });
  4031. setSelection (added);
  4032. sortNotes();
  4033. }
  4034. void PianoRollComponent::duplicateSelection()
  4035. {
  4036. const auto source = selectionOrAll();
  4037. if (source.empty())
  4038. return;
  4039. std::vector<int> added;
  4040. const auto meter = engine.getSong().meter();
  4041. editNotes ([&added, &source, meter] (Pattern& p) {
  4042. added = noteedit::duplicateBars (p, source, meter); // FL: whole bars later (round 170h)
  4043. notetools::regroup (p, added);
  4044. });
  4045. setSelection (added);
  4046. sortNotes();
  4047. }
  4048. void PianoRollComponent::quantizeOperation (int kind)
  4049. {
  4050. const auto grid = gridTicks();
  4051. runOperation ([grid, kind] (Pattern& p, const std::vector<int>& t) {
  4052. if (kind == 1)
  4053. noteedit::quantizeFull (p, t, grid);
  4054. else
  4055. transportedit::quantizeNoteStarts (p, t, grid, kind == 2 ? 0.5 : 1.0);
  4056. return t;
  4057. });
  4058. }
  4059. void PianoRollComponent::nudge (std::int64_t ticks, int keys)
  4060. {
  4061. if (selection.empty())
  4062. return;
  4063. // folded to the scale (round 166d): Up / Down step through the shown keys (an octave stays an octave)
  4064. if (folded() && keys != 0 && std::abs (keys) < 12)
  4065. {
  4066. editNotes ([this, &ticks, keys] (Pattern& p) {
  4067. auto noKeys = 0;
  4068. noteedit::move (p, selection, ticks, noKeys);
  4069. for (auto i : selection)
  4070. if (i >= 0 && i < (int) p.notes.size())
  4071. p.notes[(std::size_t) i].key = rows.step (p.notes[(std::size_t) i].key, keys);
  4072. });
  4073. }
  4074. else
  4075. {
  4076. if (keys == 1 || keys == -1) // snap to scale: up / down step along the scale (every selected note, issue #14)
  4077. if (const auto scale = snapScale(); scale.active())
  4078. {
  4079. editNotes ([this, keys, scale] (Pattern& p) { scalesnap::moveBySteps (p, selection, keys, scale); });
  4080. keys = 0;
  4081. if (ticks == 0)
  4082. {
  4083. sortNotes();
  4084. return;
  4085. }
  4086. }
  4087. editNotes ([this, &ticks, &keys] (Pattern& p) { noteedit::move (p, selection, ticks, keys); });
  4088. }
  4089. if (keys != 0 && selection.size() == 1)
  4090. {
  4091. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) selection[0]];
  4092. previewEdit (n.key, n.velocity);
  4093. juce::Timer::callAfterDelay (150, [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  4094. if (safe != nullptr)
  4095. safe->previewOff();
  4096. });
  4097. }
  4098. sortNotes();
  4099. }
  4100. bool PianoRollComponent::handleKey (const juce::KeyPress& key)
  4101. {
  4102. const auto mods = key.getModifiers();
  4103. const auto cmd = mods.isCommandDown();
  4104. const auto alt = mods.isAltDown();
  4105. const auto shift = mods.isShiftDown();
  4106. const auto code = key.getKeyCode();
  4107. const auto letter = keys::letterOfKeyCode (code); // (0 for F-keys, numpad, arrows: issue #12)
  4108. const auto grid = gridTicks();
  4109. const auto bar = engine.getSong().barTicks();
  4110. // round 190hr: the Clip-launch layout's docked editor takes the reference's grid keys (Ctrl+1…5) and Quantize
  4111. // (Ctrl+U / Ctrl+Shift+U) before the FL editor's own (FL's Ctrl+U chop stays in the Pattern layout)
  4112. if (liveGridOn() && cmd && ! alt)
  4113. {
  4114. const char* live = nullptr;
  4115. if (letter == 'U')
  4116. live = shift ? "pianoRoll.liveQuantizeSettings" : "pianoRoll.liveQuantize";
  4117. else if (! shift && code >= '1' && code <= '5')
  4118. {
  4119. static constexpr const char* gridKeys[] { "pianoRoll.liveGridNarrower", "pianoRoll.liveGridWider", "pianoRoll.liveGridTriplet",
  4120. "pianoRoll.liveGridSnap", "pianoRoll.liveGridFixed" };
  4121. live = gridKeys[code - '1'];
  4122. }
  4123. if (live != nullptr && runAction (live))
  4124. return true;
  4125. }
  4126. if (code == juce::KeyPress::backspaceKey)
  4127. {
  4128. EditorGlobals::get().toggleGrid();
  4129. return true;
  4130. }
  4131. if (code == juce::KeyPress::deleteKey && ! cmd) // (Ctrl+Shift+Del: pattern.delete; Ctrl+Del: pianoRoll.deleteSpace)
  4132. {
  4133. deleteSelection();
  4134. return true;
  4135. }
  4136. if (code == juce::KeyPress::escapeKey)
  4137. {
  4138. setSelection ({});
  4139. setTimeSelection (-1, -1);
  4140. return true;
  4141. }
  4142. if (alt && cmd && letter == 'V') // editable ghost notes
  4143. {
  4144. editGhosts = ! editGhosts;
  4145. if (editGhosts && ! showGhosts)
  4146. ghostButton.setToggleState (true, juce::sendNotificationSync);
  4147. repaint();
  4148. return true;
  4149. }
  4150. if (alt && ! cmd && letter == 'V')
  4151. {
  4152. ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync);
  4153. return true;
  4154. }
  4155. if (cmd && alt && code == juce::KeyPress::homeKey)
  4156. {
  4157. resizeFromLeft = ! resizeFromLeft;
  4158. return true;
  4159. }
  4160. if (cmd && letter == 'A')
  4161. {
  4162. selectAll();
  4163. return true;
  4164. }
  4165. if (cmd && ! shift && letter == 'C') // (Ctrl+Shift+C: pattern.clone)
  4166. {
  4167. copySelection();
  4168. return true;
  4169. }
  4170. if (cmd && letter == 'X')
  4171. {
  4172. copySelection();
  4173. deleteSelection();
  4174. return true;
  4175. }
  4176. if (cmd && ! shift && letter == 'V') // (Ctrl+Shift+V: pianoRoll.pasteMidiClipboard)
  4177. {
  4178. paste();
  4179. return true;
  4180. }
  4181. if (cmd && letter == 'B')
  4182. {
  4183. duplicateSelection();
  4184. return true;
  4185. }
  4186. // quick note operations: one undo step each, on the selection (or all notes). The quantize ones are key map
  4187. // actions (pianoRoll.quickQuantize / quantizeStarts / quantizeHalf) so they can be reassigned.
  4188. if (cmd && letter == 'U')
  4189. {
  4190. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); });
  4191. return true;
  4192. }
  4193. if (cmd && letter == 'G')
  4194. {
  4195. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; });
  4196. return true;
  4197. }
  4198. if (cmd && letter == 'L')
  4199. {
  4200. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; });
  4201. return true;
  4202. }
  4203. if (shift && ! cmd && ! alt && letter == 'D')
  4204. {
  4205. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::shrinkToGrid (p, t, grid); return t; });
  4206. return true;
  4207. }
  4208. if (cmd && shift && (code == juce::KeyPress::leftKey || code == juce::KeyPress::rightKey))
  4209. {
  4210. const auto steps = code == juce::KeyPress::rightKey ? 1 : -1;
  4211. runOperation ([grid, bar, steps] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, steps); return t; });
  4212. return true;
  4213. }
  4214. // FL's editor keys (ShortcutsModule EEMuteAction / EEUnmuteAction / EEDeselAction, round 167j): Alt+M mutes,
  4215. // Shift+Alt+M unmutes, Ctrl+D deselects. (Ctrl+M stays FL's metronome.)
  4216. if (alt && ! cmd && letter == 'M')
  4217. {
  4218. setNotesMuted (! shift);
  4219. return true;
  4220. }
  4221. if (cmd && ! alt && ! shift && letter == 'D')
  4222. {
  4223. setSelection ({});
  4224. setTimeSelection (-1, -1);
  4225. return true;
  4226. }
  4227. if (cmd && letter == 'P')
  4228. {
  4229. togglePorta();
  4230. return true;
  4231. }
  4232. // FL's editor arrow keys (noteedit::arrowMove): Shift+Up/Down a semitone, Ctrl+Up/Down an octave,
  4233. // Shift+Left/Right one grid step
  4234. if (! selection.empty())
  4235. {
  4236. using noteedit::Arrow;
  4237. const auto arrow = code == juce::KeyPress::upKey ? std::optional<Arrow> (Arrow::up)
  4238. : code == juce::KeyPress::downKey ? std::optional<Arrow> (Arrow::down)
  4239. : code == juce::KeyPress::leftKey ? std::optional<Arrow> (Arrow::left)
  4240. : code == juce::KeyPress::rightKey ? std::optional<Arrow> (Arrow::right)
  4241. : std::nullopt;
  4242. if (arrow)
  4243. if (const auto move = noteedit::arrowMove (*arrow, cmd, shift, alt); move.handled)
  4244. {
  4245. nudge (move.gridSteps * grid, move.keys);
  4246. return true;
  4247. }
  4248. }
  4249. // (the tools and the other single letters are key map actions now: runKeyAction, issue #12)
  4250. return false;
  4251. }
  4252. bool PianoRollComponent::runKeyAction (const std::string& id)
  4253. {
  4254. for (const auto& t : editTools())
  4255. if (t.tool != EditTool::slip && id == "pianoRoll.tool." + std::string (editToolId (t.tool)))
  4256. {
  4257. tools.setTool (t.tool);
  4258. return true;
  4259. }
  4260. if (id == "pianoRoll.slide") slideButton.setToggleState (! slideButton.getToggleState(), juce::dontSendNotification);
  4261. else if (id == "pianoRoll.previousChannel") stepChannel (-1, false);
  4262. else if (id == "pianoRoll.nextChannel") stepChannel (1, false);
  4263. else if (id == "pianoRoll.previousChannelWithNotes") stepChannel (-1, true);
  4264. else if (id == "pianoRoll.nextChannelWithNotes") stepChannel (1, true);
  4265. else return false;
  4266. return true;
  4267. }
  4268. void PianoRollComponent::refreshToolKeys (const std::function<juce::String (const std::string&)>& keyOf)
  4269. {
  4270. tools.refreshKeys ([&keyOf] (EditTool t) { return keyOf ("pianoRoll.tool." + std::string (editToolId (t))); });
  4271. // round 179a: the slide toggle is only an icon, so its tips name its key the way the tool buttons do
  4272. const auto slideKey = keyOf ("pianoRoll.slide");
  4273. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)")
  4274. + (slideKey.isNotEmpty() ? " (" + slideKey + ")" : juce::String()));
  4275. ui::setQuickTip (slideButton, tr ("Slide notes"), slideKey);
  4276. }
  4277. juce::PopupMenu PianoRollComponent::midiMenu()
  4278. {
  4279. juce::PopupMenu menu;
  4280. menu.addItem (tr ("Import .mid into this channel...") + keyText ("pianoRoll.importMidi"), [this] { runAction ("pianoRoll.importMidi"); });
  4281. menu.addItem (tr ("Export pattern as .mid...") + keyText ("pianoRoll.exportMidi"), [this] { runAction ("pianoRoll.exportMidi"); });
  4282. return menu;
  4283. }
  4284. void PianoRollComponent::importMidi (const midiimport::ParsedMidi& midi, const juce::String& name)
  4285. {
  4286. // FL's "Import MIDI data" window with Blend (REA round 146b): which tracks / channels / controller
  4287. static midiimport::Options remembered;
  4288. juce::Component::SafePointer<PianoRollComponent> safe (this);
  4289. showMidiImportDialog (name, midi, remembered, true, [safe, midi] (const midiimport::Options& o) {
  4290. remembered = o;
  4291. if (safe == nullptr)
  4292. return;
  4293. std::vector<int> added;
  4294. std::string err;
  4295. const auto channel = safe->engine.getSelectedChannel();
  4296. safe->engine.editSong ([&] (Song& s) { added = midiimport::importIntoChannel (s, channel, midi, o, err); });
  4297. if (added.empty())
  4298. {
  4299. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", juce::String::fromUTF8 (err.c_str()));
  4300. return;
  4301. }
  4302. safe->knownNoteCount = currentPattern (safe->engine.getSong()).notes.size();
  4303. safe->setSelection (added);
  4304. safe->scrollToNotes();
  4305. safe->repaint();
  4306. });
  4307. }
  4308. // --- other -------------------------------------------------------------------
  4309. void PianoRollComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
  4310. {
  4311. if (bar == &hBar)
  4312. scrollTicks = start;
  4313. else
  4314. scrollY = (int) start;
  4315. repaint();
  4316. }
  4317. void PianoRollComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  4318. {
  4319. // pattern/channel switched or the pattern changed externally (undo, another window): the selection no longer applies
  4320. const auto& song = engine.getSong();
  4321. const auto count = currentPattern (song).notes.size();
  4322. if (song.currentPattern != knownPattern || engine.getSelectedChannel() != knownChannel || count != knownNoteCount)
  4323. {
  4324. if (engine.getSelectedChannel() != knownChannel)
  4325. {
  4326. stopListening();
  4327. if (knownChannel >= 0)
  4328. allChannels = false; // another channel picked (Channel Rack, keys): back to it alone
  4329. }
  4330. if (song.currentPattern != knownPattern)
  4331. timeFrom = timeTo = -1; // (the time selection belongs to the pattern it was made in)
  4332. knownPattern = song.currentPattern;
  4333. knownChannel = engine.getSelectedChannel();
  4334. knownNoteCount = count;
  4335. if (drag == Drag::none)
  4336. selection.clear();
  4337. }
  4338. followButton.setToggleState (EditorGlobals::get().isFollowing (true), juce::dontSendNotification);
  4339. syncPadRows();
  4340. refreshChannelBox();
  4341. rebuildLaneBox();
  4342. updateScrollBars();
  4343. repaint();
  4344. }
  4345. std::optional<AutomationTarget> PianoRollComponent::eventLaneTarget() const
  4346. {
  4347. const auto k = laneBox.getSelectedId() - eventLaneIdBase;
  4348. if (k >= 0 && k < (int) eventTargets.size())
  4349. return eventTargets[(std::size_t) k];
  4350. return std::nullopt;
  4351. }
  4352. void PianoRollComponent::rebuildLaneBox (std::optional<AutomationTarget> shown, bool force)
  4353. {
  4354. // the pattern's event lanes, plus the one shown (it may have no events yet)
  4355. if (! shown)
  4356. shown = eventLaneTarget();
  4357. std::vector<AutomationTarget> targets;
  4358. for (const auto& lane : currentPattern (engine.getSong()).events)
  4359. if (lane.target.kind != AutomationTargetKind::none && ! lane.events.empty())
  4360. targets.push_back (lane.target);
  4361. if (shown && std::find (targets.begin(), targets.end(), *shown) == targets.end())
  4362. targets.push_back (*shown);
  4363. if (targets == eventTargets && ! force)
  4364. return;
  4365. eventTargets = targets;
  4366. const auto previous = laneBox.getSelectedId();
  4367. laneBox.clear (juce::dontSendNotification);
  4368. addNoteLanes();
  4369. if (! eventTargets.empty())
  4370. laneBox.addSectionHeading (tr ("Pattern events"));
  4371. for (int k = 0; k < (int) eventTargets.size(); ++k)
  4372. laneBox.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
  4373. auto id = previous >= 1 && previous <= laneLast ? previous : 1;
  4374. if (shown)
  4375. id = eventLaneIdBase + (int) (std::find (eventTargets.begin(), eventTargets.end(), *shown) - eventTargets.begin());
  4376. laneBox.setSelectedId (id, juce::dontSendNotification);
  4377. }
  4378. void PianoRollComponent::showEventLane (const AutomationTarget& target)
  4379. {
  4380. rebuildLaneBox (target, true);
  4381. repaint();
  4382. }
  4383. void PianoRollComponent::drawEvents (int fromX, int toX, int y, bool erase)
  4384. {
  4385. const auto target = eventLaneTarget();
  4386. if (! target)
  4387. return;
  4388. const auto lane = velocityArea();
  4389. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8));
  4390. const auto step = std::max<std::int64_t> (1, gridTicks());
  4391. const auto t0 = std::max<std::int64_t> (0, (std::int64_t) std::floor (xToTick (juce::jmin (fromX, toX)) / (double) step) * step);
  4392. const auto t1 = std::max (t0 + step, (std::int64_t) std::floor (xToTick (juce::jmax (fromX, toX)) / (double) step) * step + step);
  4393. const auto pattern = engine.getSong().currentPattern;
  4394. engine.editSong ([&] (Song& s) {
  4395. if (pattern < 0 || pattern >= (int) s.patterns.size())
  4396. return;
  4397. auto& p = s.patterns[(std::size_t) pattern];
  4398. if (erase)
  4399. {
  4400. if (auto* l = eventedit::findLane (p, *target))
  4401. eventedit::erase (*l, t0, t1);
  4402. eventedit::removeEmptyLanes (p);
  4403. }
  4404. else
  4405. eventedit::fill (eventedit::laneFor (p, *target), t0, t1, value, step);
  4406. });
  4407. repaint (velocityArea());
  4408. }
  4409. NoteMask PianoRollComponent::soundingNow() const
  4410. {
  4411. if (! allChannels)
  4412. return engine.soundingKeys (engine.getSelectedChannel());
  4413. // "All": every channel with notes in this pattern
  4414. NoteMask all {};
  4415. const auto& song = engine.getSong();
  4416. std::vector<char> seen (song.channels.size(), 0);
  4417. for (const auto& n : currentPattern (song).notes)
  4418. if (n.channel >= 0 && n.channel < (int) seen.size() && ! seen[(std::size_t) n.channel])
  4419. {
  4420. seen[(std::size_t) n.channel] = 1;
  4421. const auto k = engine.soundingKeys (n.channel);
  4422. all[0] |= k[0], all[1] |= k[1];
  4423. }
  4424. if (const auto selected = engine.getSelectedChannel(); selected >= 0 && selected < (int) seen.size() && ! seen[(std::size_t) selected])
  4425. {
  4426. const auto k = engine.soundingKeys (selected);
  4427. all[0] |= k[0], all[1] |= k[1];
  4428. }
  4429. return all;
  4430. }
  4431. void PianoRollComponent::timerCallback()
  4432. {
  4433. if (channelBox.getSelectedId() != (allChannels ? allChannelsId : engine.getSelectedChannel() + 1))
  4434. refreshChannelBox();
  4435. updateChordReadout();
  4436. // the keys the channel plays light up on the keyboard (song, pattern, typing keyboard, MIDI)
  4437. if (const auto lit = isShowing() ? soundingNow() : NoteMask {}; lit != litKeys)
  4438. {
  4439. litKeys = lit;
  4440. repaint (0, headerHeight, keyboardWidth, getHeight() - headerHeight);
  4441. }
  4442. if (const bool playing = engine.getTransport().playing.load(); playButton.getToggleState() != playing)
  4443. playButton.setToggleState (playing, juce::dontSendNotification);
  4444. }
  4445. bool PianoRollComponent::playheadFrame (double)
  4446. {
  4447. auto& transport = engine.getTransport();
  4448. auto tick = -1.0;
  4449. const auto playing = transport.playing.load();
  4450. // the playhead shows while the edited pattern plays: Pattern mode, or a clip of it in Song mode (round 162);
  4451. // stopped in Step edit too (round 170e5): it is where the next played note goes (FL enters step-edit notes at the
  4452. // song position, which it draws in the Piano roll), and it moves a snap step on after each one
  4453. if ((playing || engine.isStepEdit()) && isShowing())
  4454. {
  4455. const auto& song = engine.getSong();
  4456. // (between two audio blocks it moves on at the song's tempo: smooth at 144 Hz, round 174e)
  4457. tick = transportedit::patternPlayhead (song, song.currentPattern, transport.positionTicks.load() + engine.playheadAdvanceTicks(),
  4458. engine.patternLinearOrigin());
  4459. }
  4460. // whenever it moved: the line is anti-aliased, so even a fraction of a pixel shows (zoomed out, a playhead crossing
  4461. // a few pixels a second glides at the display's rate instead of stepping, as FL's does)
  4462. const auto moved = (tick < 0.0) != (playheadTick < 0.0) || std::abs ((tick - playheadTick) * pixelsPerTick) >= 0.002;
  4463. if (moved)
  4464. {
  4465. // (old and new column as one rectangle when they overlap: each rectangle of a repaint is a paint)
  4466. auto column = [this] (double t) {
  4467. return t >= 0.0 ? juce::Rectangle<int> ((int) tickToX (t) - 7, 0, 14, getHeight()) : juce::Rectangle<int>();
  4468. };
  4469. auto dirty = [this] (juce::Rectangle<int> r) {
  4470. if (! r.isEmpty())
  4471. repaint (r);
  4472. };
  4473. const auto before = column (playheadTick);
  4474. playheadTick = tick;
  4475. // Follow: a page further when the playhead leaves the view (off: the view stays where it is)
  4476. const auto grid = gridArea();
  4477. // (Pattern mode loops the pattern: the view holds still at its end and comes back in one jump at the wrap;
  4478. // a take with Loop record off, and Song mode, go on past it: plain paging)
  4479. const auto& followSong = engine.getSong();
  4480. const auto loops = followSong.mode == PlayMode::pattern && engine.patternLinearOrigin() < 0.0 && followSong.currentPattern >= 0
  4481. && followSong.currentPattern < (int) followSong.patterns.size();
  4482. const auto loopTicks = loops ? (double) followSong.activePattern().effectiveLength (followSong.meter()) : 0.0;
  4483. const auto newStart = transportedit::followViewStartInLoop (scrollTicks, grid.getWidth() / pixelsPerTick, tick, 20.0 / pixelsPerTick,
  4484. 20.0 / pixelsPerTick, loopTicks);
  4485. if (EditorGlobals::get().isFollowing (true) && tick >= 0.0 && newStart != scrollTicks && drag == Drag::none)
  4486. {
  4487. scrollTicks = newStart;
  4488. updateScrollBars();
  4489. repaint();
  4490. }
  4491. else if (const auto after = column (tick); ! before.isEmpty() && ! after.isEmpty() && std::abs (after.getX() - before.getX()) <= 14)
  4492. dirty (before.getUnion (after));
  4493. else
  4494. {
  4495. dirty (before);
  4496. dirty (after);
  4497. }
  4498. }
  4499. // round 177d: the notes held in a take grow with the playhead (only their rows, from their start)
  4500. if (engine.isLiveRecording() && isShowing())
  4501. {
  4502. juce::Rectangle<int> area;
  4503. for (const auto& n : engine.liveRecording().held)
  4504. {
  4505. const auto x0 = (int) tickToX ((double) n.start) - 2;
  4506. const auto x1 = juce::jmax (x0 + 8, (int) tickToX ((double) (n.start + n.length)) + 8);
  4507. area = area.getUnion (juce::Rectangle<int> (x0, keyToY (n.key), x1 - x0, rowHeight + 1));
  4508. }
  4509. const auto dirty = area.getUnion (liveHeldArea).getIntersection (gridArea());
  4510. liveHeldArea = area;
  4511. if (! dirty.isEmpty())
  4512. repaint (dirty);
  4513. }
  4514. else if (! liveHeldArea.isEmpty())
  4515. {
  4516. repaint (liveHeldArea);
  4517. liveHeldArea = {};
  4518. }
  4519. return playing || moved;
  4520. }
  4521. // --- round 168g: FL's Piano roll File / Edit / View items ----------------------------------------------------------------
  4522. void PianoRollComponent::setTimeSelection (std::int64_t from, std::int64_t to)
  4523. {
  4524. if (from < 0 || to <= from)
  4525. from = to = -1;
  4526. if (from == timeFrom && to == timeTo)
  4527. return;
  4528. timeFrom = from;
  4529. timeTo = to;
  4530. repaint();
  4531. }
  4532. void PianoRollComponent::spaceOperation (int kind)
  4533. {
  4534. // FL needs a time selection for these (FUN_00eb35f0: nothing without one)
  4535. if (timeFrom < 0 || timeTo <= timeFrom)
  4536. {
  4537. ui::postHint ({ tr ("Select a time range on the ruler first (Ctrl+drag)") }, 2000);
  4538. return;
  4539. }
  4540. std::vector<int> channel;
  4541. const auto& notes = currentPattern (engine.getSong()).notes;
  4542. for (int i = 0; i < (int) notes.size(); ++i)
  4543. if (edits (notes[(std::size_t) i]))
  4544. channel.push_back (i);
  4545. const auto from = timeFrom, to = timeTo;
  4546. const auto& song = engine.getSong();
  4547. const auto end = currentPattern (song).effectiveLength (song.meter());
  4548. const auto who = allChannels ? -1 : engine.getSelectedChannel();
  4549. std::vector<int> moved;
  4550. setSelection ({});
  4551. editNotes ([&] (Pattern& p) {
  4552. if (kind == 0 || kind == 1)
  4553. moved = noteedit::insertSpace (p, channel, from, to, kind == 1);
  4554. else if (kind == 2)
  4555. moved = noteedit::deleteSpace (p, channel, from, to);
  4556. else
  4557. noteedit::trimToSelection (p, who, from, to, end);
  4558. noteedit::sortTracking (p, moved);
  4559. });
  4560. if (kind == 3)
  4561. setTimeSelection (-1, -1); // (FL clears the time selection after a trim)
  4562. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  4563. setSelection (moved); // FL selects the notes that moved (FUN_00e3b1a0)
  4564. }
  4565. void PianoRollComponent::insertControllerValue()
  4566. {
  4567. // FL's Ctrl+I (EEInitAction → FUN_00eb38d0): the event lane's control, its current value, at the start of the
  4568. // time selection (or at the pattern's start)
  4569. const auto target = eventLaneTarget();
  4570. if (! target)
  4571. {
  4572. ui::postHint ({ tr ("Show a control's events in the bottom lane first (its box on the left)") }, 2000);
  4573. return;
  4574. }
  4575. const auto value = engine.getSong().targetValue (*target);
  4576. const auto at = timeFrom >= 0 ? timeFrom : (std::int64_t) 0;
  4577. engine.editSong ([&] (Song& s) { eventedit::setEvent (eventedit::laneFor (currentPattern (s), *target), at, value); });
  4578. repaint (velocityArea());
  4579. }
  4580. void PianoRollComponent::deleteAllNotes()
  4581. {
  4582. // FL's Edit › Delete all (FUN_00e3d230): every note of the edited channel in the pattern, one undo step
  4583. std::vector<int> doomed;
  4584. const auto& notes = currentPattern (engine.getSong()).notes;
  4585. for (int i = 0; i < (int) notes.size(); ++i)
  4586. if (edits (notes[(std::size_t) i]))
  4587. doomed.push_back (i);
  4588. if (doomed.empty())
  4589. return;
  4590. setSelection ({});
  4591. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  4592. }
  4593. bool PianoRollComponent::openScore (const juce::File& file)
  4594. {
  4595. juce::MemoryBlock bytes;
  4596. if (! file.loadFileAsData (bytes))
  4597. return false;
  4598. const auto score = prtools::parseScore (std::span<const std::uint8_t> (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize()));
  4599. if (! score)
  4600. return false;
  4601. const auto channel = engine.getSelectedChannel();
  4602. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  4603. return false;
  4604. // FL's score loading (FUN_00ff85c0): the channel's notes in the pattern are replaced by the score's
  4605. const auto loaded = prtools::notesFromScore (*score, channel);
  4606. std::vector<int> added;
  4607. setSelection ({});
  4608. editNotes ([&] (Pattern& p) {
  4609. std::vector<int> old;
  4610. for (int i = 0; i < (int) p.notes.size(); ++i)
  4611. if (p.notes[(std::size_t) i].channel == channel)
  4612. old.push_back (i);
  4613. noteedit::remove (p, old);
  4614. added = noteedit::paste (p, loaded, 0, channel);
  4615. noteedit::sortTracking (p, added);
  4616. });
  4617. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  4618. repaint();
  4619. return true;
  4620. }
  4621. bool PianoRollComponent::saveScore (const juce::File& file) const
  4622. {
  4623. // FL (FUN_0121b1b0): every note of the edited channel; "*.mid" in the same window saves a MIDI file
  4624. const auto& notes = currentPattern (engine.getSong()).notes;
  4625. std::vector<Note> mine;
  4626. for (const auto& n : notes)
  4627. if (n.channel == engine.getSelectedChannel())
  4628. mine.push_back (n);
  4629. if (mine.empty())
  4630. return false;
  4631. if (file.hasFileExtension ("mid;midi"))
  4632. {
  4633. const auto& song = engine.getSong();
  4634. const auto c = engine.getSelectedChannel();
  4635. const auto smf = MidiFileIo::writeNotes (song, mine, c >= 0 && c < (int) song.channels.size() ? song.channels[(std::size_t) c].name : std::string());
  4636. return file.replaceWithData (smf.getData(), smf.getSize());
  4637. }
  4638. const auto bytes = prtools::writeScore (mine);
  4639. return file.replaceWithData (bytes.data(), bytes.size());
  4640. }
  4641. bool PianoRollComponent::copyToMidiClipboard() const
  4642. {
  4643. const auto& song = engine.getSong();
  4644. const auto c = engine.getSelectedChannel();
  4645. std::vector<Note> mine;
  4646. for (const auto& n : currentPattern (song).notes)
  4647. if (n.channel == c)
  4648. mine.push_back (n);
  4649. if (mine.empty())
  4650. return false;
  4651. const auto smf = MidiFileIo::writeNotes (song, mine, c >= 0 && c < (int) song.channels.size() ? song.channels[(std::size_t) c].name : std::string());
  4652. const auto ok = midiclipboard::put (smf);
  4653. ui::postHint ({ ok ? tr ("Copied {0} notes to the MIDI clipboard", { juce::String ((int) mine.size()) }) : tr ("The clipboard is busy: try again") }, 2000);
  4654. return ok;
  4655. }
  4656. void PianoRollComponent::pasteFromMidiClipboard()
  4657. {
  4658. const auto smf = midiclipboard::get();
  4659. if (! smf)
  4660. {
  4661. ui::postHint ({ tr ("There is no MIDI data in the clipboard") }, 2000);
  4662. return;
  4663. }
  4664. juce::String error;
  4665. const auto midi = MidiFileIo::parseBytes (smf->getData(), smf->getSize(), error);
  4666. if (! midi)
  4667. {
  4668. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", tr ("Error parsing the MIDI data..."));
  4669. return;
  4670. }
  4671. importMidi (*midi, tr ("MIDI from clipboard")); // (FL: the same "Import MIDI data" window, FUN_00e1d090)
  4672. }
  4673. bool PianoRollComponent::loadFile (const juce::File& file)
  4674. {
  4675. if (isScoreFile (file))
  4676. return openScore (file);
  4677. if (isMidiFile (file))
  4678. {
  4679. juce::String error;
  4680. const auto midi = MidiFileIo::parseFile (file, error);
  4681. if (! midi)
  4682. {
  4683. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  4684. return true;
  4685. }
  4686. importMidi (*midi, file.getFileName());
  4687. return true;
  4688. }
  4689. if (BrowserComponent::isAudioFile (file))
  4690. {
  4691. loadBackgroundWave (file);
  4692. return true;
  4693. }
  4694. return false;
  4695. }
  4696. bool PianoRollComponent::isInterestedInFileDrag (const juce::StringArray& files)
  4697. {
  4698. for (const auto& f : files)
  4699. if (const juce::File file (f); isScoreFile (file) || isMidiFile (file) || BrowserComponent::isAudioFile (file))
  4700. return true;
  4701. return false;
  4702. }
  4703. void PianoRollComponent::filesDropped (const juce::StringArray& files, int, int)
  4704. {
  4705. for (const auto& f : files)
  4706. if (loadFile (juce::File (f)))
  4707. return;
  4708. }
  4709. bool PianoRollComponent::isInterestedInDragSource (const juce::DragAndDropTarget::SourceDetails& details)
  4710. {
  4711. if (! BrowserComponent::isBrowserDrag (details))
  4712. return false;
  4713. const auto file = BrowserComponent::draggedFile (details);
  4714. return isScoreFile (file) || isMidiFile (file) || BrowserComponent::isAudioFile (file);
  4715. }
  4716. void PianoRollComponent::itemDropped (const juce::DragAndDropTarget::SourceDetails& details)
  4717. {
  4718. loadFile (BrowserComponent::draggedFile (details));
  4719. }
  4720. bool PianoRollComponent::isBackgroundWaveShown() noexcept
  4721. {
  4722. return backgroundWaveOn() && backgroundWave() != nullptr;
  4723. }
  4724. void PianoRollComponent::setBackgroundWaveShown (bool on)
  4725. {
  4726. backgroundWaveOn() = on;
  4727. if (on && backgroundWave() == nullptr)
  4728. ui::postHint ({ tr ("Drop an audio file on the Piano roll to see it as the background waveform") }, 2500);
  4729. repaint();
  4730. }
  4731. void PianoRollComponent::loadBackgroundWave (const juce::File& file)
  4732. {
  4733. // peaks (min / max per 256 samples, every channel) read off the message thread
  4734. juce::Component::SafePointer<PianoRollComponent> safe (this);
  4735. juce::Thread::launch ([file, safe] {
  4736. auto wave = std::make_shared<BackgroundWave>();
  4737. wave->file = file;
  4738. juce::AudioFormatManager formats;
  4739. registerAudioFormats (formats);
  4740. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (file)); reader != nullptr && reader->lengthInSamples > 0)
  4741. {
  4742. wave->sampleRate = reader->sampleRate > 0 ? reader->sampleRate : 44100.0;
  4743. wave->samples = juce::jmin<std::int64_t> (reader->lengthInSamples, (std::int64_t) (wave->sampleRate * 60.0 * 30.0)); // (30 min at most)
  4744. const auto channels = (int) juce::jlimit (1u, 8u, reader->numChannels);
  4745. constexpr int chunk = BackgroundWave::perPeak * 256;
  4746. juce::AudioBuffer<float> buffer (channels, chunk);
  4747. for (std::int64_t pos = 0; pos < wave->samples; pos += chunk)
  4748. {
  4749. const auto n = (int) juce::jmin<std::int64_t> (chunk, wave->samples - pos);
  4750. buffer.clear();
  4751. reader->read (&buffer, 0, n, pos, true, channels > 1);
  4752. for (int b = 0; b < n; b += BackgroundWave::perPeak)
  4753. {
  4754. auto lo = 0.0f, hi = 0.0f;
  4755. const auto m = juce::jmin (BackgroundWave::perPeak, n - b);
  4756. for (int c = 0; c < channels; ++c)
  4757. {
  4758. const auto range = juce::FloatVectorOperations::findMinAndMax (buffer.getReadPointer (c, b), m);
  4759. lo = juce::jmin (lo, range.getStart());
  4760. hi = juce::jmax (hi, range.getEnd());
  4761. }
  4762. wave->lo.push_back (lo);
  4763. wave->hi.push_back (hi);
  4764. }
  4765. }
  4766. }
  4767. juce::MessageManager::callAsync ([safe, wave] {
  4768. if (wave->lo.empty())
  4769. {
  4770. ui::postHint ({ tr ("This audio file could not be read") }, 2000);
  4771. return;
  4772. }
  4773. backgroundWave() = wave;
  4774. backgroundWaveOn() = true; // FL: loading one turns the view on (FUN_00ead950 (1))
  4775. if (safe != nullptr)
  4776. safe->repaint();
  4777. });
  4778. });
  4779. }
  4780. void PianoRollComponent::paintBackgroundWave (juce::Graphics& g, juce::Rectangle<int> grid)
  4781. {
  4782. const auto wave = backgroundWave();
  4783. if (! backgroundWaveOn() || wave == nullptr || wave->lo.empty())
  4784. return;
  4785. // FL (FUN_00e45a00): from the pattern's start, as long as the audio lasts at the song tempo, across the whole grid
  4786. // height (centred, 90% of the half height)
  4787. const auto& song = engine.getSong();
  4788. const auto ticksPerSecond = juce::jmax (1.0, song.bpm) / 60.0 * ppq;
  4789. const auto ticksPerPeak = BackgroundWave::perPeak / wave->sampleRate * ticksPerSecond;
  4790. const auto centre = (float) grid.getCentreY();
  4791. const auto amplitude = (float) grid.getHeight() * 0.5f * 0.9f;
  4792. const auto x0 = juce::jmax (grid.getX(), (int) std::floor (tickToX (0.0)));
  4793. const auto x1 = juce::jmin (grid.getRight(), (int) std::ceil (tickToX ((double) wave->lo.size() * ticksPerPeak)));
  4794. if (x1 <= x0)
  4795. return;
  4796. juce::RectangleList<float> bars;
  4797. for (int x = x0; x < x1; ++x)
  4798. {
  4799. const auto p0 = (std::int64_t) std::floor (xToTick (x) / ticksPerPeak);
  4800. const auto p1 = juce::jmax (p0 + 1, (std::int64_t) std::floor (xToTick (x + 1) / ticksPerPeak));
  4801. auto lo = 0.0f, hi = 0.0f;
  4802. for (auto p = juce::jmax<std::int64_t> (0, p0); p < juce::jmin<std::int64_t> ((std::int64_t) wave->lo.size(), p1); ++p)
  4803. {
  4804. lo = juce::jmin (lo, wave->lo[(std::size_t) p]);
  4805. hi = juce::jmax (hi, wave->hi[(std::size_t) p]);
  4806. }
  4807. const auto top = centre - juce::jlimit (0.0f, 1.0f, hi) * amplitude, bottom = centre - juce::jlimit (-1.0f, 0.0f, lo) * amplitude;
  4808. bars.addWithoutMerging ({ (float) x, top, 1.0f, juce::jmax (1.0f, bottom - top) });
  4809. }
  4810. g.setColour (theme::colour::textPrimary.withAlpha (0.16f));
  4811. g.fillRectList (bars);
  4812. }
  4813. juce::PopupMenu PianoRollComponent::fileMenu()
  4814. {
  4815. // FL's EEFileMenu (DFM): Open score, Browse scores, Save score as | Import / Export MIDI, Paste from / Copy to MIDI
  4816. // clipboard
  4817. juce::PopupMenu menu;
  4818. menu.addItem (theme::mnemonic (tr ("Open score..."), 'O') + keyText ("pianoRoll.openScore"), [this] { runAction ("pianoRoll.openScore"); });
  4819. menu.addItem (theme::mnemonic (tr ("Browse scores"), 'B') + keyText ("pianoRoll.browseScores"), onBrowseScores != nullptr, false, [this] { runAction ("pianoRoll.browseScores"); });
  4820. menu.addItem (theme::mnemonic (tr ("Save score as..."), 'S') + keyText ("pianoRoll.saveScore"), [this] { runAction ("pianoRoll.saveScore"); });
  4821. menu.addSeparator();
  4822. menu.addItem (theme::mnemonic (tr ("Import MIDI file..."), 'I') + keyText ("pianoRoll.importMidi"), [this] { runAction ("pianoRoll.importMidi"); });
  4823. menu.addItem (theme::mnemonic (tr ("Export as MIDI file..."), 'E') + keyText ("pianoRoll.exportMidi"), [this] { runAction ("pianoRoll.exportMidi"); });
  4824. menu.addItem (theme::mnemonic (tr ("Paste from MIDI clipboard..."), 'P') + keyText ("pianoRoll.pasteMidiClipboard"), midiclipboard::hasMidi(), false,
  4825. [this] { runAction ("pianoRoll.pasteMidiClipboard"); });
  4826. menu.addItem (theme::mnemonic (tr ("Copy to MIDI clipboard"), 'C') + keyText ("pianoRoll.copyMidiClipboard"), [this] { runAction ("pianoRoll.copyMidiClipboard"); });
  4827. return menu;
  4828. }
  4829. juce::PopupMenu PianoRollComponent::editMenu()
  4830. {
  4831. // FL's EEEditMenu, the items that apply to notes (DFM; Shift / Transpose = the arrow keys, round 167j)
  4832. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  4833. const auto grid = gridTicks();
  4834. juce::PopupMenu menu;
  4835. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", ! selection.empty(), false, [this] { copySelection(); deleteSelection(); });
  4836. menu.addItem (theme::mnemonic (tr ("Copy"), 'C') + "\tCtrl+C", [this] { copySelection(); });
  4837. menu.addItem (tr ("Copy ghost notes"), ! visibleGhostNotes().empty(), false, [this] { copyGhostNotes(); }); // (LYNX, round 177d)
  4838. menu.addItem (theme::mnemonic (tr ("Paste"), 'P') + "\tCtrl+V", ! clipboard.empty(), false, [this] { paste(); });
  4839. menu.addItem (theme::mnemonic (tr ("Duplicate"), 'u') + "\tCtrl+B", [this] { duplicateSelection(); });
  4840. menu.addItem (theme::mnemonic (tr ("Delete"), 'D') + "\tDel", ! selection.empty(), false, [this] { deleteSelection(); });
  4841. menu.addItem (theme::mnemonic (tr ("Delete all"), 'a') + keyText ("pianoRoll.deleteAll"), [this] { runAction ("pianoRoll.deleteAll"); });
  4842. menu.addSeparator();
  4843. menu.addItem (tr ("Shift left") + "\tShift+Left", ! selection.empty(), false, [this, grid] { nudge (-grid, 0); });
  4844. menu.addItem (tr ("Shift right") + "\tShift+Right", ! selection.empty(), false, [this, grid] { nudge (grid, 0); });
  4845. menu.addItem (tr ("Transpose up") + "\tShift+Up", ! selection.empty(), false, [this] { nudge (0, 1); });
  4846. menu.addItem (tr ("Transpose down") + "\tShift+Down", ! selection.empty(), false, [this] { nudge (0, -1); });
  4847. menu.addItem (tr ("Transpose one octave up") + "\tCtrl+Up", ! selection.empty(), false, [this] { nudge (0, 12); });
  4848. menu.addItem (tr ("Transpose one octave down") + "\tCtrl+Down", ! selection.empty(), false, [this] { nudge (0, -12); });
  4849. menu.addSeparator();
  4850. menu.addItem (tr ("Insert space") + keyText ("pianoRoll.insertSpace"), hasTime, false, [this] { runAction ("pianoRoll.insertSpace"); });
  4851. menu.addItem (tr ("Slice & insert space") + keyText ("pianoRoll.sliceInsertSpace"), hasTime, false, [this] { runAction ("pianoRoll.sliceInsertSpace"); });
  4852. menu.addItem (tr ("Delete space") + keyText ("pianoRoll.deleteSpace"), hasTime, false, [this] { runAction ("pianoRoll.deleteSpace"); });
  4853. menu.addItem (tr ("Trim") + keyText ("pianoRoll.trimSpace"), hasTime, false, [this] { runAction ("pianoRoll.trimSpace"); });
  4854. menu.addSeparator();
  4855. menu.addItem (tr ("Insert current controller value") + keyText ("pianoRoll.insertControllerValue"), eventLaneTarget().has_value(), false,
  4856. [this] { runAction ("pianoRoll.insertControllerValue"); });
  4857. return menu;
  4858. }
  4859. juce::PopupMenu PianoRollComponent::stampMenu()
  4860. {
  4861. // the toolbar chord box's items, the chosen one ticked ("Note" = no stamp: single notes)
  4862. juce::PopupMenu menu;
  4863. for (int i = 0; i < chordBox.getNumItems(); ++i)
  4864. {
  4865. const auto id = chordBox.getItemId (i);
  4866. menu.addItem (chordBox.getItemText (i) + (id == 1 ? keyText ("pianoRoll.stampNone") : juce::String()), true, chordBox.getSelectedId() == id,
  4867. [this, id] { chordBox.setSelectedId (id, juce::sendNotificationSync); });
  4868. }
  4869. return menu;
  4870. }
  4871. juce::PopupMenu PianoRollComponent::viewMenu()
  4872. {
  4873. // FL's EEViewMenu, its "Helpers" items (DFM)
  4874. juce::PopupMenu menu;
  4875. menu.addItem (tr ("Note grid highlights") + keyText ("pianoRoll.gridHighlights"), true, gridHighlights, [this] { runAction ("pianoRoll.gridHighlights"); });
  4876. menu.addItem (tr ("Show chord name for selection") + keyText ("pianoRoll.showChordName"), true, showChordName,
  4877. [this] { runAction ("pianoRoll.showChordName"); });
  4878. menu.addItem (tr ("Background waveform") + keyText ("pianoRoll.backgroundWave"), true, isBackgroundWaveShown(),
  4879. [this] { runAction ("pianoRoll.backgroundWave"); });
  4880. menu.addItem (tr ("Ruler: song bars (LYNX)") + keyText ("pianoRoll.songBarsRuler"), true, songBarsRuler, [this] { runAction ("pianoRoll.songBarsRuler"); });
  4881. {
  4882. // round 190j (discussion #136): flat = LYNX's keyboard so far, the default. (FL 2026's own keyboard has the white
  4883. // keys meeting behind the black ones, with lines only between B / C and E / F: flshots/fl-pr-keys-x3.png.)
  4884. juce::PopupMenu style;
  4885. const auto add = [this, &style] (const juce::String& name, pianokeys::Style value) {
  4886. style.addItem (name, true, keyStyle == value, [this, value] { setKeyStyle (value); });
  4887. };
  4888. add (tr ("Flat keys"), pianokeys::Style::flat);
  4889. add (tr ("Piano keys (lines between the white keys)"), pianokeys::Style::piano);
  4890. menu.addSubMenu (tr ("Keyboard style"), style);
  4891. }
  4892. if (const auto wave = backgroundWave())
  4893. menu.addItem (tr ("Remove the background waveform ({0})", { wave->file.getFileName() }), [this] {
  4894. backgroundWave().reset();
  4895. backgroundWaveOn() = false;
  4896. repaint();
  4897. });
  4898. return menu;
  4899. }
  4900. // --- the pattern's time markers (round 168g, docs/analise/REA_rodada168g.md §M13) --------------------------------------
  4901. juce::PopupMenu PianoRollComponent::markersMenu()
  4902. {
  4903. // FL's EEMarkerMenu (the Piano roll shows the Playlist's Time markers items, on the pattern's own markers)
  4904. juce::PopupMenu menu;
  4905. menu.addItem (tr ("Add one...") + keyText ("pianoRoll.markerAdd"), [this] { runAction ("pianoRoll.markerAdd"); });
  4906. menu.addItem (tr ("Add auto") + keyText ("pianoRoll.markerAuto"), [this] { runAction ("pianoRoll.markerAuto"); });
  4907. menu.addItem (tr ("Add time signature change...") + keyText ("pianoRoll.markerSignature"), [this] { runAction ("pianoRoll.markerSignature"); });
  4908. const auto any = ! currentPattern (engine.getSong()).markers.empty();
  4909. menu.addSeparator();
  4910. menu.addItem (tr ("Delete all markers"), any, false, [this] {
  4911. engine.editSong ([] (Song& s) { currentPattern (s).markers.clear(); });
  4912. repaint();
  4913. });
  4914. return menu;
  4915. }
  4916. std::int64_t PianoRollComponent::markerKeyTick() const
  4917. {
  4918. // like the Playlist's (FL FUN_0122b0d0 / FUN_01229d20): the time selection's start; else the playhead when it is
  4919. // in view; else the bar line nearest the view's left edge
  4920. if (timeFrom >= 0 && timeTo > timeFrom)
  4921. return timeFrom;
  4922. const auto left = std::max (0.0, scrollTicks);
  4923. const auto right = xToTick (gridArea().getRight());
  4924. if (playheadTick >= left && playheadTick <= right)
  4925. return (std::int64_t) playheadTick;
  4926. const auto bar = engine.getSong().barTicks();
  4927. const auto at = (std::int64_t) left;
  4928. return at % bar > bar / 2 ? (at / bar + 1) * bar : at / bar * bar;
  4929. }
  4930. void PianoRollComponent::editPatternMarker (std::int64_t tick, int existing)
  4931. {
  4932. const auto& markers = currentPattern (engine.getSong()).markers;
  4933. const auto current = existing >= 0 && existing < (int) markers.size() ? juce::String::fromUTF8 (markers[(std::size_t) existing].name.c_str())
  4934. : tr ("Marker");
  4935. // FL's "Marker name" prompt
  4936. auto* window = new juce::AlertWindow (existing >= 0 ? tr ("Rename marker") : tr ("New marker"), {}, juce::MessageBoxIconType::NoIcon, this);
  4937. window->addTextEditor ("name", current);
  4938. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4939. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4940. juce::Component::SafePointer<PianoRollComponent> safe (this);
  4941. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, tick, existing, window] (int result) {
  4942. if (result != 1 || safe == nullptr)
  4943. return;
  4944. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  4945. safe->engine.editSong ([tick, existing, name] (Song& s) {
  4946. auto& p = currentPattern (s);
  4947. if (existing < 0)
  4948. noteedit::addPatternMarker (p, { tick, name, 0, 4 });
  4949. else if (existing < (int) p.markers.size())
  4950. p.markers[(std::size_t) existing].name = name;
  4951. });
  4952. safe->repaint();
  4953. }),
  4954. true);
  4955. }
  4956. void PianoRollComponent::addPatternSignatureByKey()
  4957. {
  4958. const auto& song = engine.getSong();
  4959. const auto hasTime = timeFrom >= 0 && timeTo > timeFrom;
  4960. const auto from = hasTime ? timeFrom : snap ((double) markerKeyTick(), true);
  4961. const auto to = hasTime ? timeTo : (std::int64_t) -1;
  4962. const auto current = noteedit::patternSignatureAt (currentPattern (song), from, song.meter());
  4963. auto* window = new juce::AlertWindow (tr ("Add time signature change..."), {}, juce::MessageBoxIconType::NoIcon, this);
  4964. juce::StringArray numerators, denominators;
  4965. for (int n = 1; n <= 32; ++n)
  4966. numerators.add (juce::String (n));
  4967. for (int d : { 1, 2, 4, 8, 16, 32 })
  4968. denominators.add (juce::String (d));
  4969. window->addComboBox ("numerator", numerators, tr ("Numerator"));
  4970. window->addComboBox ("denominator", denominators, tr ("Denominator"));
  4971. window->getComboBoxComponent ("numerator")->setText (juce::String (current.first), juce::dontSendNotification);
  4972. window->getComboBoxComponent ("denominator")->setText (juce::String (current.second), juce::dontSendNotification);
  4973. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4974. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4975. juce::Component::SafePointer<PianoRollComponent> safe (this);
  4976. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, from, to, window] (int result) {
  4977. if (result != 1 || safe == nullptr)
  4978. return;
  4979. const auto n = window->getComboBoxComponent ("numerator")->getText().getIntValue();
  4980. const auto d = window->getComboBoxComponent ("denominator")->getText().getIntValue();
  4981. safe->engine.editSong ([from, to, n, d] (Song& s) {
  4982. noteedit::addPatternSignatureChange (currentPattern (s), from, to, n, d, s.meter());
  4983. });
  4984. safe->repaint();
  4985. }),
  4986. true);
  4987. }
  4988. int PianoRollComponent::markerAtX (int x) const
  4989. {
  4990. // the flag and the name to its right (the last one drawn wins, as it is on top)
  4991. const auto& markers = currentPattern (engine.getSong()).markers;
  4992. for (int i = (int) markers.size() - 1; i >= 0; --i)
  4993. {
  4994. const auto mx = (int) tickToX ((double) markers[(std::size_t) i].tick);
  4995. if (x >= mx - 3 && x <= mx + 60)
  4996. return i;
  4997. }
  4998. return -1;
  4999. }
  5000. void PianoRollComponent::showPatternMarkerMenu (int index)
  5001. {
  5002. juce::PopupMenu menu;
  5003. menu.addItem (tr ("Rename marker..."), [this, index] { editPatternMarker (0, index); });
  5004. menu.addItem (tr ("Delete marker"), [this, index] {
  5005. engine.editSong ([index] (Song& s) {
  5006. auto& markers = currentPattern (s).markers;
  5007. if (index >= 0 && index < (int) markers.size())
  5008. markers.erase (markers.begin() + index);
  5009. });
  5010. repaint();
  5011. });
  5012. menu.addSeparator();
  5013. menu.addSubMenu (tr ("Time markers"), markersMenu());
  5014. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  5015. }
  5016. // --- MPE lanes (round 190hy, issue #108; core/NoteCurves.h, docs/analise/REA_rodada190hy-mpe.md) -------------------
  5017. // Each note's own pitch bend / slide / pressure curve, edited as Live 11+ edits its note expression: the lane shows the
  5018. // curves over the notes' lengths (the selected notes brighter), a drag draws the curve of the note under the mouse (a
  5019. // selected one first), a point is dragged to move it and double-clicked to delete it; LYNX's own lane gestures on top
  5020. // (right-drag erases, Alt+click clears). FL 2026 has no per-note curves (FLEngine / Fruity Wrapper strings: none).
  5021. void PianoRollComponent::setMpeView (bool on)
  5022. {
  5023. if (mpeStacked == on)
  5024. return;
  5025. mpeStacked = on;
  5026. // (three lanes need room: the Clip-launch dock's 30 px lane grows while the MPE tab shows)
  5027. if (fitKeysToNotes && ! on)
  5028. velocityHeight = compactVelocityHeight; // (on: layoutEventPane sizes the three lanes)
  5029. resized();
  5030. repaint();
  5031. }
  5032. std::vector<std::pair<juce::Rectangle<int>, int>> PianoRollComponent::mpeLaneAreas() const
  5033. {
  5034. std::vector<std::pair<juce::Rectangle<int>, int>> out;
  5035. const auto lane = velocityArea();
  5036. if (lane.getHeight() < 12)
  5037. return out;
  5038. if (mpeStacked)
  5039. {
  5040. auto rest = lane;
  5041. const auto h = lane.getHeight() / 3;
  5042. out.push_back ({ rest.removeFromTop (h), laneMpePitch });
  5043. out.push_back ({ rest.removeFromTop (h), laneMpeSlide });
  5044. out.push_back ({ rest, laneMpePressure });
  5045. }
  5046. else if (isMpeLane (laneBox.getSelectedId()))
  5047. out.push_back ({ lane, laneBox.getSelectedId() });
  5048. return out;
  5049. }
  5050. int PianoRollComponent::mpeLaneAt (juce::Point<int> p, juce::Rectangle<int>* area) const
  5051. {
  5052. for (const auto& [r, id] : mpeLaneAreas())
  5053. if (r.contains (p))
  5054. {
  5055. if (area != nullptr)
  5056. *area = r;
  5057. return id;
  5058. }
  5059. return 0;
  5060. }
  5061. float PianoRollComponent::mpePitchRange() const
  5062. {
  5063. // ±12 semitones, or ±24 / ±48 when a shown note's curve goes further (Live's lane spans the MPE range, ±48)
  5064. auto reach = 0.0f;
  5065. const auto& notes = currentPattern (engine.getSong()).notes;
  5066. for (auto i : channelNotes())
  5067. if (const auto& n = notes[(std::size_t) i]; n.curves.has())
  5068. for (const auto& q : n.curves->lane (NoteCurveLane::pitch))
  5069. reach = juce::jmax (reach, std::abs (q.value));
  5070. return reach <= 1200.0f ? 1200.0f : reach <= 2400.0f ? 2400.0f : notecurves::maxPitchCents;
  5071. }
  5072. float PianoRollComponent::mpeNorm (int lane, float value, float range) const noexcept
  5073. {
  5074. return lane == laneMpePitch ? juce::jlimit (0.0f, 1.0f, 0.5f + value / (2.0f * range)) : juce::jlimit (0.0f, 1.0f, value);
  5075. }
  5076. float PianoRollComponent::mpeValue (int lane, float norm, float range) const noexcept
  5077. {
  5078. norm = juce::jlimit (0.0f, 1.0f, norm);
  5079. if (lane != laneMpePitch)
  5080. return norm;
  5081. const auto cents = (norm - 0.5f) * 2.0f * range;
  5082. return std::abs (cents) < range * 0.015f ? 0.0f : std::round (cents); // (snaps to no bend; whole cents)
  5083. }
  5084. float PianoRollComponent::mpeBase (int lane, const Note& n) noexcept
  5085. {
  5086. return lane == laneMpePitch ? 0.0f : lane == laneMpeSlide ? n.modX : mpe::pressureOfModY (n.modY);
  5087. }
  5088. int PianoRollComponent::mpeNoteAt (int x) const
  5089. {
  5090. const auto tick = xToTick (x);
  5091. const auto& notes = currentPattern (engine.getSong()).notes;
  5092. auto best = -1;
  5093. auto bestSelected = false;
  5094. for (auto i : channelNotes())
  5095. {
  5096. const auto& n = notes[(std::size_t) i];
  5097. if (tick < (double) n.start || tick >= (double) (n.start + n.length))
  5098. continue;
  5099. const auto selected = isSelected (i);
  5100. if (best < 0 || (selected && ! bestSelected)
  5101. || (selected == bestSelected && n.start >= notes[(std::size_t) best].start))
  5102. {
  5103. best = i;
  5104. bestSelected = selected;
  5105. }
  5106. }
  5107. return best;
  5108. }
  5109. int PianoRollComponent::mpePointAt (int note, int lane, juce::Rectangle<int> area, juce::Point<int> p, float range) const
  5110. {
  5111. const auto& notes = currentPattern (engine.getSong()).notes;
  5112. if (note < 0 || note >= (int) notes.size() || ! notes[(std::size_t) note].curves.has())
  5113. return -1;
  5114. const auto& n = notes[(std::size_t) note];
  5115. const auto usable = (float) area.getHeight() - 8.0f;
  5116. const auto& points = n.curves->lane ((NoteCurveLane) (lane - laneMpePitch));
  5117. auto best = -1;
  5118. auto bestDistance = 6.0f;
  5119. for (int k = 0; k < (int) points.size(); ++k)
  5120. {
  5121. const auto x = (float) tickToX ((double) n.start + (double) points[(std::size_t) k].tick);
  5122. const auto y = (float) area.getBottom() - 2.0f - usable * mpeNorm (lane, points[(std::size_t) k].value, range);
  5123. if (const auto d = juce::jmax (std::abs (x - (float) p.x), std::abs (y - (float) p.y)); d < bestDistance)
  5124. {
  5125. bestDistance = d;
  5126. best = k;
  5127. }
  5128. }
  5129. return best;
  5130. }
  5131. void PianoRollComponent::paintMpeLane (juce::Graphics& g, juce::Rectangle<int> area, int lane, float range)
  5132. {
  5133. using namespace theme::colour;
  5134. juce::Graphics::ScopedSaveState state (g);
  5135. g.reduceClipRegion (area);
  5136. const auto& notes = currentPattern (engine.getSong()).notes;
  5137. const auto usable = (float) area.getHeight() - 8.0f;
  5138. const auto yOf = [&] (float norm) { return (float) area.getBottom() - 2.0f - usable * norm; };
  5139. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  5140. if (mpeStacked && lane != laneMpePitch) // (the stacked lanes' dividers)
  5141. {
  5142. g.setColour (border);
  5143. g.drawHorizontalLine (area.getY(), (float) area.getX(), (float) area.getRight());
  5144. }
  5145. if (lane == laneMpePitch) // the "no bend" line, and one per octave
  5146. {
  5147. g.setColour (textPrimary.withAlpha (0.15f));
  5148. g.drawHorizontalLine ((int) yOf (0.5f), (float) area.getX(), (float) area.getRight());
  5149. for (auto c = 1200.0f; c < range; c += 1200.0f)
  5150. for (auto sign : { -1.0f, 1.0f })
  5151. {
  5152. g.setColour (textPrimary.withAlpha (0.06f));
  5153. g.drawHorizontalLine ((int) yOf (mpeNorm (lane, sign * c, range)), (float) area.getX(), (float) area.getRight());
  5154. }
  5155. }
  5156. for (auto i : channelNotes())
  5157. {
  5158. const auto& n = notes[(std::size_t) i];
  5159. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  5160. if (x1 < (float) area.getX() || x0 > (float) area.getRight())
  5161. continue;
  5162. const auto selected = isSelected (i);
  5163. auto colour = selected ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  5164. if (n.muted)
  5165. colour = noteMuted;
  5166. // the note's length, faintly (where its curve lives)
  5167. g.setColour (colour.withAlpha (selected ? 0.10f : 0.05f));
  5168. g.fillRect (juce::Rectangle<float> (x0, (float) area.getY() + 1.0f, juce::jmax (1.0f, x1 - x0), (float) area.getHeight() - 1.0f));
  5169. const auto& points = n.curves->lane (curveLane);
  5170. const auto base = mpeBase (lane, n);
  5171. if (points.empty()) // (no curve: the note's own value, dashed)
  5172. {
  5173. const auto y = yOf (mpeNorm (lane, base, range));
  5174. const float dash[] = { 3.0f, 3.0f };
  5175. g.setColour (colour.withAlpha (selected ? 0.55f : 0.3f));
  5176. g.drawDashedLine (juce::Line<float> (x0, y, x1, y), dash, 2, 1.0f);
  5177. continue;
  5178. }
  5179. juce::Path path;
  5180. path.startNewSubPath (x0, yOf (mpeNorm (lane, points.front().value, range)));
  5181. for (const auto& q : points)
  5182. {
  5183. if ((double) q.tick > (double) n.length)
  5184. break;
  5185. path.lineTo ((float) tickToX ((double) n.start + (double) q.tick), yOf (mpeNorm (lane, q.value, range)));
  5186. }
  5187. path.lineTo (x1, yOf (mpeNorm (lane, n.curves->valueAt (curveLane, (double) n.length, base), range)));
  5188. g.setColour (colour.withAlpha (selected ? 0.95f : 0.6f));
  5189. g.strokePath (path, juce::PathStrokeType (selected ? 1.6f : 1.2f));
  5190. if (selected || points.size() <= 64) // (a recorded take's many points only on the notes being edited)
  5191. for (const auto& q : points)
  5192. if ((double) q.tick <= (double) n.length)
  5193. {
  5194. const auto px = (float) tickToX ((double) n.start + (double) q.tick), py = yOf (mpeNorm (lane, q.value, range));
  5195. g.fillEllipse (px - (selected ? 2.5f : 1.8f), py - (selected ? 2.5f : 1.8f), selected ? 5.0f : 3.6f, selected ? 5.0f : 3.6f);
  5196. }
  5197. }
  5198. // the lane's name and range, top left (as the property lanes write theirs)
  5199. juce::String name = lane == laneMpePitch ? tr ("MPE pitch bend") : lane == laneMpeSlide ? tr ("MPE slide") : tr ("MPE pressure");
  5200. if (lane == laneMpePitch)
  5201. name << " " << juce::String::fromUTF8 ("\xc2\xb1") << tr ("{0} st", { juce::String (juce::roundToInt (range / 100.0f)) });
  5202. g.setColour (textSecondary.withAlpha (0.8f));
  5203. g.setFont (theme::font (theme::type::caption, true));
  5204. textcache::drawText (g, name, area.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  5205. }
  5206. void PianoRollComponent::paintMpePitchOnNotes (juce::Graphics& g, juce::Rectangle<int> grid)
  5207. {
  5208. // as Live's MPE view: the note's pitch over its key row, one row per semitone (its fine pitch included)
  5209. using namespace theme::colour;
  5210. juce::Graphics::ScopedSaveState state (g);
  5211. g.reduceClipRegion (grid);
  5212. const auto& notes = currentPattern (engine.getSong()).notes;
  5213. for (auto i : channelNotes())
  5214. {
  5215. const auto& n = notes[(std::size_t) i];
  5216. if (! n.curves.has() || n.curves->lane (NoteCurveLane::pitch).empty())
  5217. continue;
  5218. const auto x0 = (float) tickToX ((double) n.start), x1 = (float) tickToX ((double) (n.start + n.length));
  5219. if (x1 < (float) grid.getX() || x0 > (float) grid.getRight())
  5220. continue;
  5221. const auto centre = (float) keyToY (n.key) + (float) rowHeight * 0.5f;
  5222. const auto yOf = [&] (float cents) { return centre - (n.finePitch + cents) / 100.0f * (float) rowHeight; };
  5223. const auto& points = n.curves->lane (NoteCurveLane::pitch);
  5224. juce::Path path;
  5225. path.startNewSubPath (x0, yOf (points.front().value));
  5226. for (const auto& q : points)
  5227. {
  5228. if ((double) q.tick > (double) n.length)
  5229. break;
  5230. path.lineTo ((float) tickToX ((double) n.start + (double) q.tick), yOf (q.value));
  5231. }
  5232. path.lineTo (x1, yOf (n.curves->valueAt (NoteCurveLane::pitch, (double) n.length, 0.0f)));
  5233. g.setColour (juce::Colours::black.withAlpha (0.45f));
  5234. g.strokePath (path, juce::PathStrokeType (2.6f));
  5235. g.setColour ((isSelected (i) ? accentHover.brighter (0.4f) : textPrimary).withAlpha (0.9f));
  5236. g.strokePath (path, juce::PathStrokeType (1.3f));
  5237. }
  5238. }
  5239. void PianoRollComponent::editNoteCurves (int note, const std::function<void (Note&)>& edit)
  5240. {
  5241. editNotes ([note, &edit] (Pattern& p) {
  5242. if (note >= 0 && note < (int) p.notes.size())
  5243. edit (p.notes[(std::size_t) note]);
  5244. });
  5245. }
  5246. bool PianoRollComponent::mpeMouseDown (const juce::MouseEvent& e)
  5247. {
  5248. juce::Rectangle<int> area;
  5249. const auto lane = mpeLaneAt (e.getPosition(), &area);
  5250. if (lane == 0)
  5251. return false;
  5252. mpeDragLane = lane;
  5253. mpeDragRange = mpePitchRange();
  5254. lastMpeX = e.x;
  5255. lastMpeY = e.y;
  5256. mpeDragNote = mpeNoteAt (e.x);
  5257. mpeDragPoint = -1;
  5258. if (mpeDragNote < 0)
  5259. return true; // (no note there: nothing to draw on)
  5260. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  5261. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) mpeDragNote];
  5262. const auto norm = (float) (area.getBottom() - 2 - e.y) / (float) juce::jmax (1, area.getHeight() - 8);
  5263. const auto value = mpeValue (lane, norm, mpeDragRange);
  5264. const auto tick = juce::jlimit (0.0, (double) n.length, xToTick (e.x) - (double) n.start);
  5265. const auto base = mpeBase (lane, n);
  5266. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click: the note's lane back to its own value
  5267. {
  5268. editNoteCurves (mpeDragNote, [curveLane] (Note& m) { notecurves::clearLane (m.curves, curveLane); });
  5269. mpeDragNote = -1;
  5270. return true;
  5271. }
  5272. if (e.mods.isRightButtonDown()) // right-drag erases the points it crosses
  5273. {
  5274. drag = Drag::mpeErase;
  5275. editNoteCurves (mpeDragNote, [curveLane, tick] (Note& m) { notecurves::erase (m.curves, curveLane, tick - 1.0, tick + 1.0); });
  5276. return true;
  5277. }
  5278. if (const auto point = mpePointAt (mpeDragNote, lane, area, e.getPosition(), mpeDragRange); point >= 0)
  5279. {
  5280. drag = Drag::mpePoint; // (a point: dragged)
  5281. mpeDragPoint = point;
  5282. return true;
  5283. }
  5284. drag = Drag::mpeDraw; // (elsewhere: drawing starts with a point here)
  5285. mpeCreatedAt = juce::Time::getMillisecondCounter();
  5286. editNoteCurves (mpeDragNote, [curveLane, tick, value, base] (Note& m) { notecurves::addPoint (m.curves, curveLane, tick, value, base); });
  5287. return true;
  5288. }
  5289. bool PianoRollComponent::mpeMouseDrag (const juce::MouseEvent& e)
  5290. {
  5291. const auto& notes = currentPattern (engine.getSong()).notes;
  5292. if (mpeDragNote < 0 || mpeDragNote >= (int) notes.size())
  5293. return true;
  5294. juce::Rectangle<int> area;
  5295. for (const auto& [r, id] : mpeLaneAreas())
  5296. if (id == mpeDragLane)
  5297. area = r;
  5298. if (area.isEmpty())
  5299. return true;
  5300. const auto& n = notes[(std::size_t) mpeDragNote];
  5301. const auto lane = mpeDragLane;
  5302. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  5303. const auto valueAtY = [&] (int y) { return mpeValue (lane, (float) (area.getBottom() - 2 - y) / (float) juce::jmax (1, area.getHeight() - 8), mpeDragRange); };
  5304. const auto tickAtX = [&] (int x) { return juce::jlimit (0.0, (double) n.length, xToTick (x) - (double) n.start); };
  5305. const auto t0 = tickAtX (lastMpeX), t1 = tickAtX (e.x);
  5306. const auto v0 = valueAtY (lastMpeY), v1 = valueAtY (e.y);
  5307. const auto base = mpeBase (lane, n);
  5308. if (drag == Drag::mpePoint)
  5309. {
  5310. const auto point = mpeDragPoint;
  5311. editNoteCurves (mpeDragNote, [curveLane, point, t1, v1] (Note& m) { notecurves::movePoint (m.curves, curveLane, point, t1, v1); });
  5312. }
  5313. else if (drag == Drag::mpeDraw)
  5314. {
  5315. // (one point every 3 pixels along the drag)
  5316. const auto step = juce::jmax (1.0, 3.0 / juce::jmax (1.0e-9, pixelsPerTick));
  5317. editNoteCurves (mpeDragNote, [=] (Note& m) { notecurves::drawLine (m.curves, curveLane, t0, v0, t1, v1, step, base); });
  5318. }
  5319. else
  5320. editNoteCurves (mpeDragNote, [=] (Note& m) { notecurves::erase (m.curves, curveLane, juce::jmin (t0, t1) - 1.0, juce::jmax (t0, t1) + 1.0); });
  5321. lastMpeX = e.x;
  5322. lastMpeY = e.y;
  5323. return true;
  5324. }
  5325. bool PianoRollComponent::mpeDoubleClick (const juce::MouseEvent& e)
  5326. {
  5327. juce::Rectangle<int> area;
  5328. const auto lane = mpeLaneAt (e.getPosition(), &area);
  5329. if (lane == 0 || e.mods.isRightButtonDown())
  5330. return lane != 0;
  5331. // the first click of this double click drew the point: that was adding it, not deleting it
  5332. if (juce::Time::getMillisecondCounter() - mpeCreatedAt < 800)
  5333. return true;
  5334. const auto note = mpeNoteAt (e.x);
  5335. const auto range = mpePitchRange();
  5336. if (const auto point = mpePointAt (note, lane, area, e.getPosition(), range); point >= 0)
  5337. {
  5338. const auto curveLane = (NoteCurveLane) (lane - laneMpePitch);
  5339. editNoteCurves (note, [curveLane, point] (Note& m) { notecurves::removePoint (m.curves, curveLane, point); });
  5340. }
  5341. return true;
  5342. }
  5343. } // namespace lynx