PlaylistComponent.cpp 937 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559
  1. #include <cstring>
  2. #include "core/TransientNav.h" // round 190on (P8)
  3. #include "core/TrackIconScale.h"
  4. #include "core/SelectionRename.h"
  5. #include "core/FlCurve.h"
  6. #include "core/DrawMode.h"
  7. #include "core/LayoutStyle.h"
  8. #include "core/PastePlace.h"
  9. #include "ui/NewtoneEditor.h"
  10. #include "ui/PolyEditor.h"
  11. #include "ui/AraMenu.h"
  12. #include "ui/TempoDetectionDialog.h"
  13. #include "ui/ClipGridComponent.h"
  14. #include "ui/CleanVoiceMenu.h"
  15. #include "ui/FlMods.h"
  16. #include "ui/Motion.h"
  17. #include "platform/Paths.h" // (round 190qe: testMode)
  18. #include "ui/ShotShowing.h"
  19. #include "core/FlSettings.h"
  20. #include "core/RulerGestures.h"
  21. #include "core/ZoomAnchor.h"
  22. #include "core/ClipHandle.h"
  23. #include "ui/ColourPicker.h"
  24. #include "ui/TrackIcons.h"
  25. #include "core/TrackIcons.h"
  26. #include "core/WarpEdit.h"
  27. #include "core/ClipEnvelope.h"
  28. #include "core/ClipWarp.h"
  29. #include "ui/ClipProperties.h"
  30. #include "ui/UiTrace.h"
  31. #include "ui/ImageReadback.h"
  32. #include "ui/TextCache.h"
  33. #include "ui/PlaylistComponent.h"
  34. #include "core/SelectionKeep.h"
  35. #include "core/MuteKeys.h"
  36. #include "core/TempoMarkers.h"
  37. #include "core/PaintTemplate.h"
  38. #include "ui/PaintAB.h" // (round 190md: LYNX_PAINT_SAVINGS=0 paints the end veil as before)
  39. #include "core/PickerDrop.h"
  40. #include "core/ChainPresets.h"
  41. #include "core/ClipLauncher.h"
  42. #include "ui/ArticulatorTools.h"
  43. #include "core/SessionKeys.h"
  44. #include "core/EventEdit.h"
  45. #include "ui/EventEditor.h"
  46. #include "ui/PatternBlocksView.h"
  47. #include "ui/VideoTracks.h"
  48. #include "core/PatternBlocks.h"
  49. #include "ui/StemExtract.h"
  50. #include "ui/AudioToMidi.h"
  51. #include "core/KeyMap.h"
  52. #include "ui/ShortcutManager.h"
  53. #include "core/MarkerPlan.h"
  54. #include "core/Performance.h"
  55. #include "core/Templates.h"
  56. #include "core/TransportEdit.h"
  57. #include "core/ClipOps.h"
  58. #include "core/CopyName.h"
  59. #include "core/FlClipMenu.h"
  60. #include "core/Rack.h"
  61. #include "engine/UniqueSamples.h"
  62. #include "ui/FileChoosers.h"
  63. #include "core/Slicer.h"
  64. #include "core/EditorPolish.h"
  65. #include "core/RackOps.h"
  66. #include "core/NoteEdit.h"
  67. #include "core/PlaylistOps.h"
  68. #include "core/PlaylistTrackOps.h"
  69. #include "core/TrackStates.h"
  70. #include "core/TrackVersions.h"
  71. #include "core/TrackHeaderGestures.h"
  72. #include "core/FolderDrag.h" // round 190jf (B17)
  73. #include "core/CrossPaste.h" // issue #232 stage 2 (round 190nz)
  74. #include "ui/WindowClipboard.h"
  75. #include "core/KeyFollow.h"
  76. #include "core/SimpleTracks.h"
  77. #include "core/TrackOnly.h"
  78. #include "core/RegionLoop.h"
  79. #include "core/QuickRender.h"
  80. #include "core/TempoDetect.h"
  81. #include "core/Comping.h"
  82. #include "core/ExportOptions.h"
  83. #include "core/TakeRecording.h"
  84. #include "core/WheelZones.h" // round 190iu (issue #186)
  85. #include "ui/WorkflowExtras.h" // round 190iu (issue #191)
  86. #include "core/MidiDrop.h"
  87. #include "ui/ExportDialog.h"
  88. #include "ui/MixerComponent.h"
  89. #include "engine/Text.h"
  90. #include "ui/BrowserComponent.h"
  91. #include "ui/PluginDropUi.h"
  92. #include "ui/ClipGridComponent.h"
  93. #include "core/SessionOps.h"
  94. #include "core/DetailChain.h"
  95. #include "core/TrackInserts.h"
  96. #include "core/StandIns.h"
  97. #include "core/Groove.h"
  98. #include "core/GrooveAudio.h"
  99. #include "ui/GroovePoolComponent.h"
  100. #include "ui/AutomationUi.h"
  101. #include "ui/ChannelSettings.h"
  102. #include "ui/Dialogs.h"
  103. #include "ui/HintBar.h"
  104. #include "ui/PluginOffTag.h"
  105. #include "ui/I18n.h"
  106. #include "ui/Theme.h"
  107. #include "ui/LabelFont.h"
  108. #include "ui/WaveformView.h"
  109. #include "ui/AudioEditor.h"
  110. #include "ui/PluginPicker.h"
  111. #include "ui/QuickPick.h"
  112. #include "ui/Icons.h"
  113. #include "ui/SimpleLook.h"
  114. #include "core/SectionOps.h" // round 190ol (the Sections lane)
  115. #include "core/SignatureEdit.h" // round 190ol (P6: Simple time signature changes)
  116. #include "ui/SectionsLane190ol.h" // round 190ol (P1: the Sections lane)
  117. #include "ui/ChordLane190pf.h" // round 190pf (P13: the Chord lane)
  118. #include "ui/SmartTempo190pf.h" // round 190pf (P12: Smart Tempo)
  119. #include "core/LoopAnalysis.h" // round 190kx
  120. #include "core/TrackClips.h" // round 190ne
  121. #include "ui/LoopInfo.h"
  122. #include <map>
  123. #include <unordered_map>
  124. namespace lynx
  125. {
  126. // FL 2026's selection-strip box (live check 190gu, PAIR-header-selection-strip-range): lime, not the LEDs' green
  127. constexpr juce::uint32 selectionStripLimeArgb = 0xffa6d63c;
  128. static const juce::Colour selectionStripLime { selectionStripLimeArgb };
  129. namespace
  130. {
  131. constexpr float clipTitleHeight = 13.0f;
  132. // FL's "+" at the top left of the track headers (TEVENTEDITFORM TLEventPanel.AddInstrBtn, 21 x 18, hint "Add instrument
  133. // track / Add audio track"; round 190dx): a left click opens its menu (AddInstrBtnBeforePopup), a right click adds an
  134. // audio track at once (AddInstrBtnMouseUp, right button -> FUN_012e3640); a middle click opens the "Select generator
  135. // plugin" dialog, as the menu's More plugins... (live check 190ew PL-4)
  136. class AddTrackButton : public juce::Component, public juce::SettableTooltipClient
  137. {
  138. public:
  139. std::function<void()> onMenu, onAddAudioTrack, onMorePlugins;
  140. void paint (juce::Graphics& g) override
  141. {
  142. using namespace theme;
  143. const auto over = isMouseOverOrDragging();
  144. const auto r = getLocalBounds().toFloat().reduced (0.5f);
  145. fillRoundRect (g, r, radius::sm, over ? colour::bg4 : colour::bg3);
  146. g.setColour (over ? colour::accent : colour::textSecondary);
  147. const auto c = r.getCentre();
  148. g.fillRect (juce::Rectangle<float> (c.x - 4.5f, c.y - 0.75f, 9.0f, 1.5f));
  149. g.fillRect (juce::Rectangle<float> (c.x - 0.75f, c.y - 4.5f, 1.5f, 9.0f));
  150. }
  151. void mouseEnter (const juce::MouseEvent&) override { repaint(); }
  152. void mouseExit (const juce::MouseEvent&) override { repaint(); }
  153. void mouseUp (const juce::MouseEvent& e) override
  154. {
  155. if (! getLocalBounds().contains (e.getPosition()))
  156. return;
  157. if (e.mods.isMiddleButtonDown())
  158. {
  159. if (onMorePlugins)
  160. onMorePlugins();
  161. }
  162. else if (flmods::popup (e.mods))
  163. {
  164. if (onAddAudioTrack)
  165. onAddAudioTrack();
  166. }
  167. else if (e.mods.isLeftButtonDown() && onMenu)
  168. onMenu();
  169. }
  170. };
  171. // --- clip look -------------------------------------------------------------------------------------
  172. // One recipe for every clip kind (studied from FL's Playlist, drawn with LYNX's own code and palette): a muted
  173. // header bar holding a small kind glyph and the name, a body in a deep tint of the clip colour, and the
  174. // content (waveform, notes, curve) in a light tint of it; a thin dark edge separates neighbours. Few elements,
  175. // one hue per clip, so a busy Playlist stays calm and every clip reads at a glance.
  176. enum class ClipGlyph { pattern, audio, automation };
  177. // Text colour readable on a clip's header bar.
  178. juce::Colour clipTitleText (juce::Colour band)
  179. {
  180. return band.getPerceivedBrightness() > 0.62f ? theme::colour::bg0 : juce::Colours::white.withAlpha (0.92f);
  181. }
  182. // the header keeps a hint of the clip colour, greyed so the names read and the bodies carry the colour
  183. juce::Colour clipHeaderColour (juce::Colour base) { return base.interpolatedWith (juce::Colour (0xff4b525a), 0.5f); }
  184. juce::Colour clipBodyColour (juce::Colour base) { return base.interpolatedWith (theme::colour::bg1, 0.72f); }
  185. // The content in a light tint of the clip colour; on the pale body of a light theme (issue #95: background #FFFFFF, the
  186. // white-tinted waveform vanished) a dark shade of that body instead.
  187. juce::Colour clipContentColour (juce::Colour base)
  188. {
  189. const auto body = clipBodyColour (base);
  190. if (body.getPerceivedBrightness() <= 0.6f)
  191. return base.interpolatedWith (juce::Colours::white, 0.7f);
  192. // a dark shade of the body, or of the clip colour when that is darker (a dark clip on white: PR #100's point)
  193. const auto shade = body.interpolatedWith (juce::Colours::black, 0.65f), deep = base.interpolatedWith (juce::Colours::black, 0.55f);
  194. return deep.getPerceivedBrightness() < shade.getPerceivedBrightness() ? deep : shade;
  195. }
  196. float clipHeaderHeight (juce::Rectangle<float> r) { return juce::jmin (clipTitleHeight, juce::jmax (0.0f, r.getHeight() - 8.0f)); }
  197. // --- FL Studio's clip look, Pattern layout only (round 190ig, design190ia slice 3: FM-21, FM-22, FM-27) ----------------
  198. // Measured in FL Studio 2026 on "Ookay - Thief" (shots/ref/fl-playlist-zoom-audioclips.png at 50 px tracks, fl-playlist.png
  199. // at 26 px): a clip fills its track row down to the row's separator; on a tall track a header band in the clip's colour
  200. // (15 px with its rim) over a body of the track's colour at 50 % (the grid shows through), the waveform in a light tint
  201. // and a 1 px silence line; on a short track the whole clip is one header-coloured band with the waveform in the clip's
  202. // own colour. The Clip-launch and Simple layouts keep their look (theme::clipBody's Live / BandLab styles are theirs).
  203. bool flClipLook() noexcept { return layoutstyle::current() == layoutstyle::Style::pattern; }
  204. // Round 190qm (PR #268, checked in FL 2026 on Thief: shots/fl/fl3-*): a Playlist track switched off (its LED dark) draws its
  205. // clips as muted clips, the veil and the X in the glyph's place, and its header grey; the lane itself is unchanged. Pattern
  206. // layout only (the Clip-launch and Simple layouts keep their looks). A take lane is muted only so that it stays silent
  207. // (Live's TakeLanes, a comp's lanes: comp::isTakeLane): it keeps its own look (paint gate, Patience: +20 % without this).
  208. bool switchedOff (const Song& song, int track) { return song.isTrackMuted (track) && ! comp::isTakeLane (song, track); }
  209. bool shownMuted (const Song& song, const Clip& c) { return c.muted || (flClipLook() && switchedOff (song, c.track)); }
  210. // FL's two clip forms: the band (one colour) below this track height, header + body from it. FL shows the band at its
  211. // default 26 px tracks and header + body at 50 px; the switch point between was not captured (an open item).
  212. constexpr int flBandBelow = 38;
  213. // FL keeps a clip's glyph and name in view at the Playlist's left edge when the clip starts further left (shots/ref/
  214. // fl-playing.png "GROSS BEAT - Saw Bass", "Main Vox" at bar 21). Those held titles are drawn last, over the lanes and
  215. // just under the playhead: by paint() itself, or over the cached picture (which never holds them, so a scroll can shift
  216. // it); a scroll step in which a clip's start crosses the left edge paints that clip's header band again (cacheShift).
  217. constexpr float flStickyTitleMax = 400.0f;
  218. // FL's grid levels by zoom (live check 190iw Q4, FL 2026's Ctrl+wheel steps measured on the empty grid): bar lines only up
  219. // to 9.9 px a beat, beat lines from 11.5, and a third, faintest level every half beat from 21.5 px a beat (none at 18.4).
  220. // FL's own steps skip the values in between, so the thresholds sit in those gaps.
  221. constexpr double flBeatLinesFrom = 11.0;
  222. constexpr double flHalfBeatLinesFrom = 21.0;
  223. // FL's half-beat line darkens the lane about 10/18 as much as its beat line does (#24343E vs #1C2C36 on #2E3E48)
  224. constexpr float flHalfBeatAlpha = 0.55f;
  225. // --- Live 12.4's Arrangement, Clip-launch layout only (round 190jn, design190ia CL-17, CL-18) ----------------------------
  226. // Measured in live-arrangement.png (default zoom, 5.4 px a bar) and live-arrangement-audiolane.png (34.7 px a bar):
  227. // lanes 17 px + a 2 px #242424 separator; the lane background alternates by groups of bars, #323232 / #363636, a group
  228. // being the smallest power of two of bars at least 80 px wide (16 bars = 86 px, 4 bars = 139 px); in the dark group the
  229. // group's first line #232323, bar lines #282828, beat lines #2c2c2c; in the light one #262626 / #2b2b2b / #303030; bars under
  230. // 8 px apart: a line every 2^k bars (at least 8 px apart) in the group-line colour (10.8 px apart at 2 bars); beats from
  231. // 6 px apart. A clip: one block in its colour, a 1 px rim of colour x 0.53 on its top row, its left column and the row
  232. // under its 15 px title strip (y + 16; on a collapsed lane that is its last row); the name at x + 4, centred in the strip,
  233. // in colour x 0.24; on a taller lane the body below has the grid in colour x 0.88 (beats), x 0.79 (bars), x 0.68 (a group's
  234. // first bar), and the waveform / notes / curve in colour x 0.15.
  235. bool tallLiveLanes = false;
  236. const juce::Colour liveLaneSeparator { 0xff242424 };
  237. constexpr int liveStripHeight = 17; // a lane's title strip (all a collapsed lane shows)
  238. float flHeaderHeight (juce::Rectangle<float> r) { return juce::jlimit (11.0f, 15.0f, std::round (r.getHeight() * 0.3f)); }
  239. // FL's track header (round 190ig, FM-23): the plate in the track's own colour (FL's grey #485156 without one), the name in a
  240. // light tint of it (FL: #AAF2A6 on #237719, colour + 130 per channel), or the primary text where the tint would be too faint
  241. // (round 190qw: the Soft look mutes it, theme::softened)
  242. juce::Colour flHeaderFill (std::uint32_t colour) { return theme::softened (colour != 0 ? juce::Colour (colour).withAlpha (1.0f) : theme::colour::defaultTrack); }
  243. juce::Colour flHeaderInk (juce::Colour plate)
  244. {
  245. const auto f = [] (juce::uint8 v) { return (juce::uint8) juce::jmin (255, (int) v + 130); };
  246. const auto tint = juce::Colour (f (plate.getRed()), f (plate.getGreen()), f (plate.getBlue()));
  247. const auto luminance = [] (juce::Colour c) {
  248. const auto lin = [] (float v) { return v <= 0.04045f ? v / 12.92f : std::pow ((v + 0.055f) / 1.055f, 2.4f); };
  249. return 0.2126f * lin (c.getFloatRed()) + 0.7152f * lin (c.getFloatGreen()) + 0.0722f * lin (c.getFloatBlue());
  250. };
  251. const auto ratio = (luminance (tint) + 0.05f) / (luminance (plate) + 0.05f);
  252. return ratio >= 4.5f ? tint : (plate.getPerceivedBrightness() > 0.6f ? theme::colour::bg0 : theme::colour::textPrimary);
  253. }
  254. // The Simple headers' sizes (round 190jc, design190ia SG-3, BandLab's 82 px rows: M S 26x22, a 26 px pan knob, the volume
  255. // a line in the track colour with a 12 px thumb; LYNX keeps its rows a little lower). Large controls: touch sizes.
  256. struct SimpleHeaderSizes
  257. {
  258. int row, twoRows, top, button, buttonHeight, gap, icon, knob, fxWidth, fxHeight, volumeHit, add;
  259. };
  260. SimpleHeaderSizes simpleSizes()
  261. {
  262. if (ui::simplelook::largeControls())
  263. return { 88, 76, 8, 40, 32, 6, 20, 30, 60, 30, 32, 48 };
  264. return { 64, 54, 6, 24, 20, 4, 16, 20, 44, 18, 20, 40 };
  265. }
  266. // A Simple track's type icon: its own, else its kind's (round 190jc, SG-3; the song is not changed)
  267. trackicons::Icon simpleTrackIcon (const Song& song, int track)
  268. {
  269. if (track < 0 || track >= (int) song.playlistTracks.size())
  270. return trackicons::Icon::none;
  271. if (const auto own = trackicons::iconFor (song.playlistTracks[(std::size_t) track].icon); own != trackicons::Icon::none)
  272. return own;
  273. if (const auto kind = simpletracks::kindOf (song, track))
  274. return simpletracks::iconOf (*kind);
  275. // round 190oj (CS-25): a track of an FL project has no Simple kind: the icon of what its clips are (notes, audio,
  276. // automation; mixed: layers of steps), so every header keeps its icon and the names stay in one line
  277. bool pattern = false, audio = false, automation = false;
  278. for (const auto& c : song.playlist)
  279. if (c.track == track)
  280. {
  281. pattern = pattern || c.kind == ClipKind::pattern;
  282. audio = audio || c.kind == ClipKind::audio;
  283. automation = automation || c.kind == ClipKind::automation;
  284. }
  285. const auto kinds = (int) pattern + (int) audio + (int) automation;
  286. if (kinds == 0)
  287. return trackicons::Icon::none;
  288. if (kinds > 1)
  289. return trackicons::Icon::steps;
  290. return pattern ? trackicons::Icon::notes : audio ? trackicons::Icon::audio : trackicons::Icon::automation;
  291. }
  292. // A Playlist track's colour (transparent: none set)
  293. juce::Colour trackColourIn (const Song& song, int track)
  294. {
  295. return track >= 0 && track < (int) song.playlistTracks.size() ? juce::Colour (song.playlistTracks[(std::size_t) track].colour) : juce::Colour();
  296. }
  297. // A clip's rectangle in its row (x1 = the clip's end): FL fills the row down to its separator line; LYNX's look leaves a
  298. // pixel above and two below.
  299. juce::Rectangle<float> clipRectAt (float x0, float x1, float y, int trackHeight)
  300. {
  301. // round 190jn (CL-17): Live fills its 17 px lane above the 2 px separator; clips meet edge to edge (the next one's rim
  302. // shows where they meet: live-arrangement.png x 580, y 242..258)
  303. if (theme::livelook::active())
  304. return { x0, y, juce::jmax (3.0f, x1 - x0), (float) trackHeight - 2.0f };
  305. if (flClipLook())
  306. return { x0, y, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) trackHeight - 1.0f };
  307. return { x0, y + 1.0f, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) trackHeight - 3.0f };
  308. }
  309. // an audio clip's gain as FL's gain handle shows it (round 166e): "-INF" at the bottom of the range
  310. juce::String gainText (float gain)
  311. {
  312. const auto db = clipops::clipGainToDb (gain);
  313. return db <= clipops::clipGainMinDb + 1.0e-6 ? juce::String ("-INF dB") : juce::String (db, 1) + " dB";
  314. }
  315. // The kind glyph at the header's left (the clip menu opens from it): LYNX's own small shapes.
  316. void paintClipGlyph (juce::Graphics& g, juce::Rectangle<float> box, ClipGlyph glyph, juce::Colour colour)
  317. {
  318. g.setColour (colour);
  319. const auto c = box.getCentre();
  320. switch (glyph)
  321. {
  322. case ClipGlyph::pattern: // three note bars, stepped
  323. for (int i = 0; i < 3; ++i)
  324. g.fillRect (juce::Rectangle<float> (c.x - 4.0f + (float) i * 2.0f, c.y - 3.5f + (float) i * 3.0f, 5.0f, 1.5f));
  325. break;
  326. case ClipGlyph::audio: // a small mirrored waveform
  327. {
  328. const float heights[] = { 2.0f, 6.0f, 9.0f, 5.0f, 3.0f };
  329. for (int i = 0; i < 5; ++i)
  330. g.fillRect (juce::Rectangle<float> (c.x - 4.5f + (float) i * 2.0f, c.y - heights[i] * 0.5f, 1.2f, heights[i]));
  331. break;
  332. }
  333. case ClipGlyph::automation: // a rising curve
  334. {
  335. juce::Path p;
  336. p.startNewSubPath (c.x - 4.5f, c.y + 3.5f);
  337. p.quadraticTo (c.x + 1.0f, c.y + 3.5f, c.x + 4.5f, c.y - 3.5f);
  338. g.strokePath (p, juce::PathStrokeType (1.3f));
  339. break;
  340. }
  341. }
  342. }
  343. // FL's header glyphs (round 190ig, measured at 1:1 in fl-playlist-zoom-audioclips.png): an audio clip's bar with an arrow
  344. // leaving it ("|->", 8 x 7 px), an automation clip's two nodes joined by a rising line (10 x 9 px). LYNX's own vectors.
  345. void paintFlClipGlyph (juce::Graphics& g, juce::Rectangle<float> box, ClipGlyph glyph, juce::Colour colour)
  346. {
  347. g.setColour (colour);
  348. const auto x = box.getX(), cy = box.getCentreY();
  349. if (glyph == ClipGlyph::audio)
  350. {
  351. g.fillRect (juce::Rectangle<float> (x, cy - 3.5f, 1.2f, 7.0f)); // the bar
  352. g.fillRect (juce::Rectangle<float> (x, cy - 0.6f, 6.0f, 1.2f)); // the shaft
  353. juce::Path head;
  354. head.addTriangle (x + 4.5f, cy - 2.6f, x + 8.0f, cy, x + 4.5f, cy + 2.6f);
  355. g.fillPath (head);
  356. }
  357. else if (glyph == ClipGlyph::automation)
  358. {
  359. g.drawEllipse (juce::Rectangle<float> (x + 0.5f, cy + 0.5f, 3.2f, 3.2f), 1.0f);
  360. g.drawEllipse (juce::Rectangle<float> (x + 6.3f, cy - 3.7f, 3.2f, 3.2f), 1.0f);
  361. g.drawLine (x + 3.2f, cy + 1.2f, x + 6.8f, cy - 1.4f, 1.0f);
  362. }
  363. else
  364. paintClipGlyph (g, box, glyph, colour);
  365. }
  366. // The FL frame: the header band (or, on a short track, the whole clip as one band), the body at its alpha and the rim.
  367. // Returns where the content goes: the body under the header, or the whole band (FL draws the waveform behind the name).
  368. juce::Rectangle<float> paintFlClipFrame (juce::Graphics& g, juce::Rectangle<float> r, const theme::ClipLook& look, bool band)
  369. {
  370. const uitrace::Part tally (uitrace::part::frame);
  371. const auto title = band ? r : r.withHeight (flHeaderHeight (r));
  372. if (! band)
  373. {
  374. g.setColour (look.body.withMultipliedAlpha (look.bodyAlpha));
  375. g.fillRect (r.withTrimmedTop (title.getHeight()));
  376. }
  377. // the header gradient as three flat bands (round 151: a gradient brush per clip costs a GPU geometry each)
  378. g.setColour (look.headerTop.interpolatedWith (look.headerBottom, 0.5f));
  379. g.fillRect (title);
  380. if (title.getHeight() >= 6.0f && r.getWidth() >= 8.0f)
  381. {
  382. const auto third = title.getHeight() / 3.0f;
  383. g.setColour (look.headerTop);
  384. g.fillRect (title.withHeight (third));
  385. g.setColour (look.headerBottom);
  386. g.fillRect (title.withTrimmedTop (2.0f * third));
  387. }
  388. if (r.getWidth() >= 3.0f && title.getHeight() >= 4.0f)
  389. {
  390. g.setColour (look.edge); // the rim: top, bottom, and the right edge that keeps neighbours apart
  391. g.fillRect (title.withHeight (1.0f));
  392. g.fillRect (title.withTop (title.getBottom() - 1.0f));
  393. g.fillRect (title.withLeft (title.getRight() - 1.0f));
  394. if (! band)
  395. {
  396. g.setColour (look.edge.withAlpha (0.6f));
  397. g.fillRect (r.withTrimmedTop (title.getHeight()).withLeft (r.getRight() - 1.0f));
  398. }
  399. }
  400. return band ? r.reduced (0.0f, 1.0f) : r.withTrimmedTop (title.getHeight());
  401. }
  402. // Round 190qe (D2-PL2, FL's Playlist ▸ View ▸ "Keep labels on screen", on by default): while the Playlist paints its
  403. // clips, the arrangement's left edge when the option is on (else far left): a clip that starts left of it and reaches
  404. // past it leaves its title to the held pass (PlaylistComponent::paintStickyTitles), which draws it at that edge
  405. static float heldTitleLeft = -1.0e9f;
  406. // LYNX_KEEP_LABELS_ALL=0 (diagnostics, A/B with one build): only what round 190ig held (the Pattern layout's audio and
  407. // automation clips), for the paint gate's measure of what this round adds
  408. static bool heldEveryClip()
  409. {
  410. static const bool all = [] { const auto* v = std::getenv ("LYNX_KEEP_LABELS_ALL"); return v == nullptr || juce::String (v) != "0"; }();
  411. return all;
  412. }
  413. void paintClipFrameTitle (juce::Graphics& g, juce::Rectangle<float> title, float width, juce::Colour header, const juce::String& name, ClipGlyph glyph,
  414. bool muted, const theme::ClipLook* look);
  415. // The FL header's glyph and name, drawn after the content: the glyph from 16 px wide, the name from 34 px with FL's middle
  416. // ellipsis (FM-27, FM-14: FL keeps both on narrow clips). A muted clip leaves the glyph's place to its X (paintMutedVeil).
  417. void paintFlClipTitle (juce::Graphics& g, juce::Rectangle<float> r, const theme::ClipLook& look, const juce::String& name, ClipGlyph glyph,
  418. bool muted, bool band, float viewLeft, bool sticky)
  419. {
  420. using namespace theme;
  421. if (r.getX() < viewLeft && r.getRight() > viewLeft) // (FL: the title stays in view, at the left edge)
  422. {
  423. if (! sticky || muted) // (held titles are drawn last, PlaylistComponent::paintStickyTitles; a muted clip keeps
  424. return; // its veil: no title held in view)
  425. r = r.withLeft (juce::jmin (viewLeft, r.getRight() - 1.0f));
  426. }
  427. const auto title = band ? r : r.withHeight (flHeaderHeight (r));
  428. const auto nameLine = title.withHeight (juce::jmin (title.getHeight(), 15.0f)).reduced (0.0f, 1.0f);
  429. if (r.getWidth() < 16.0f || nameLine.getHeight() < 9.0f)
  430. return;
  431. auto text = nameLine.withTrimmedLeft (3.0f).withTrimmedRight (2.0f);
  432. const auto glyphBox = text.removeFromLeft (11.0f);
  433. if (! muted)
  434. paintFlClipGlyph (g, glyphBox, glyph, look.ink);
  435. if (r.getWidth() < 34.0f)
  436. return;
  437. const uitrace::Part tallyTitle (uitrace::part::title);
  438. const auto f = font (type::caption, true);
  439. g.setColour (look.ink);
  440. g.setFont (f);
  441. const auto box = text.withTrimmedLeft (2.0f);
  442. textcache::drawText (g, theme::fitMiddle (name, f, box.getWidth()), box.toNearestInt(), juce::Justification::centredLeft, false);
  443. }
  444. // The header's glyph place. A muted clip shows its X there, as FL Studio does, however narrow the clip (round 177c).
  445. juce::Rectangle<float> clipGlyphBox (juce::Rectangle<float> title)
  446. {
  447. return title.withTrimmedLeft (3.0f).withTrimmedRight (2.0f).withWidth (juce::jmin (13.0f, title.getWidth() - 5.0f));
  448. }
  449. constexpr float mutedMarkMinWidth = 14.0f;
  450. // Clip body with the header bar, glyph and name; returns the body below the header. A muted clip leaves the glyph's place
  451. // empty for the X its veil draws on top (paintMutedVeil).
  452. // `look` (round 190jc, the Simple layout's BandLab colours, theme::clipBody bandlabHue): its header, body and ink instead of
  453. // the tints of `base`.
  454. juce::Rectangle<float> paintClipFrame (juce::Graphics& g, juce::Rectangle<float> r, juce::Colour base, const juce::String& name,
  455. ClipGlyph glyph = ClipGlyph::pattern, bool muted = false, const theme::ClipLook* look = nullptr)
  456. {
  457. using namespace theme;
  458. const uitrace::Part tally (uitrace::part::frame);
  459. const auto title = r.withHeight (clipHeaderHeight (r));
  460. const auto bodyColour = look != nullptr ? look->body : clipBodyColour (base);
  461. const auto headerColour = look != nullptr ? look->headerTop : clipHeaderColour (base);
  462. // zoomed far out (a clip a few pixels wide, often a thousand of them on screen): plain rectangles, the same
  463. // colours. Rounded shapes and gradients cost a path each on the GPU renderer (round 151: 1 350 clips of
  464. // Thief's chopped vocals took 20-40 ms a frame), and at this size they look the same.
  465. if (r.getWidth() < 8.0f)
  466. {
  467. g.setColour (bodyColour);
  468. g.fillRect (r);
  469. if (title.getHeight() >= 4.0f)
  470. {
  471. g.setColour (headerColour);
  472. g.fillRect (title);
  473. }
  474. return r.withTrimmedTop (title.getHeight());
  475. }
  476. g.setColour (bodyColour);
  477. g.fillRoundedRectangle (r, radius::sm);
  478. if (title.getHeight() >= 4.0f)
  479. {
  480. // the header band: rounded top corners, square bottom; a lighter top half gives it the slight sheen of a
  481. // gradient (round 151: drawn with the renderer's rounded-rectangle and rectangle primitives, not a path and
  482. // a gradient brush, which cost a GPU geometry each for every clip)
  483. const auto header = headerColour;
  484. g.setColour (header);
  485. g.fillRoundedRectangle (title, radius::sm);
  486. g.fillRect (title.withTrimmedTop (juce::jmin (radius::sm, title.getHeight() * 0.5f)));
  487. g.setColour (header.brighter (0.06f));
  488. g.fillRect (title.reduced (juce::jmin (radius::sm, title.getWidth() * 0.5f), 0.0f).withHeight (title.getHeight() * 0.45f).withTrimmedTop (1.0f));
  489. g.setColour (theme::colour::bg0.withAlpha (0.35f)); // the header's lower edge
  490. g.fillRect (title.getX(), title.getBottom() - 1.0f, title.getWidth(), 1.0f);
  491. // (round 190qe, "Keep labels on screen": a clip whose start is scrolled off gets its title in the held pass,
  492. // PlaylistComponent::paintStickyTitles, at the view's left edge)
  493. if (! (r.getX() < heldTitleLeft && r.getRight() > heldTitleLeft) || muted || ! heldEveryClip())
  494. paintClipFrameTitle (g, title, r.getWidth(), header, name, glyph, muted, look);
  495. }
  496. return r.withTrimmedTop (title.getHeight());
  497. }
  498. // paintClipFrame's glyph and name in the header band `title` of a clip `width` px wide (round 190qe: also a held title)
  499. void paintClipFrameTitle (juce::Graphics& g, juce::Rectangle<float> title, float width, juce::Colour header, const juce::String& name, ClipGlyph glyph,
  500. bool muted, const theme::ClipLook* look)
  501. {
  502. using namespace theme;
  503. if (width > 18.0f && title.getHeight() >= 9.0f)
  504. {
  505. auto text = title.withTrimmedLeft (3.0f).withTrimmedRight (2.0f);
  506. if (muted)
  507. text.removeFromLeft (13.0f);
  508. else if (width >= 40.0f) // room for the glyph (where the clip menu opens)
  509. paintClipGlyph (g, text.removeFromLeft (13.0f), glyph, (look != nullptr ? look->ink : clipTitleText (header)).withMultipliedAlpha (0.8f));
  510. const uitrace::Part tallyTitle (uitrace::part::title);
  511. g.setColour (look != nullptr ? look->ink : clipTitleText (header));
  512. g.setFont (font (type::caption, true));
  513. textcache::drawText (g, name, text.withTrimmedLeft (2.0f).toNearestInt(), juce::Justification::centredLeft, true);
  514. }
  515. }
  516. // A muted clip, as in FL Studio: the whole clip dims, its waveform or notes still readable, and an X takes the glyph's place.
  517. // `lit`: the parts of a take lane's clip its comp plays (round 177c): those stay undimmed, as in Ableton Live's lanes.
  518. void paintMutedVeil (juce::Graphics& g, juce::Rectangle<float> r, const std::vector<juce::Rectangle<float>>& lit = {})
  519. {
  520. using namespace theme;
  521. {
  522. const juce::Graphics::ScopedSaveState keep (g);
  523. for (const auto& part : lit)
  524. g.excludeClipRegion (part.getSmallestIntegerContainer());
  525. g.setColour (colour::bg1.withAlpha (0.55f));
  526. g.fillRoundedRectangle (r, radius::sm);
  527. }
  528. for (const auto& part : lit)
  529. {
  530. g.setColour (colour::accent);
  531. g.fillRect (part.withTop (part.getBottom() - 2.0f));
  532. }
  533. const auto title = r.withHeight (clipHeaderHeight (r));
  534. if (r.getWidth() < mutedMarkMinWidth || title.getHeight() < 9.0f)
  535. return;
  536. const auto c = clipGlyphBox (title).getCentre();
  537. const auto arm = juce::jmin (3.5f, title.getHeight() * 0.5f - 1.0f);
  538. g.setColour (colour::textSecondary); // a little above the dimmed name, as FL's X is, not the brightest thing on the clip
  539. g.drawLine (c.x - arm, c.y - arm, c.x + arm, c.y + arm, 1.4f);
  540. g.drawLine (c.x - arm, c.y + arm, c.x + arm, c.y - arm, 1.4f);
  541. }
  542. void paintClipOutline (juce::Graphics& g, juce::Rectangle<float> r, juce::Colour base, bool selected, bool current)
  543. {
  544. using namespace theme;
  545. const uitrace::Part tally (uitrace::part::outline);
  546. if (r.getWidth() < 8.0f && ! selected) // tiny clip (see paintClipFrame): a dark right edge keeps neighbours apart
  547. {
  548. g.setColour (current ? colour::textPrimary.withAlpha (0.55f) : colour::bg0.withAlpha (0.85f));
  549. g.fillRect (r.getRight() - 1.0f, r.getY(), 1.0f, r.getHeight());
  550. return;
  551. }
  552. if (selected)
  553. {
  554. g.setColour (colour::selection);
  555. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, 2.0f);
  556. }
  557. else
  558. {
  559. g.setColour (current ? colour::textPrimary.withAlpha (0.55f) : colour::bg0.withAlpha (0.85f));
  560. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, current ? 1.2f : 1.0f);
  561. }
  562. }
  563. } // namespace
  564. #include "SectionsLane190ol.inc" // round 190ol (research190oe P1): the Sections lane
  565. #include "ChordLane190pf.inc" // round 190pf (research190oe P13): the Chord lane
  566. // Zoomed far out, a song of chopped audio shows a thousand clips a few pixels wide. Painted one by one, each is a
  567. // handful of rounded paths (frame, header, waveform, outline), and the GPU renderer pays per path: Thief's Playlist
  568. // took 33-47 ms a frame to scroll (round 151). These clips are gathered here, rectangles per colour and waveforms per
  569. // colour as one path, and filled together after the other clips: a few calls a frame. At this size they look the
  570. // same as the full recipe.
  571. struct PlaylistComponent::SmallClips
  572. {
  573. static constexpr float maxWidth = 12.0f;
  574. std::map<juce::uint32, juce::RectangleList<float>> bodies, contents, edges;
  575. std::map<juce::uint32, juce::Path> waves;
  576. // round 190qm (PR #268): small clips of a switched-off track, under the muted-clip veil (too narrow for its X)
  577. juce::RectangleList<float> veils;
  578. void fill (juce::Graphics& g)
  579. {
  580. // (rectangle by rectangle: the GPU renderer turns a rectangle list into a geometry, which costs more)
  581. for (auto* layer : { &bodies, &contents })
  582. for (auto& [argb, list] : *layer)
  583. {
  584. g.setColour (juce::Colour (argb));
  585. for (const auto& r : list)
  586. g.fillRect (r);
  587. }
  588. const uitrace::Part tally (uitrace::part::batchWaves);
  589. for (auto& [argb, path] : waves)
  590. {
  591. g.setColour (juce::Colour (argb));
  592. g.fillPath (path);
  593. }
  594. for (auto& [argb, list] : edges)
  595. {
  596. g.setColour (juce::Colour (argb));
  597. for (const auto& r : list)
  598. g.fillRect (r);
  599. }
  600. if (! veils.isEmpty())
  601. {
  602. g.setColour (theme::colour::bg1.withAlpha (0.55f)); // (paintMutedVeil's veil)
  603. for (const auto& r : veils)
  604. g.fillRect (r);
  605. }
  606. }
  607. };
  608. // The Playlist's image cache (round 174e): JUCE's buffered-to-image cache, plus the playhead drawn over the image and
  609. // the playhead's own repaints leaving the image valid
  610. class PlaylistComponent::PlayheadCache final : public juce::CachedComponentImage
  611. {
  612. public:
  613. explicit PlayheadCache (PlaylistComponent& o) : owner (o) {}
  614. void paint (juce::Graphics& g) override
  615. {
  616. const auto scale = g.getInternalContext().getPhysicalPixelScaleFactor();
  617. const auto bounds = owner.getLocalBounds();
  618. const auto imageBounds = bounds * scale;
  619. const auto nowMs = juce::Time::getMillisecondCounterHiRes();
  620. const auto clip = g.getClipBounds();
  621. const auto lanes = owner.gridArea();
  622. // (round 190bm) a window drawn without the GPU gets a software picture; a picture lost with its graphics
  623. // device is painted again; no picture at all (no size, no memory): straight to the window
  624. const auto software = ui::windowDrawnByCpu (owner);
  625. const auto losses = ui::pictureLossCount();
  626. if (image.isNull() || image.getBounds() != imageBounds || software != softwareImage || losses != lossesSeen)
  627. {
  628. if (image.isNull() || image.getBounds() != imageBounds || software != softwareImage)
  629. image = ui::makePicture (imageBounds.getWidth(), imageBounds.getHeight(), software);
  630. softwareImage = software;
  631. lossesSeen = losses;
  632. spare = {};
  633. valid.clear();
  634. }
  635. ui::notePicture ("Playlist", image, scale, softwareImage, owner, noted);
  636. if (image.isNull())
  637. {
  638. drawnView = owner.cacheView();
  639. owner.paintEntireComponent (g, false);
  640. return;
  641. }
  642. // a zoom gesture left scaled lanes in the picture (round 174f): once it is over they are painted exactly
  643. if (lanesScaled && ! owner.zoomGesture)
  644. valid.subtract (lanes);
  645. // the view moved since the picture was drawn. A scroll by whole pixels (round 174e2): the picture is shifted
  646. // and only the columns / rows it uncovered are painted (FL scrolls at ~120 fps). A step of a zoom gesture
  647. // (Ctrl+wheel, round 174f): the lanes are scaled to the new zoom around the same ticks and only the columns a
  648. // zoom out uncovers are painted (a whole repaint of the lanes costs 15-30 ms on a large project); exact once
  649. // the gesture is over. Anything else (a track resize, both directions at once, the corner tags): everything
  650. // is painted again.
  651. const auto view = owner.cacheView();
  652. CacheShift shift;
  653. Zoom zoom;
  654. if (view != drawnView)
  655. {
  656. shift = owner.cacheShift (drawnView, view, scale);
  657. if (shift.area.isEmpty())
  658. zoom = zoomFrom (drawnView, view, lanes);
  659. if (shift.area.isEmpty() && ! zoom.on)
  660. valid.clear();
  661. }
  662. auto validNow = valid;
  663. if (! shift.area.isEmpty())
  664. {
  665. juce::RectangleList<int> moved;
  666. for (const auto& r : valid)
  667. if (const auto in = r.getIntersection (shift.area); ! in.isEmpty())
  668. moved.addWithoutMerging (in.translated (shift.dx, shift.dy).getIntersection (shift.area));
  669. validNow.subtract (shift.area);
  670. validNow.subtract (shift.alsoChanged);
  671. validNow.add (moved);
  672. validNow.subtract (shift.stickyTitles);
  673. }
  674. if (zoom.on)
  675. {
  676. const auto whole = valid.containsRectangle (lanes);
  677. validNow.subtract (lanes);
  678. validNow.subtract (owner.rulerArea()); // (the ruler follows the zoom: painted exactly)
  679. if (whole)
  680. validNow.add (zoom.covered);
  681. }
  682. // a repaint of (almost) everything (an edit): painted straight to the window (through the picture it costs a
  683. // render and a full blit); the picture is rebuilt once the view has been still for a moment, by the next
  684. // playhead frame. Not a scroll or a zoom: they go through the picture, so the next frame can shift or scale it
  685. // (painted straight, every scroll frame found the picture gone and painted everything again)
  686. auto invalid = juce::RectangleList<int> (bounds);
  687. invalid.subtract (validNow);
  688. const auto half = 0.5 * bounds.getWidth() * bounds.getHeight();
  689. if ((double) clip.getWidth() * clip.getHeight() > half && area (invalid) > half)
  690. lastLargeMs = nowMs;
  691. if (nowMs - lastLargeMs < 300.0 && shift.area.isEmpty() && ! zoom.on && ! validNow.containsRectangle (clip) && ! owner.zoomRecent (nowMs))
  692. {
  693. if (view != drawnView)
  694. {
  695. valid.clear(); // (the picture is of another view now; later invalidations are in this one's coordinates)
  696. drawnView = view;
  697. }
  698. owner.paintEntireComponent (g, false);
  699. return;
  700. }
  701. const auto moving = ! shift.area.isEmpty() || zoom.on;
  702. if (moving || ! invalid.isEmpty())
  703. {
  704. if (moving && (spare.isNull() || spare.getBounds() != image.getBounds()))
  705. {
  706. spare = ui::makePicture (image.getWidth(), image.getHeight(), softwareImage);
  707. if (spare.isNull()) // (no memory for the second picture: this frame straight to the window)
  708. {
  709. valid.clear();
  710. drawnView = view;
  711. owner.paintEntireComponent (g, false);
  712. return;
  713. }
  714. }
  715. auto& target = moving ? spare : image;
  716. const ui::ScopedNoImageReadback noReadback (target); // (the picture is normally only drawn to the window)
  717. juce::Graphics imageGraphics (target);
  718. if (moving)
  719. {
  720. // the whole picture, then the moving area over it, shifted or scaled: plain rectangular clips (the
  721. // picture with a hole cut out is a clip region the GPU renderer masks with a layer; round 174f)
  722. imageGraphics.drawImageAt (image, 0, 0);
  723. const juce::Graphics::ScopedSaveState state (imageGraphics);
  724. if (! shift.area.isEmpty())
  725. {
  726. if (imageGraphics.reduceClipRegion ((shift.area.toFloat() * scale).getSmallestIntegerContainer()))
  727. imageGraphics.drawImageAt (image, juce::roundToInt ((float) shift.dx * scale), juce::roundToInt ((float) shift.dy * scale));
  728. }
  729. else if (! zoom.covered.isEmpty() && imageGraphics.reduceClipRegion ((zoom.covered.toFloat() * scale).getSmallestIntegerContainer()))
  730. {
  731. imageGraphics.setImageResamplingQuality (juce::Graphics::mediumResamplingQuality);
  732. imageGraphics.drawImageTransformed (image, juce::AffineTransform ((float) zoom.a, 0.0f, (float) zoom.b * scale, 0.0f, 1.0f, 0.0f), false);
  733. }
  734. }
  735. if (! shift.heldBands.empty()) // (round 190im: the held titles' bands, each by its own clip)
  736. {
  737. const juce::Graphics::ScopedSaveState bands (imageGraphics);
  738. imageGraphics.addTransform (juce::AffineTransform::scale (scale));
  739. for (const auto& [index, band] : shift.heldBands)
  740. {
  741. const juce::Graphics::ScopedSaveState one (imageGraphics);
  742. if (imageGraphics.reduceClipRegion (band))
  743. owner.paintHeldClip (imageGraphics, index);
  744. }
  745. }
  746. if (! invalid.isEmpty())
  747. {
  748. imageGraphics.addTransform (juce::AffineTransform::scale (scale));
  749. paintExactly (imageGraphics, invalid, validNow); // (the picture without the playhead: drawn over it below)
  750. }
  751. }
  752. if (moving)
  753. std::swap (image, spare);
  754. if (zoom.on)
  755. {
  756. lanesScaled = true;
  757. ++scaledSteps;
  758. }
  759. else if (! moving && ! validNow.intersectsRectangle (lanes))
  760. {
  761. lanesScaled = false; // (the lanes were all painted exactly)
  762. scaledSteps = 0;
  763. }
  764. valid = bounds;
  765. drawnView = view;
  766. g.setColour (juce::Colours::black);
  767. g.drawImageTransformed (image,
  768. juce::AffineTransform::scale ((float) bounds.getWidth() / (float) imageBounds.getWidth(),
  769. (float) bounds.getHeight() / (float) imageBounds.getHeight()),
  770. false);
  771. owner.paintTrackSelectionDim (g); // (over the picture: the selection changes without the lanes being painted again)
  772. owner.paintMutedTracks (g); // (over the picture: a mute changes without the lanes being painted again)
  773. owner.paintStickyTitles (g);
  774. if (! owner.gpuPlayhead.isShowing()) // (round 190ip: the GPU moves it while playing)
  775. owner.paintPlayhead (g);
  776. if (ui::pictureLostMeanwhile (lossesSeen, lossRetries))
  777. owner.repaint();
  778. }
  779. bool invalidateAll() override // (JUCE's repaint() of the whole component comes here, not to invalidate())
  780. {
  781. if (! owner.playheadRepaintOnly && ! owner.scrollRepaintOnly)
  782. valid.clear();
  783. return true;
  784. }
  785. bool invalidate (const juce::Rectangle<int>& r) override
  786. {
  787. if (! owner.playheadRepaintOnly && ! owner.scrollRepaintOnly)
  788. valid.subtract (r);
  789. return true; // (the window repaints the area either way)
  790. }
  791. void releaseResources() override // (the Playlist was hidden: its pictures are freed)
  792. {
  793. image = {};
  794. spare = {};
  795. valid.clear();
  796. }
  797. // --cachetest: the picture's size in bytes (both images); whether its lanes are scaled (a zoom gesture)
  798. std::size_t memoryBytes() const
  799. {
  800. const auto bytes = [] (const juce::Image& i) { return i.isNull() ? (std::size_t) 0 : (std::size_t) i.getWidth() * (std::size_t) i.getHeight() * 4u; };
  801. return bytes (image) + bytes (spare);
  802. }
  803. bool hasScaledLanes() const { return lanesScaled; }
  804. private:
  805. // (each step resamples the last: after 2 (a stretch of at most 1.44x from the last exact picture, at Ctrl+wheel's
  806. // 1.2 per notch) the lanes are painted exactly; round 174f, chosen by eye: 8 steps stretched names up to 4x)
  807. static constexpr int maxScaledSteps = 2;
  808. // A zoom step: column x of the picture (drawn at `from`) shows the same tick at a x + b in `to`
  809. struct Zoom
  810. {
  811. bool on = false;
  812. double a = 1.0, b = 0.0;
  813. juce::Rectangle<int> covered; // the part of the lanes the scaled picture fills
  814. };
  815. Zoom zoomFrom (const CacheView& from, const CacheView& to, juce::Rectangle<int> lanes) const
  816. {
  817. Zoom z;
  818. if (! owner.zoomGesture || owner.blocksShown || image.isNull() || from.pixelsPerTick <= 0.0 || scaledSteps >= maxScaledSteps
  819. || from.scrollY != to.scrollY || from.tracksHeight != to.tracksHeight || from.tracks != to.tracks || from.overlays || to.overlays
  820. || from.width != to.width || from.height != to.height || lanes.isEmpty())
  821. return z;
  822. z.a = to.pixelsPerTick / from.pixelsPerTick;
  823. if (z.a < 0.5 || z.a > 2.0)
  824. return z;
  825. // tickToX: x = headerWidth + (tick - scrollTicks) * pixelsPerTick
  826. z.b = owner.headerWidth + (from.scrollTicks - to.scrollTicks) * to.pixelsPerTick - owner.headerWidth * z.a;
  827. const auto left = z.a * lanes.getX() + z.b, right = z.a * lanes.getRight() + z.b;
  828. z.covered = lanes.getIntersection (juce::Rectangle<int>::leftTopRightBottom ((int) std::ceil (left), lanes.getY(), (int) std::floor (right),
  829. lanes.getBottom()));
  830. z.on = true;
  831. return z;
  832. }
  833. // Paints `area` of the component as paint() does, without the playhead. A few rectangles (a scroll's strip, the
  834. // ruler, a hover): one plain rectangular clip each, which the GPU renderer clips for free and paint() culls by;
  835. // more: the area as one clip region (everything but `exceptFor`)
  836. void paintExactly (juce::Graphics& target, const juce::RectangleList<int>& area, const juce::RectangleList<int>& exceptFor)
  837. {
  838. const juce::ScopedValueSetter<bool> noPlayhead (owner.cachePainting, true);
  839. if (area.getNumRectangles() <= 4)
  840. {
  841. for (const auto& r : area)
  842. {
  843. const juce::Graphics::ScopedSaveState state (target);
  844. if (target.reduceClipRegion (r))
  845. owner.paintEntireComponent (target, true);
  846. }
  847. return;
  848. }
  849. const juce::Graphics::ScopedSaveState state (target);
  850. for (const auto& r : exceptFor)
  851. target.excludeClipRegion (r);
  852. owner.paintEntireComponent (target, true);
  853. }
  854. static double area (const juce::RectangleList<int>& list)
  855. {
  856. double a = 0.0;
  857. for (const auto& r : list)
  858. a += (double) r.getWidth() * r.getHeight();
  859. return a;
  860. }
  861. PlaylistComponent& owner;
  862. juce::Image image, spare; // spare: the shifted / scaled copy is drawn into it, then they swap
  863. juce::RectangleList<int> valid;
  864. CacheView drawnView;
  865. bool lanesScaled = false; // the lanes are a zoom gesture's scaled picture
  866. int scaledSteps = 0;
  867. double lastLargeMs = 0.0;
  868. bool softwareImage = false; // the pictures are software images (the window is drawn without the GPU)
  869. int lossesSeen = 0; // ui::pictureLossCount() when the picture was last known good
  870. int lossRetries = 0;
  871. juce::String noted; // ui::notePicture's memory
  872. };
  873. // What the cached picture depends on beyond what repaints say (round 174e2)
  874. PlaylistComponent::CacheView PlaylistComponent::cacheView() const
  875. {
  876. return { scrollTicks, scrollY, pixelsPerTick, trackTops.empty() ? 0 : trackTops.back(), (int) trackTops.size(),
  877. ripple || engine.getSong().performanceMode, getWidth(), getHeight() };
  878. }
  879. // The picture of view `from` shown as `to` by shifting it: the area that moves and by how much (whole physical pixels).
  880. // Horizontal: the ruler and the lanes (the headers stay); vertical: the headers and the lanes (the ruler stays).
  881. // Empty area: not a plain scroll (zoom, resize, track heights, both directions at once, the corner tags).
  882. PlaylistComponent::CacheShift PlaylistComponent::cacheShift (const CacheView& from, const CacheView& to, float scale) const
  883. {
  884. if (from.pixelsPerTick != to.pixelsPerTick || from.tracksHeight != to.tracksHeight || from.tracks != to.tracks
  885. || from.overlays || to.overlays || from.width != to.width || from.height != to.height)
  886. return {};
  887. const auto grid = gridArea();
  888. const auto dxExact = (from.scrollTicks - to.scrollTicks) * to.pixelsPerTick;
  889. const auto dx = (int) std::lround (dxExact), dy = from.scrollY - to.scrollY;
  890. const auto whole = [scale] (int d) { return std::abs ((float) d * scale - (float) juce::roundToInt ((float) d * scale)) < 0.01f; };
  891. if (std::abs (dxExact - dx) > 0.01 || (dx != 0 && dy != 0) || ! whole (dx) || ! whole (dy))
  892. return {};
  893. CacheShift shift;
  894. if (dx != 0)
  895. {
  896. shift.area = { headerWidth, rulerTop, grid.getRight() - headerWidth, grid.getBottom() - rulerTop };
  897. shift.alsoChanged = { headerWidth, grid.getBottom(), grid.getWidth(), getHeight() - grid.getBottom() }; // (the pattern blocks)
  898. // round 190ig: FL's titles held at the left edge; only their header bands are painted again (round 190qe: FL's
  899. // "Keep labels on screen", every layout and clip kind, while the option is on)
  900. if (keeplabels::on)
  901. {
  902. const auto& song = engine.getSong();
  903. const auto left = (float) grid.getX();
  904. const auto fl = flClipLook();
  905. const auto titleFont = theme::font (theme::type::caption, true);
  906. juce::Rectangle<int> titles;
  907. for (const auto& c : song.playlist)
  908. {
  909. if (shownMuted (song, c) || c.track < 0 || (! heldEveryClip() && (! fl || c.kind == ClipKind::pattern)))
  910. continue;
  911. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  912. if (((x0 < left) == (x0 - (float) dx < left)) || x1 - x0 < 16.0f) // (only a start that crosses the edge now)
  913. continue;
  914. const auto y = trackToY (c.track), h = heightOf (c.track);
  915. if (y > grid.getBottom() || y + h < grid.getY() || juce::jmax (x1, x1 - (float) dx) <= left || noteedit::isFoldedAway (song, c.track))
  916. continue;
  917. const auto* name = c.kind == ClipKind::audio ? (c.channel >= 0 && c.channel < (int) song.channels.size() ? &song.channels[(std::size_t) c.channel].name : nullptr)
  918. : c.kind == ClipKind::automation ? (c.automation >= 0 && c.automation < (int) song.automations.size() ? &song.automations[(std::size_t) c.automation].name : nullptr)
  919. : (c.pattern >= 0 && c.pattern < (int) song.patterns.size() ? &song.patterns[(std::size_t) c.pattern].name : nullptr);
  920. if (name == nullptr)
  921. continue;
  922. // (the picture holds a clip's title only while its start is in view; a start that crosses the edge in this step
  923. // leaves a cut title, or lacks one, in the shifted picture)
  924. const auto xOld = x0 - (float) dx;
  925. if ((x0 < left) == (xOld < left) || x1 - x0 < 16.0f) // (a clip under 16 px wide shows no title)
  926. continue;
  927. const auto reach = 22.0f + (float) std::abs (dx) + juce::GlyphArrangement::getStringWidth (titleFont, juce::String::fromUTF8 (name->c_str()));
  928. const auto r = clipRectAt (x0, x1, (float) y, h);
  929. const auto bandHeight = ! fl ? (liveArrangeLook() ? juce::jmin (r.getHeight(), (float) liveStripHeight) : clipHeaderHeight (r))
  930. : r.getHeight() + 1.0f < (float) flBandBelow ? juce::jmin (r.getHeight(), 15.0f)
  931. : flHeaderHeight (r);
  932. const auto bandArea = juce::Rectangle<float> (left, r.getY(), reach, bandHeight).getSmallestIntegerContainer().getIntersection (grid);
  933. // round 190im (perf, the scroll frames where a start crosses the edge: 9.4 → 11.0 ms in round 190ig): the band
  934. // is the clip's own opaque header, so painting that one clip there gives the exact pixels, without a whole
  935. // paint pass for the union of the bands. Only when nothing else is drawn there: no other clip of the track
  936. // reaching the band, no hover / drag / rubber band / Performance / recording overlay
  937. const auto band = bandArea.getIntersection (r.withRight (juce::jmin (r.getRight(), x1)).getSmallestIntegerContainer());
  938. const auto& index = song.playlist;
  939. const auto i = (int) (&c - index.data());
  940. auto alone = fl && c.kind != ClipKind::pattern && ! band.isEmpty() && r.getWidth() >= SmallClips::maxWidth && drag == Drag::none && hover.clip != i && rubberBand.isEmpty()
  941. && song.performanceZoneEnd() <= 0 && ! engine.isLiveRecording();
  942. for (int k = 0; alone && k < (int) index.size(); ++k)
  943. if (const auto& o = index[(std::size_t) k]; k != i && o.track == c.track
  944. && tickToX ((double) o.start) < (double) band.getRight() && tickToX ((double) o.end()) > (double) band.getX())
  945. alone = false;
  946. if (alone)
  947. shift.heldBands.push_back ({ i, band });
  948. else
  949. titles = titles.getUnion (bandArea);
  950. }
  951. // (one rectangle: a few separate ones would make the picture's repaint a masked clip region, slower than this)
  952. if (! titles.isEmpty())
  953. shift.stickyTitles.add (titles);
  954. }
  955. }
  956. else // (#193, round 190nq: from the clip tracks' top, not the ruler's foot: the pinned video lanes between them stay put;
  957. // from headerHeight the picture slid them down with the tracks, and the rows at the bottom were never shifted)
  958. {
  959. static const bool fix193 = [] { const auto* v = std::getenv ("LYNX_FIX193"); return v == nullptr || juce::String (v) != "0"; }(); // (0: the old area, A/B)
  960. shift.area = { 0, fix193 ? grid.getY() : headerHeight, grid.getRight(), grid.getHeight() };
  961. }
  962. shift.dx = dx;
  963. shift.dy = dy;
  964. if (std::abs (dx) >= shift.area.getWidth() || std::abs (dy) >= shift.area.getHeight())
  965. return {};
  966. return shift;
  967. }
  968. // --cachetest (round 174f): the picture the cache shows against an exact paint of the same view, after the cases that
  969. // reuse it (a zoom gesture and its settle, scrolls by whole pixels, an edit). Off screen, at scale 1. Every exact case
  970. // must match to the pixel; the zoom gesture's frames are scaled (their difference is reported, the rest of the view
  971. // outside the lanes must match).
  972. juce::String PlaylistComponent::cacheSelfTest (const std::function<void()>& waitForWaveforms, const juce::File& dumpFolder)
  973. {
  974. auto* cache = dynamic_cast<PlayheadCache*> (getCachedComponentImage());
  975. if (cache == nullptr)
  976. return "cache: off (LYNX_PLAYLIST_CACHE=0)\nresult=SKIPPED\n";
  977. const auto w = getWidth(), h = getHeight();
  978. auto render = [w, h] (auto&& paintFn) {
  979. juce::Image im (juce::Image::RGB, w, h, true);
  980. {
  981. juce::Graphics g (im);
  982. paintFn (g);
  983. }
  984. return im;
  985. };
  986. auto exact = [&] { return render ([this] (juce::Graphics& g) { paintEntireComponent (g, true); }); };
  987. auto cached = [&] { return render ([cache] (juce::Graphics& g) { cache->paint (g); }); };
  988. struct Diff
  989. {
  990. int pixels = 0, worst = 0;
  991. juce::Rectangle<int> box;
  992. };
  993. auto diff = [] (const juce::Image& a, const juce::Image& b, juce::Rectangle<int> area, juce::Rectangle<int> except) {
  994. Diff d;
  995. const juce::Image::BitmapData pa (a, juce::Image::BitmapData::readOnly), pb (b, juce::Image::BitmapData::readOnly);
  996. for (int y = area.getY(); y < area.getBottom(); ++y)
  997. for (int x = area.getX(); x < area.getRight(); ++x)
  998. {
  999. if (except.contains (x, y))
  1000. continue;
  1001. const auto ca = pa.getPixelColour (x, y), cb = pb.getPixelColour (x, y);
  1002. const auto m = juce::jmax (std::abs ((int) ca.getRed() - (int) cb.getRed()), std::abs ((int) ca.getGreen() - (int) cb.getGreen()),
  1003. std::abs ((int) ca.getBlue() - (int) cb.getBlue()));
  1004. if (m > 0)
  1005. {
  1006. ++d.pixels;
  1007. d.box = d.box.isEmpty() ? juce::Rectangle<int> (x, y, 1, 1) : d.box.getUnion ({ x, y, 1, 1 });
  1008. }
  1009. d.worst = juce::jmax (d.worst, m);
  1010. }
  1011. return d;
  1012. };
  1013. juce::String out;
  1014. auto failures = 0;
  1015. auto dumpedScaled = false;
  1016. const auto all = getLocalBounds();
  1017. auto check = [&] (const juce::String& name, bool mustMatch, juce::Rectangle<int> except = {}) {
  1018. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1019. const auto viaCache = cached();
  1020. const auto cacheMs = juce::Time::getMillisecondCounterHiRes() - t0;
  1021. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  1022. const auto reference = exact();
  1023. const auto exactMs = juce::Time::getMillisecondCounterHiRes() - t1;
  1024. const auto d = diff (viaCache, reference, all, except);
  1025. // (one step of 255 is allowed: a view scrolled by a whole number of pixels puts shapes at positions that differ
  1026. // from the shifted ones by float rounding, ~1e-12 px, which can move an anti-aliased edge's coverage by one step)
  1027. const auto ok = d.worst <= 1;
  1028. failures += mustMatch && ! ok ? 1 : 0;
  1029. out << name << ": " << (mustMatch ? (ok ? (d.pixels == 0 ? "match" : "match (1-step rounding)") : "MISMATCH") : (d.pixels == 0 ? "match" : "scaled")) << ", " << d.pixels << " px differ (max "
  1030. << d.worst << (ok ? juce::String() : ", in " + d.box.toString()) << "), via cache " << juce::String (cacheMs, 2) << " ms, exact "
  1031. << juce::String (exactMs, 2) << " ms\n";
  1032. // (both pictures, to look at: a mismatch, and the first scaled zoom frame)
  1033. const auto dump = mustMatch ? ! ok : (d.pixels > 0 && ! dumpedScaled);
  1034. if (! mustMatch && dump)
  1035. dumpedScaled = true;
  1036. if (dump && dumpFolder != juce::File())
  1037. for (const auto& [suffix, im] : { std::pair<const char*, const juce::Image*> { "cache", &viaCache }, { "exact", &reference } })
  1038. {
  1039. juce::PNGImageFormat png;
  1040. juce::FileOutputStream stream (dumpFolder.getChildFile ("cachetest-" + (mustMatch ? juce::String (failures) : juce::String ("zoomframe")) + "-" + suffix + ".png"));
  1041. if (stream.openedOk())
  1042. {
  1043. stream.setPosition (0);
  1044. stream.truncate();
  1045. png.writeImageToStream (*im, stream);
  1046. }
  1047. }
  1048. };
  1049. // (the waveforms are analysed in the background: one paint asks for them, then they are waited for)
  1050. exact();
  1051. if (waitForWaveforms)
  1052. waitForWaveforms();
  1053. repaint();
  1054. check ("first picture", true);
  1055. check ("unchanged view (blit only)", true);
  1056. // a zoom gesture: four steps in, two out (scaled, the lanes only), then still
  1057. const auto anchor = (double) gridArea().getWidth() * 0.4;
  1058. auto zoomStep = [&] (double factor) {
  1059. const auto zoomed = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick * factor);
  1060. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchor);
  1061. pixelsPerTick = zoomed;
  1062. updateScrollBars();
  1063. repaintZoomed();
  1064. };
  1065. for (auto f : { 1.2, 1.2, 1.2, 1.0 / 1.2, 1.0 / 1.2 })
  1066. {
  1067. zoomStep (f);
  1068. check ("zoom step x" + juce::String (f, 3) + " (outside the lanes)", true, gridArea());
  1069. check ("zoom step x" + juce::String (f, 3) + " (lanes scaled)", false);
  1070. }
  1071. settleZoom();
  1072. check ("zoom settled", true);
  1073. // past 2x in one gesture: the lanes are painted again on the way
  1074. for (int i = 0; i < 6; ++i)
  1075. {
  1076. zoomStep (1.0 / 1.2);
  1077. check ("zoom out step " + juce::String (i + 1) + " (outside the lanes)", true, gridArea());
  1078. }
  1079. settleZoom();
  1080. check ("zoom out settled", true);
  1081. // a plain wheel moves the view up and down, wherever a zoom left it sideways: at 0, a whole pixel or between two
  1082. // pixels, the glide must not touch it (between two, it used to flip by a pixel's fraction every frame, and each
  1083. // frame painted everything). Then a sideways glide into the end of the song has to finish.
  1084. auto runGlide = [&] {
  1085. int moves = 0, frames = 0;
  1086. for (auto last = scrollTicks; gliding && frames < 400; ++frames)
  1087. {
  1088. glideFrame();
  1089. moves += scrollTicks != last ? 1 : 0;
  1090. last = scrollTicks;
  1091. }
  1092. return std::pair { moves, frames };
  1093. };
  1094. for (const auto pixels : { 0.0, 130.0, 130.8 })
  1095. {
  1096. gliding = false;
  1097. scrollTicks = pixels / pixelsPerTick;
  1098. updateScrollBars();
  1099. const auto before = scrollTicks;
  1100. glideBy (0.0, 2.0 * defaultRowHeight(), false);
  1101. const auto [moves, frames] = runGlide();
  1102. out << "wheel glide, view at " << juce::String (pixels, 1) << " px: " << moves << " sideways moves in " << frames << " frames\n";
  1103. if (moves != 0 || scrollTicks != before || gliding)
  1104. {
  1105. ++failures;
  1106. out << "FAIL wheel glide moved the view sideways\n";
  1107. }
  1108. }
  1109. gliding = false;
  1110. scrollY = 0;
  1111. glideBy (1.0e9, 0.0, false);
  1112. if (const auto [moves, frames] = runGlide(); gliding)
  1113. {
  1114. ++failures;
  1115. out << "FAIL sideways glide into the end did not finish: " << moves << " moves in " << frames << " frames\n";
  1116. }
  1117. gliding = false;
  1118. scrollTicks = 0.0;
  1119. updateScrollBars();
  1120. repaint();
  1121. check ("after the glides", true);
  1122. // scrolls by whole pixels (the picture shifted, the strip painted)
  1123. scrollTicks = juce::jmax (0.0, scrollTicks + 37.0 / pixelsPerTick);
  1124. updateScrollBars();
  1125. repaintScrolled();
  1126. check ("scroll right 37 px", true);
  1127. scrollTicks = juce::jmax (0.0, scrollTicks - 11.0 / pixelsPerTick);
  1128. updateScrollBars();
  1129. repaintScrolled();
  1130. check ("scroll left 11 px", true);
  1131. if (tracksHeight() > gridArea().getHeight() + 30)
  1132. {
  1133. scrollY += 23;
  1134. updateScrollBars();
  1135. repaintScrolled();
  1136. check ("scroll down 23 px", true);
  1137. }
  1138. // a partial repaint (a hover, an edit): its area painted again
  1139. repaint (gridArea().withSizeKeepingCentre (200, 80));
  1140. check ("partial repaint", true);
  1141. repaint();
  1142. check ("whole repaint", true);
  1143. out << "picture memory: " << juce::String ((double) cache->memoryBytes() / (1024.0 * 1024.0), 1) << " MB\n";
  1144. setVisible (false); // (JUCE releases the cached pictures of a hidden component)
  1145. out << "hidden: picture memory " << juce::String ((double) cache->memoryBytes() / (1024.0 * 1024.0), 1) << " MB\n";
  1146. setVisible (true);
  1147. out << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  1148. return out;
  1149. }
  1150. // A repaint after the view scrolled: the cached picture is shifted instead of painted again (round 174e2)
  1151. void PlaylistComponent::repaintScrolled()
  1152. {
  1153. scrollRepaintOnly = playheadOverlay;
  1154. repaint();
  1155. scrollRepaintOnly = false;
  1156. }
  1157. // A repaint after a step of a continuous zoom (Ctrl+wheel, the overview's ends, the zoom keys): the cache shows the
  1158. // lanes scaled from its picture until the zoom has been still for zoomSettleMs, then they are painted exactly (round 174f)
  1159. void PlaylistComponent::repaintZoomed()
  1160. {
  1161. static const bool scaled = [] { const auto* v = std::getenv ("LYNX_ZOOM_SCALE"); return v == nullptr || juce::String (v) != "0"; }(); // (0: A/B)
  1162. if (playheadOverlay && scaled)
  1163. {
  1164. zoomGesture = true;
  1165. zoomSettle.startTimer (zoomSettleMs);
  1166. }
  1167. repaintScrolled();
  1168. }
  1169. void PlaylistComponent::settleZoom()
  1170. {
  1171. zoomSettle.stopTimer();
  1172. if (! zoomGesture)
  1173. return;
  1174. zoomGesture = false;
  1175. zoomEndMs = juce::Time::getMillisecondCounterHiRes();
  1176. repaint (gridArea()); // (the lanes, exactly; the rest of the picture already is)
  1177. }
  1178. bool PlaylistComponent::zoomRecent (double nowMs) const
  1179. {
  1180. return zoomGesture || nowMs - zoomEndMs < 400.0;
  1181. }
  1182. juce::Rectangle<int> PlaylistComponent::rulerArea() const
  1183. {
  1184. return { headerWidth, rulerTop, gridArea().getWidth(), timelineHeight };
  1185. }
  1186. PlaylistComponent::PlaylistComponent (AudioEngine& e)
  1187. : engine (e)
  1188. {
  1189. // round 190jc (design190ia SG-18): the drop lane as a component the first-song tour can ring (transparent, no clicks)
  1190. dropLaneProbe.setComponentID ("simple.dropLane");
  1191. dropLaneProbe.setInterceptsMouseClicks (false, false);
  1192. addChildComponent (dropLaneProbe);
  1193. addAndMakeVisible (overviewGapBlock); // (transparent: the Playlist paints the band; a press there is no ruler or strip press)
  1194. addChildComponent (insertMarkLine); // round 190mk (DL-70)
  1195. setWantsKeyboardFocus (false);
  1196. setMouseClickGrabsKeyboardFocus (false);
  1197. for (auto* bar : { &hBar, &vBar })
  1198. {
  1199. bar->addListener (this);
  1200. bar->setAutoHide (false);
  1201. addAndMakeVisible (bar);
  1202. }
  1203. // the overview strip is the horizontal scroller (FL's Playlist has its preview bar on top)
  1204. hBar.setVisible (false);
  1205. overview.paintContent = [this] (juce::Graphics& g, juce::Rectangle<float> area, double total) { paintOverview (g, area, total); };
  1206. overview.onChange = [this] (double start, double length) {
  1207. const auto width = (double) gridArea().getWidth();
  1208. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, width / juce::jmax (1.0, length));
  1209. scrollTicks = juce::jmax (0.0, start);
  1210. updateScrollBars();
  1211. repaintZoomed(); // (dragging the overview's window or its ends: a continuous scroll / zoom)
  1212. };
  1213. overview.onShowAll = [this] { zoomAll(); };
  1214. addAndMakeVisible (overview);
  1215. // FL's legacy Pattern Blocks (round 170f): shown under the clip tracks while the project's option is on
  1216. blocksView = std::make_unique<PatternBlocksView> (engine, *this);
  1217. addChildComponent (*blocksView);
  1218. videoLanes = std::make_unique<VideoLanesView> (engine, *this);
  1219. addChildComponent (*videoLanes);
  1220. sectionsLane = std::make_unique<SectionsLaneView> (engine, *this); // round 190ol
  1221. addChildComponent (*sectionsLane);
  1222. chordLane = std::make_unique<ChordLaneView> (engine, *this); // round 190pf
  1223. addChildComponent (*chordLane);
  1224. grid::fillEditorBox (snapBox);
  1225. snapBox.setTooltip (tr ("Playlist snap (magnet): \"Main\" follows the snap in the toolbar, or pick this window's own; hold Alt while dragging to ignore it"));
  1226. ui::setQuickTip (snapBox, tr ("Playlist snap"));
  1227. snapBox.setWantsKeyboardFocus (false);
  1228. snapBox.setMouseClickGrabsKeyboardFocus (false);
  1229. snapBox.onChange = [this] { repaint(); };
  1230. addAndMakeVisible (snapBox);
  1231. tools.onChange = [this] (EditTool) { updateCursor (juce::ModifierKeys::currentModifiers); };
  1232. tools.onZoomMenu = [this] (juce::Component& button) { // (round 190mp, DE-74)
  1233. quickZoomMenu ("playlist.", [this] (const std::string& id) { return runAction (id); }, shortcutText,
  1234. engine.getSong().performanceZoneEnd() > 0)
  1235. .showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&button));
  1236. };
  1237. setOpaque (true); // paints every pixel: nothing behind it is redrawn while scrolling
  1238. if (const auto* v = std::getenv ("LYNX_PLAYLIST_CACHE"); v == nullptr || juce::String (v) != "0")
  1239. {
  1240. setCachedComponentImage (new PlayheadCache (*this)); // (owned by the component)
  1241. playheadOverlay = true;
  1242. }
  1243. gpuPlayhead.onHidden = [this] { repaintPlayheadColumn (playheadTick); }; // (round 190ip: painted again)
  1244. addAndMakeVisible (tools);
  1245. // Follow (FL: "Auto scrolling"): the view pages along with the playhead in Song mode; off, it stays put
  1246. followButton.setOnColour (theme::colour::bg6);
  1247. followButton.setIconColourWhenOn (theme::colour::accent);
  1248. followButton.setFlat (true);
  1249. followButton.setClickingTogglesState (false);
  1250. followButton.setToggleState (EditorGlobals::get().isFollowing (false), juce::dontSendNotification);
  1251. // PR #308: the right-click's menu in the hint bar (FL's mouse glyph there; LYNX's [RMB] markup + the menu marker), the
  1252. // tooltip the same words in plain text
  1253. const auto followHint = tr ("Follow: the Playlist scrolls along with the playhead while the song plays; off, you can look around freely")
  1254. + " [RMB] " + tr ("Continuous scrolling");
  1255. ui::setHint (followButton, followHint, true);
  1256. followButton.setTooltip (ui::plainHint (followHint));
  1257. ui::setQuickTip (followButton, tr ("Follow the playhead"));
  1258. followButton.onClick = [this] { runAction ("playlist.follow"); };
  1259. followButton.onRightClick = [this] { showFollowMenu(); };
  1260. followButton.setWantsKeyboardFocus (false);
  1261. followButton.setMouseClickGrabsKeyboardFocus (false);
  1262. addAndMakeVisible (followButton);
  1263. // FL's STRETCH switch (ClipStretchBtn [DFM]: "Stretch audio when resizing audio clips", Shift+M; round 168f)
  1264. stretchButton.setOnColour (theme::colour::bg6);
  1265. stretchButton.setIconColourWhenOn (theme::colour::accent);
  1266. stretchButton.setFlat (true);
  1267. stretchButton.setClickingTogglesState (false);
  1268. stretchButton.setToggleState (EditorGlobals::get().stretchOnResize, juce::dontSendNotification);
  1269. stretchButton.setTooltip (tr ("Stretch: resizing an audio clip stretches its audio instead of cutting it (Shift+M)"));
  1270. ui::setQuickTip (stretchButton, tr ("Stretch audio when resizing audio clips"));
  1271. stretchButton.onClick = [this] { runAction ("playlist.stretchMode"); };
  1272. stretchButton.setWantsKeyboardFocus (false);
  1273. stretchButton.setMouseClickGrabsKeyboardFocus (false);
  1274. addAndMakeVisible (stretchButton);
  1275. // round 190jq (issue #191, LYNX extra): the pointer-click switch, shown with Settings › LYNX extras › "Pointer click
  1276. // switch in the Playlist toolbar" (core/PlaylistViewOptions.h); drawn as Follow and Stretch are
  1277. pointerButton.setOnColour (theme::colour::bg6);
  1278. pointerButton.setIconColourWhenOn (theme::colour::accent);
  1279. pointerButton.setFlat (true);
  1280. pointerButton.setClickingTogglesState (false);
  1281. pointerButton.setToggleState (pointerclick::on, juce::dontSendNotification);
  1282. pointerButton.setTooltip (tr ("Pointer click: a click on an empty spot selects and moves the song position; a double click places the clip (LYNX)"));
  1283. ui::setQuickTip (pointerButton, tr ("Click on an empty spot selects and moves the song position (pointer click)"));
  1284. pointerButton.onClick = [] { workflowextras::runAction ("playlist.pointerClick"); };
  1285. pointerButton.setWantsKeyboardFocus (false);
  1286. pointerButton.setMouseClickGrabsKeyboardFocus (false);
  1287. addChildComponent (pointerButton);
  1288. {
  1289. auto button = std::make_unique<AddTrackButton>();
  1290. button->setTooltip (tr ("Add instrument track / Add audio track"));
  1291. button->onMenu = [this] {
  1292. buildAddTrackMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (addTrackButton.get()));
  1293. };
  1294. button->onAddAudioTrack = [this] { addAudioTrackNow(); };
  1295. button->onMorePlugins = [this] { morePluginsForTrack (-1); };
  1296. addTrackButton = std::move (button);
  1297. addAndMakeVisible (*addTrackButton);
  1298. }
  1299. arrangementBox.setTooltip (tr ("Arrangement (as in FL, a project can have several)"));
  1300. arrangementBox.setWantsKeyboardFocus (false);
  1301. arrangementBox.setMouseClickGrabsKeyboardFocus (false);
  1302. arrangementBox.onChange = [this] { arrangementChosen(); };
  1303. addAndMakeVisible (arrangementBox);
  1304. refreshArrangementBox();
  1305. refreshTrackLayout();
  1306. engine.addChangeListener (this);
  1307. EditorGlobals::get().addChangeListener (this);
  1308. ui::WaveformCache::getInstance()->addChangeListener (this); // a waveform became ready, or the settings changed
  1309. }
  1310. namespace
  1311. {
  1312. enum ArrangementAction
  1313. {
  1314. newArrangement = 1001,
  1315. cloneArrangement,
  1316. renameArrangementAction,
  1317. removeArrangementAction,
  1318. manageArrangements
  1319. };
  1320. } // namespace
  1321. void PlaylistComponent::refreshArrangementBox()
  1322. {
  1323. const auto& song = engine.getSong();
  1324. juce::StringArray names;
  1325. for (const auto& a : song.arrangements)
  1326. names.add (juce::String::fromUTF8 (a.name.c_str()));
  1327. // only rebuilds when something changed (rebuilding closes the open menu)
  1328. bool same = arrangementBox.getNumItems() == names.size() + 4;
  1329. for (int i = 0; same && i < names.size(); ++i)
  1330. same = arrangementBox.getItemText (i) == names[i];
  1331. if (! same)
  1332. {
  1333. arrangementBox.clear (juce::dontSendNotification);
  1334. for (int i = 0; i < names.size(); ++i)
  1335. arrangementBox.addItem (names[i], i + 1);
  1336. arrangementBox.addSeparator();
  1337. arrangementBox.addItem (tr ("New arrangement"), newArrangement);
  1338. arrangementBox.addItem (tr ("Clone this one"), cloneArrangement);
  1339. arrangementBox.addItem (tr ("Rename..."), renameArrangementAction);
  1340. arrangementBox.addItem (tr ("Remove this one"), removeArrangementAction);
  1341. arrangementBox.addSeparator();
  1342. arrangementBox.addItem (tr ("Arrangements and merging..."), manageArrangements);
  1343. arrangementBox.setItemEnabled (removeArrangementAction, names.size() > 1);
  1344. }
  1345. const auto shownBefore = arrangementBox.getText();
  1346. arrangementBox.setSelectedId (song.currentArrangement + 1, juce::dontSendNotification);
  1347. if (toolbarFitsNarrow && arrangementBox.getText() != shownBefore) // (round 190sc: the box's width follows its name there)
  1348. resized();
  1349. }
  1350. void PlaylistComponent::arrangementChosen()
  1351. {
  1352. const auto id = arrangementBox.getSelectedId();
  1353. const auto& song = engine.getSong();
  1354. setSelection ({});
  1355. if (id >= 1 && id <= (int) song.arrangements.size())
  1356. {
  1357. if (id - 1 != song.currentArrangement)
  1358. engine.editSong ([index = id - 1] (Song& s) { s.selectArrangement (index); }, false);
  1359. return;
  1360. }
  1361. switch (id)
  1362. {
  1363. case newArrangement:
  1364. engine.editSong ([] (Song& s) { s.addArrangement ("Arrangement " + std::to_string (s.arrangements.size() + 1)); });
  1365. break;
  1366. case cloneArrangement:
  1367. engine.editSong ([] (Song& s) {
  1368. s.addArrangement (s.arrangements[(std::size_t) s.currentArrangement].name + " (copy)", true);
  1369. });
  1370. break;
  1371. case renameArrangementAction:
  1372. renameArrangement();
  1373. break;
  1374. case manageArrangements:
  1375. showArrangements (engine);
  1376. break;
  1377. case removeArrangementAction:
  1378. engine.editSong ([] (Song& s) { s.removeArrangement (s.currentArrangement); });
  1379. break;
  1380. default:
  1381. break;
  1382. }
  1383. refreshArrangementBox();
  1384. }
  1385. void PlaylistComponent::renameArrangement()
  1386. {
  1387. const auto index = engine.getSong().currentArrangement;
  1388. auto* window = new juce::AlertWindow (tr ("Rename arrangement"), {}, juce::MessageBoxIconType::NoIcon);
  1389. window->addTextEditor ("name", juce::String::fromUTF8 (engine.getSong().arrangements[(std::size_t) index].name.c_str()));
  1390. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1391. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1392. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, index, window] (int result) {
  1393. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  1394. if (result == 1 && ! name.empty() && index < (int) engine.getSong().arrangements.size())
  1395. engine.editSong ([index, name] (Song& s) { s.arrangements[(std::size_t) index].name = name; });
  1396. }),
  1397. true);
  1398. }
  1399. PlaylistComponent::~PlaylistComponent()
  1400. {
  1401. EditorGlobals::get().removeChangeListener (this);
  1402. engine.removeChangeListener (this);
  1403. if (auto* cache = ui::WaveformCache::getInstanceWithoutCreating())
  1404. cache->removeChangeListener (this);
  1405. }
  1406. juce::Colour PlaylistComponent::patternColour (const Song& song, int pattern)
  1407. {
  1408. if (pattern >= 0 && pattern < (int) song.patterns.size() && song.patterns[(std::size_t) pattern].colour != 0)
  1409. return juce::Colour (song.patterns[(std::size_t) pattern].colour);
  1410. // round 190oj: in the Pattern layout a pattern without a colour is FL's grey (FL 2026: a new project's "Pattern 1" and
  1411. // Thief's "Pattern 7" / "Pattern 8" in the picker, #485157, the colour of a colourless track); the auto hues gave
  1412. // white names at 2.6-3.0:1
  1413. if (flClipLook())
  1414. return juce::Colour (0xff485156);
  1415. // hues spread by the golden ratio: neighboring patterns get clearly different colors
  1416. const auto hue = std::fmod (0.08f + (float) pattern * 0.618034f, 1.0f);
  1417. return juce::Colour::fromHSV (hue, 0.45f, 0.75f, 1.0f);
  1418. }
  1419. juce::Rectangle<int> PlaylistComponent::gridArea() const
  1420. {
  1421. return getLocalBounds().withTrimmedLeft (headerWidth).withTrimmedTop (tracksTop())
  1422. .withTrimmedRight (scrollBarSize).withTrimmedBottom (blocksSectionHeight());
  1423. }
  1424. int PlaylistComponent::blocksSectionHeight() const
  1425. {
  1426. if (! engine.getSong().patternBlocksOn)
  1427. return 0;
  1428. const auto available = getHeight() - tracksTop();
  1429. const auto least = PatternBlocksView::dividerHeight + 3 * PatternBlocksView::rowHeight;
  1430. const auto most = juce::jmax (least, available - 2 * baseRowHeight()); // the clip tracks keep two rows
  1431. // by default a third of the grid, or less when every row (and a spare one) fits in less
  1432. const auto rows = PatternBlocksView::dividerHeight + ((int) engine.getSong().patterns.size() + 1) * PatternBlocksView::rowHeight;
  1433. const auto wanted = blocksHeight > 0 ? blocksHeight : juce::jmin (available / 3, rows);
  1434. return juce::jlimit (least, most, wanted);
  1435. }
  1436. int PlaylistComponent::videoSectionHeight() const
  1437. {
  1438. const auto natural = VideoLanesView::contentHeight (engine.getSong());
  1439. if (natural <= 0)
  1440. return 0;
  1441. // (the clip tracks keep two rows; with the Pattern Blocks section too, the video lanes take at most half)
  1442. const auto available = getHeight() - headerHeight - sectionsLaneHeight() - chordLaneHeight();
  1443. const auto least = VideoLanesView::dividerHeight + 20;
  1444. const auto most = juce::jmax (least, engine.getSong().patternBlocksOn ? available / 2 : available - 2 * baseRowHeight());
  1445. return juce::jlimit (least, most, videoHeight > 0 ? videoHeight : natural);
  1446. }
  1447. void PlaylistComponent::setVideoHeight (int height)
  1448. {
  1449. videoHeight = juce::jmax (0, height);
  1450. resized();
  1451. repaint();
  1452. }
  1453. void PlaylistComponent::setBlocksHeight (int height)
  1454. {
  1455. blocksHeight = juce::jmax (1, height);
  1456. resized();
  1457. repaint();
  1458. }
  1459. void PlaylistComponent::scrollTicksBy (double ticks)
  1460. {
  1461. scrollTicks = juce::jmax (0.0, scrollTicks + ticks);
  1462. updateScrollBars();
  1463. repaint();
  1464. }
  1465. void PlaylistComponent::togglePatternBlocks()
  1466. {
  1467. const auto& song = engine.getSong();
  1468. if (! song.patternBlocksOn)
  1469. {
  1470. engine.editSong ([] (Song& s) { s.patternBlocksOn = true; });
  1471. return;
  1472. }
  1473. auto any = false;
  1474. for (const auto& a : song.arrangements)
  1475. any = any || ! a.blocks.empty();
  1476. if (song.blocks.empty() && ! any)
  1477. {
  1478. engine.editSong ([] (Song& s) { s.patternBlocksOn = false; });
  1479. return;
  1480. }
  1481. // blocks that stay hidden would still be in the project but silent: FL's own way out was to turn them into clips
  1482. auto options = juce::MessageBoxOptions()
  1483. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  1484. .withTitle (tr ("Pattern blocks"))
  1485. .withMessage (tr ("This project has pattern blocks. Turn them into clips (one track per pattern) so they keep playing, or delete them?"))
  1486. .withButton (tr ("Turn them into clips"))
  1487. .withButton (tr ("Delete them"))
  1488. .withButton (tr ("Cancel"))
  1489. .withAssociatedComponent (this);
  1490. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] (int result) {
  1491. if (safe == nullptr || result == 0)
  1492. return;
  1493. safe->engine.editSong ([result] (Song& s) {
  1494. if (result == 1)
  1495. patternblocks::toClipsInEveryArrangement (s);
  1496. s.forEachBlockList ([] (std::vector<PatternBlock>& list) { list.clear(); });
  1497. s.patternBlocksOn = false;
  1498. });
  1499. });
  1500. }
  1501. void PlaylistComponent::turnBlocksIntoClips()
  1502. {
  1503. if (engine.getSong().blocks.empty())
  1504. {
  1505. ui::postHint ({ tr ("No pattern blocks to turn into clips"), {} }, 3000);
  1506. return;
  1507. }
  1508. setSelection ({});
  1509. engine.editSong ([] (Song& s) { patternblocks::toClips (s); });
  1510. }
  1511. double PlaylistComponent::tickToX (double tick) const { return headerWidth + (tick - scrollTicks) * pixelsPerTick; }
  1512. double PlaylistComponent::xToTick (int x) const { return (x - headerWidth) / pixelsPerTick + scrollTicks; }
  1513. // Round 190jf (B17): a header's left edge, one step per folder level (FL's groups: 2 px for a header, 8 for a member)
  1514. int PlaylistComponent::headerIndent (const Song& song, int track)
  1515. {
  1516. const auto depth = noteedit::folderDepth (song, track);
  1517. return depth > 0 ? groupIndent * depth : 2;
  1518. }
  1519. int PlaylistComponent::heightOf (int track) const
  1520. {
  1521. const auto& tracks = engine.getSong().playlistTracks;
  1522. if (const auto owner = projection.ownerOf (track); owner >= 0 && laneHidden (owner)) // round 190jq: a folded lane
  1523. return 0;
  1524. if (anyHiddenTracks && ! showHiddenTracks && trackstates::isHidden (engine.getSong(), track)) // round 190op (P4): no row
  1525. return 0;
  1526. if (noteedit::isFoldedAway (engine.getSong(), track))
  1527. return hideCollapsedGroups ? 0 : foldedHeight; // FL's View › "Hide collapsed grouped tracks" (round 190jf)
  1528. // rollup 0.1.30 step 7 (owner, QA-2): the Simple layout hides imported take lanes (Live's TakeLanes, round
  1529. // qafix190kq's PlaylistTrack::takeLane), as the clip grid and the Session mixer do; the Pattern layout's Playlist and
  1530. // the Clip-launch Arrangement keep them under their track. (A comp made in LYNX keeps its lanes everywhere.)
  1531. if (simpleHeaders && track >= 0 && track < (int) tracks.size() && tracks[(std::size_t) track].takeLane && tracks[(std::size_t) track].grouped)
  1532. return 0;
  1533. if (arrange::isFolded (engine.getSong(), track)) // round 190cg: a folded track is its title bar
  1534. return liveFoldedHeight;
  1535. const auto h = track >= 0 && track < (int) tracks.size() ? tracks[(std::size_t) track].height : 0;
  1536. // "Lock to this size" (FL +0x14, round 168f): the row keeps its px height whatever the vertical zoom
  1537. if (const auto locked = track >= 0 && track < (int) tracks.size() ? tracks[(std::size_t) track].lockedHeight : -1; locked > 0)
  1538. return polish::clampTrackHeight (locked);
  1539. return scaledHeight (h > 0 ? polish::clampTrackHeight (h) : baseRowHeight());
  1540. }
  1541. int PlaylistComponent::baseRowHeight() const
  1542. {
  1543. if (simpleHeaders)
  1544. return simpleTrackHeight();
  1545. if (liveStyle) // (round 190jn, owner decision CL-17: Live's 19 px collapsed lanes in its look, 38 px an option)
  1546. return liveArrangeLook() && ! tallLiveLanes ? liveCollapsedHeight : liveTrackHeight;
  1547. return polish::clampTrackHeight (engine.getSong().playlistRowHeight);
  1548. }
  1549. juce::Rectangle<int> PlaylistComponent::trackZoomHandle() const
  1550. {
  1551. // the corner above the vertical scroll bar, beside the overview and the ruler (where FL keeps it)
  1552. return { getWidth() - scrollBarSize, toolbarHeight, scrollBarSize, headerHeight - toolbarHeight };
  1553. }
  1554. void PlaylistComponent::setTrackZoom (double zoom, int anchorY)
  1555. {
  1556. zoom = juce::jlimit (0.5, 4.0, zoom);
  1557. if (std::abs (zoom - trackZoom) < 1.0e-4)
  1558. return;
  1559. // the track under `anchorY` stays where it is
  1560. anchorY = juce::jlimit (tracksTop(), juce::jmax (tracksTop(), gridArea().getBottom() - 1), anchorY);
  1561. const auto track = yToTrack (anchorY);
  1562. const auto within = heightOf (track) > 0 ? (double) (anchorY - trackToY (track)) / heightOf (track) : 0.0;
  1563. trackZoom = zoom;
  1564. refreshTrackLayout();
  1565. const auto top = trackToY (track) + scrollY - tracksTop(); // the track's top in the content
  1566. scrollY = juce::jmax (0, top + (int) std::lround (within * heightOf (track)) - (anchorY - tracksTop()));
  1567. updateScrollBars();
  1568. repaint();
  1569. ui::postHint ({ tr ("Track height (vertical zoom)"), juce::String (juce::roundToInt (trackZoom * 100.0)) + "%", false, false });
  1570. }
  1571. void PlaylistComponent::refreshTrackLayout()
  1572. {
  1573. const auto count = numTracks();
  1574. updateProjection (count); // round 190jq: the rows in drawn order (automation clips as lanes; else the tracks' order)
  1575. trackTops.assign ((std::size_t) count + 1, 0);
  1576. for (int r = 0; r < count; ++r) // (indexed by drawn row)
  1577. {
  1578. const auto t = projection.trackAt (r);
  1579. trackTops[(std::size_t) r + 1] = trackTops[(std::size_t) r] + heightOf (t) + laneBlockHeight (t); // (+ its lanes: round 177b)
  1580. }
  1581. }
  1582. // --- round 190jq (issue #191.3, core/PlaylistViewOptions.h › cliplanes) --------------------------------------------------
  1583. bool PlaylistComponent::clipLanesShown() const noexcept
  1584. {
  1585. return cliplanes::shownIn (liveStyle, simpleHeaders);
  1586. }
  1587. void PlaylistComponent::updateProjection (int count)
  1588. {
  1589. const auto on = clipLanesShown();
  1590. // (worked out again after a song change or a switch; a zoom or a scroll keeps it)
  1591. // (round 190oo: + the Clip-launch look, whose envelope lists are made here too)
  1592. const auto stamp = (engine.getPublishCount() * 1000003u + (std::uint64_t) count) * 4u + (on ? 1u : 0u) + (liveStyle ? 2u : 0u);
  1593. if (stamp == projectionStamp && (int) projection.order.size() == count)
  1594. return;
  1595. projectionStamp = stamp;
  1596. const auto& song = engine.getSong();
  1597. anyHiddenTracks = trackstates::hiddenCount (song) > 0; // (round 190op: heightOf looks no further without any)
  1598. projection = cliplanes::project (song, count, on);
  1599. laneNames.assign ((std::size_t) count, {});
  1600. laneClips.clear(); // (round 190oo, CS-19: rebuilt below while lanes are drawn)
  1601. if (! projection.any())
  1602. return;
  1603. if (liveStyle)
  1604. laneClips = cliplanes::laneClipLists (song, projection, count);
  1605. for (const auto& c : song.playlist)
  1606. if (projection.isChild (c.track) && laneNames[(std::size_t) c.track].isEmpty() && c.kind == ClipKind::automation && c.automation >= 0
  1607. && c.automation < (int) song.automations.size())
  1608. laneNames[(std::size_t) c.track] = juce::String::fromUTF8 (song.automations[(std::size_t) c.automation].name.c_str());
  1609. }
  1610. bool PlaylistComponent::laneHidden (int owner) const
  1611. {
  1612. const auto& song = engine.getSong();
  1613. return (owner < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) owner].lanesFolded) || arrange::isFolded (song, owner)
  1614. || noteedit::isFoldedAway (song, owner) || heightOf (owner) <= 0;
  1615. }
  1616. // Round 190oo (CS O-3): a project just opened shows its automation lanes folded the first time the Clip-launch arrangement
  1617. // shows it, when the LYNX extra is on (Live folds them). One edit that is not an undo step and does not mark the project
  1618. // changed; nothing at all when no lane is open. Runs once per opened project: later unfolding stays.
  1619. void PlaylistComponent::foldLanesAfterOpen()
  1620. {
  1621. const auto opened = engine.getOpenCount();
  1622. if (opened == foldedForOpen || ! liveStyle || simpleHeaders)
  1623. return; // (another layout: kept for when the Clip-launch arrangement first shows the project)
  1624. foldedForOpen = opened;
  1625. if (! cliplanes::foldedOnOpen)
  1626. return;
  1627. const auto& song = engine.getSong();
  1628. const auto lanes = cliplanes::project (song, numTracks(), cliplanes::shownIn (true, false));
  1629. auto tracks = cliplanes::tracksToFold (song, lanes, autolanes::shown());
  1630. if (tracks.empty())
  1631. return;
  1632. engine.editSong ([tracks = std::move (tracks)] (Song& s) {
  1633. for (const auto t : tracks)
  1634. if (t >= 0 && t < (int) s.playlistTracks.size())
  1635. s.playlistTracks[(std::size_t) t].lanesFolded = true;
  1636. }, false);
  1637. }
  1638. bool PlaylistComponent::liveTakeLane (int track) const
  1639. {
  1640. const auto& tracks = engine.getSong().playlistTracks;
  1641. return liveHeaders() && track >= 0 && track < (int) tracks.size() && tracks[(std::size_t) track].takeLane;
  1642. }
  1643. void PlaylistComponent::paintClipLaneHeader (juce::Graphics& g, int t, int y, int height, bool hovered)
  1644. {
  1645. // the lane plate of round 177b's automation lanes (paintLaneHeaders): indented under the owner, an automation stripe
  1646. // and the control's name; the mute LED and the selection strip work as on any header
  1647. using namespace theme;
  1648. const auto& song = engine.getSong();
  1649. const auto owner = projection.ownerOf (t);
  1650. const auto muted = song.isTrackMuted (t);
  1651. const auto left = (float) headerIndent (song, owner) + 10.0f;
  1652. const auto plate = juce::Rectangle<float> (left, (float) y + 1.0f, (float) (headerWidth - rightColumn()) - 2.0f - left, (float) height - 3.0f);
  1653. g.setColour (colour::bg2.interpolatedWith (colour::automation, hovered ? 0.14f : 0.08f));
  1654. g.fillRoundedRectangle (plate, radius::sm);
  1655. g.setColour (colour::automation.withAlpha (muted ? 0.3f : 0.9f));
  1656. g.fillRoundedRectangle (plate.withWidth (3.0f).reduced (0.0f, juce::jmin (3.0f, plate.getHeight() * 0.2f)), 1.5f);
  1657. const auto led = trackLed (t).toFloat();
  1658. if (height >= 10)
  1659. {
  1660. g.setColour (muteLed (muted));
  1661. g.fillEllipse (led.withSizeKeepingCentre (8.0f, 8.0f));
  1662. if (hovered && hover.led)
  1663. {
  1664. g.setColour (colour::textPrimary.withAlpha (0.7f));
  1665. g.drawEllipse (led.withSizeKeepingCentre (12.0f, 12.0f), 1.0f);
  1666. }
  1667. }
  1668. g.setColour (muted ? colour::textDisabled : colour::textSecondary);
  1669. g.setFont (font (type::caption));
  1670. const auto name = t < (int) laneNames.size() && laneNames[(std::size_t) t].isNotEmpty() ? laneNames[(std::size_t) t] : tr ("Track {0}", { juce::String (t + 1) });
  1671. textcache::drawFittedText (g, name, (int) plate.getX() + 7, y, juce::jmax (0, (int) led.getX() - 4 - ((int) plate.getX() + 7)), height,
  1672. juce::Justification::centredLeft, height >= 30 ? 2 : 1, 0.8f);
  1673. if (isTrackSelected (t)) // (the selection strip's lime box, as on any FL header)
  1674. {
  1675. g.setColour (selectionStripLime);
  1676. g.drawRect (juce::Rectangle<int> (headerWidth - trackhdr::selectionStripWidth, y + 1, trackhdr::selectionStripWidth, juce::jmax (4, height - 2)), 2);
  1677. }
  1678. }
  1679. void PlaylistComponent::refreshViewOptions()
  1680. {
  1681. pointerButton.setToggleState (pointerclick::on, juce::dontSendNotification);
  1682. headerWidth = -1; // (laid out again: the dragged width, or the layout's own)
  1683. resized();
  1684. refreshTrackLayout();
  1685. updateScrollBars();
  1686. repaint();
  1687. }
  1688. // --- round 190jq (issue #164): the header column's right edge ------------------------------------------------------------
  1689. bool PlaylistComponent::onHeaderGrip (juce::Point<int> p) const
  1690. {
  1691. return ! simpleHeaders && ! liveHeaders() && headerwidth::onGrip (p.x, headerWidth) && p.y >= rulerTop && p.y < gridArea().getBottom();
  1692. }
  1693. int PlaylistComponent::tracksHeight() const
  1694. {
  1695. return trackTops.empty() ? numTracks() * defaultRowHeight() : trackTops.back();
  1696. }
  1697. int PlaylistComponent::trackToY (int track) const
  1698. {
  1699. // past the cached rows (the list grew during a drag): default heights
  1700. const auto last = (int) trackTops.size() - 1;
  1701. const auto top = trackTops.empty() ? track * defaultRowHeight()
  1702. : track <= last ? trackTops[(std::size_t) juce::jmax (0, projection.row (track))] // (round 190jq: its drawn row)
  1703. : trackTops.back() + (track - last) * defaultRowHeight();
  1704. return tracksTop() + top - scrollY;
  1705. }
  1706. int PlaylistComponent::yToTrack (int y) const
  1707. {
  1708. const auto offset = y - tracksTop() + scrollY;
  1709. if (trackTops.size() < 2)
  1710. return juce::jlimit (0, numTracks() - 1, offset / defaultRowHeight());
  1711. const auto it = std::upper_bound (trackTops.begin(), trackTops.end(), offset);
  1712. const auto index = (int) (it - trackTops.begin()) - 1;
  1713. return projection.trackAt (juce::jlimit (0, numTracks() - 1, index)); // (round 190jq: the track drawn on that row)
  1714. }
  1715. int PlaylistComponent::dividerAt (juce::Point<int> p) const
  1716. {
  1717. // FL's resize band (FUN_00ea93a0, round 190ft): the bottom quarter of the header, 4 to 14 px, inside the row and
  1718. // left of its buttons (the LED, the group arrow, the audio track's buttons)
  1719. if (p.x >= headerWidth || p.y < tracksTop() || p.y >= gridArea().getBottom())
  1720. return -1;
  1721. const auto t = yToTrack (p.y);
  1722. if (t < 0 || noteedit::isFoldedAway (engine.getSong(), t) || ! trackhdr::inResizeBand (heightOf (t), p.y - trackToY (t)))
  1723. return -1;
  1724. if (const auto led = trackLed (t); ! led.isEmpty() && p.x >= led.getX() - 2)
  1725. return -1;
  1726. for (const auto& r : { trackArrow (t), trackArm (t), trackInput (t), trackAudition (t), trackSolo (t), trackVolume (t), trackPan (t), trackFx (t),
  1727. trackLaneArrow (t), trackAddLane (t) })
  1728. if (! r.isEmpty() && r.expanded (2).contains (p))
  1729. return -1;
  1730. return t;
  1731. }
  1732. void PlaylistComponent::setTrackHeights (std::vector<int> tracks, int height)
  1733. {
  1734. engine.editSong ([tracks, height, base = baseRowHeight()] (Song& s) {
  1735. for (auto t : tracks)
  1736. {
  1737. if (t < 0)
  1738. continue;
  1739. if ((int) s.playlistTracks.size() <= t)
  1740. s.playlistTracks.resize ((std::size_t) t + 1);
  1741. s.playlistTracks[(std::size_t) t].height = height == base ? 0 : polish::clampTrackHeight (height);
  1742. pltracks::unlockSize (s.playlistTracks[(std::size_t) t]); // a new size unlocks it (FL's Size menu)
  1743. }
  1744. });
  1745. refreshTrackLayout();
  1746. updateScrollBars();
  1747. repaint();
  1748. }
  1749. int PlaylistComponent::numTracks() const
  1750. {
  1751. int highest = 0;
  1752. for (const auto& c : engine.getSong().playlist)
  1753. highest = juce::jmax (highest, c.track);
  1754. // Options › Mixer › "Playlist tracks shown" (round 163; 16 by default): at least that many, and always a few free
  1755. // tracks under the last clip
  1756. const auto least = juce::jlimit (1, 500, newProjectDefaults().playlistTracks);
  1757. return juce::jlimit (least, 500, highest + 1 + juce::jlimit (1, 7, least / 2));
  1758. }
  1759. std::int64_t PlaylistComponent::gridTicks() const
  1760. {
  1761. const auto bar = engine.getSong().barTicks();
  1762. const auto& option = grid::resolve (snapBox);
  1763. switch (option.kind)
  1764. {
  1765. case grid::Kind::none: return 1;
  1766. case grid::Kind::ticks: return option.ticks;
  1767. case grid::Kind::bar: return bar;
  1768. case grid::Kind::screen:
  1769. case grid::Kind::nearest: break;
  1770. }
  1771. // FL's Line step at this zoom (round 190ax; it was noteedit::screenStep's: a beat where FL steps half a beat, and
  1772. // quarter steps zoomed in where FL stays on steps)
  1773. return noteedit::flLineStep (pixelsPerTick, engine.getSong().beatsPerBar, meterUnit (engine.getSong().beatUnit));
  1774. }
  1775. std::vector<std::int64_t> PlaylistComponent::snapCandidates() const
  1776. {
  1777. // edges of the other clips ("Nearest note" in the Playlist snaps to clip edges)
  1778. std::vector<std::int64_t> out;
  1779. const auto& playlist = engine.getSong().playlist;
  1780. for (int i = 0; i < (int) playlist.size(); ++i)
  1781. if (std::find (dragIndices.begin(), dragIndices.end(), i) == dragIndices.end())
  1782. {
  1783. out.push_back (playlist[(std::size_t) i].start);
  1784. out.push_back (playlist[(std::size_t) i].end());
  1785. }
  1786. return out;
  1787. }
  1788. std::int64_t PlaylistComponent::snap (double tick, bool enabled) const
  1789. {
  1790. if (! enabled)
  1791. return (std::int64_t) std::floor (tick);
  1792. const auto& option = grid::resolve (snapBox);
  1793. const auto step = gridTicks();
  1794. if (option.kind == grid::Kind::nearest)
  1795. return noteedit::snapNearest (tick, snapCandidates(), 10.0 / pixelsPerTick, step);
  1796. // whole bars respect time signature changes
  1797. if (step == engine.getSong().barTicks())
  1798. return engine.getSong().barAt ((std::int64_t) std::max (0.0, std::floor (tick))).tick;
  1799. return noteedit::snapDown (tick, step);
  1800. }
  1801. void PlaylistComponent::updateScrollBars()
  1802. {
  1803. const auto& song = engine.getSong();
  1804. const auto grid = gridArea();
  1805. const auto bar = (double) song.barTicks();
  1806. const auto total = juce::jmax ((double) song.songLength() + 16 * bar, grid.getWidth() / pixelsPerTick);
  1807. hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
  1808. hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
  1809. vBar.setRangeLimits (0.0, (double) tracksHeight(), juce::dontSendNotification);
  1810. vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
  1811. scrollTicks = hBar.getCurrentRangeStart();
  1812. scrollY = (int) vBar.getCurrentRangeStart();
  1813. overview.minLength = grid.getWidth() / (maxPixelsPerTick);
  1814. overview.setRange (total, scrollTicks, grid.getWidth() / pixelsPerTick);
  1815. }
  1816. void PlaylistComponent::setTitleBarInsets (int left, int right)
  1817. {
  1818. if (left != titleInsetLeft || right != titleInsetRight)
  1819. {
  1820. titleInsetLeft = left;
  1821. titleInsetRight = right;
  1822. resized();
  1823. }
  1824. }
  1825. void PlaylistComponent::resized()
  1826. {
  1827. updateHeaderWidth(); // (round 190ig: the header width follows the layout style)
  1828. updateDropLaneProbe();
  1829. const auto h = toolbarHeight - 6;
  1830. const auto layoutToolbar = [this, h] (int boxWidth) {
  1831. arrangementBox.setBounds (4 + titleInsetLeft, 3, boxWidth, h);
  1832. // round 190ig (FM-26): the Pattern layout's toolbar in FL's order — the snap (magnet) before the tools, and the tools'
  1833. // own FL order and glyphs; the other layouts keep LYNX's order
  1834. tools.setFlPlaylistLook (flClipLook() && ! simpleHeaders);
  1835. if (flClipLook() && ! simpleHeaders)
  1836. {
  1837. snapBox.setBounds (arrangementBox.getRight() + 8, 3, 128, h);
  1838. tools.setBounds (snapBox.getRight() + 8, 3, tools.getIdealWidth (h), h);
  1839. followButton.setBounds (tools.getRight() + 6, 3, h, h);
  1840. }
  1841. else
  1842. {
  1843. tools.setBounds (arrangementBox.getRight() + 8, 3, tools.getIdealWidth (h), h);
  1844. snapBox.setBounds (tools.getRight() + 8, 3, 128, h);
  1845. followButton.setBounds (snapBox.getRight() + 6, 3, h, h);
  1846. }
  1847. stretchButton.setBounds (followButton.getRight() + 2, 3, h, h);
  1848. pointerButton.setBounds (stretchButton.getRight() + 2, 3, h, h); // round 190jq (issue #191)
  1849. // beside the clip grid the Playlist is narrow: what would run under the panel's title buttons goes (the inset keeps
  1850. // 4 px of air before them). Anywhere else the toolbar stays exactly as it was.
  1851. const auto toolbarEnd = getWidth() - titleInsetRight + 4;
  1852. if (toolbarFitsNarrow && tools.getRight() > toolbarEnd)
  1853. tools.setSize (juce::jmax (0, toolbarEnd - tools.getX()), h);
  1854. for (auto* c : std::initializer_list<juce::Component*> { &snapBox, &followButton, &stretchButton })
  1855. c->setVisible (! toolbarFitsNarrow || c->getRight() <= toolbarEnd);
  1856. pointerButton.setVisible (pointerclick::buttonShown && ! simpleHeaders && (! toolbarFitsNarrow || pointerButton.getRight() <= toolbarEnd));
  1857. };
  1858. auto boxWidth = juce::jmin (150, getWidth() / 5);
  1859. layoutToolbar (boxWidth);
  1860. // round 190sc: beside the clip grid (at 125 % the box read "Arrangeme..."), the box takes the width its name needs
  1861. // from the room left after the last item shown, so nothing that showed goes; anywhere else nothing changes
  1862. if (toolbarFitsNarrow)
  1863. {
  1864. auto right = tools.getRight();
  1865. for (auto* c : std::initializer_list<juce::Component*> { &snapBox, &followButton, &stretchButton, &pointerButton })
  1866. if (c->isVisible())
  1867. right = juce::jmax (right, c->getRight());
  1868. const auto need = juce::roundToInt (juce::GlyphArrangement::getStringWidth (getLookAndFeel().getComboBoxFont (arrangementBox), arrangementBox.getText())) + 56;
  1869. if (const auto grow = juce::jlimit (0, juce::jmax (0, getWidth() - titleInsetRight - right), juce::jmin (150, need) - boxWidth); grow > 0)
  1870. layoutToolbar (boxWidth + grow);
  1871. }
  1872. overview.setBounds (headerWidth, toolbarHeight, getWidth() - headerWidth - scrollBarSize, overviewHeight - overviewGap);
  1873. overviewGapBlock.setBounds (overview.getX(), overview.getBottom(), overview.getWidth(), overviewGap);
  1874. // FL's "+" (21 x 18 at 7 px from the left of the header panel), on the ruler's row; FL's headers only
  1875. if (addTrackButton != nullptr)
  1876. {
  1877. addTrackButton->setBounds (7, rulerTop + (timelineHeight - 18) / 2, 21, 18);
  1878. addTrackButton->setVisible (! simpleHeaders);
  1879. }
  1880. const auto blocks = blocksSectionHeight();
  1881. blocksShown = blocks > 0;
  1882. vBar.setBounds (getWidth() - scrollBarSize, tracksTop(), scrollBarSize, getHeight() - tracksTop() - blocks);
  1883. blocksView->setBounds (0, getHeight() - blocks, getWidth(), blocks);
  1884. blocksView->setVisible (blocksShown);
  1885. const auto video = videoSectionHeight();
  1886. const auto lane = sectionsLaneHeight(); // round 190ol: the Sections lane, right under the ruler
  1887. laidOutSectionsHeight = lane;
  1888. sectionsLane->setBounds (0, headerHeight, getWidth(), lane);
  1889. sectionsLane->setVisible (lane > 0);
  1890. const auto chords = chordLaneHeight(); // round 190pf: the Chord lane, under the Sections lane
  1891. laidOutChordHeight = chords;
  1892. chordLane->setBounds (0, headerHeight + lane, getWidth(), chords);
  1893. chordLane->setVisible (chords > 0);
  1894. videoLanes->setBounds (0, headerHeight + lane + chords, getWidth(), video);
  1895. videoLanes->setVisible (video > 0);
  1896. updateScrollBars();
  1897. if (fitSongPending)
  1898. showSongAfterOpen();
  1899. }
  1900. void PlaylistComponent::showSongAfterOpen (bool newProject)
  1901. {
  1902. const auto width = gridArea().getWidth();
  1903. fitSongPending = width < 100;
  1904. if (fitSongPending)
  1905. return;
  1906. scrollY = 0;
  1907. scrollTicks = 0.0;
  1908. const auto length = (double) engine.getSong().songLength();
  1909. // round 190ig (FM-24): FL opens a song at its own zoom, ~16 px a bar, not the whole song squeezed in
  1910. // (LYNX_FL_OPEN_ZOOM=0, diagnostics: the whole song as before, for like-for-like paint benchmarks)
  1911. static const auto flOpenZoom = juce::SystemStats::getEnvironmentVariable ("LYNX_FL_OPEN_ZOOM", "1") != "0";
  1912. if (flClipLook() && flOpenZoom)
  1913. {
  1914. // (round 190oj: File › New opens FL's new project at ~60 px a bar, measured on FL 2026: bar 5 at +240 px)
  1915. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, (newProject ? 60.0 : 16.0) / (double) juce::jmax<std::int64_t> (1, engine.getSong().barTicks()));
  1916. updateScrollBars();
  1917. repaint();
  1918. return;
  1919. }
  1920. if (length > width / pixelsPerTick)
  1921. zoomAll(); // (also updates the scroll bars)
  1922. else
  1923. {
  1924. updateScrollBars();
  1925. repaint();
  1926. }
  1927. }
  1928. void PlaylistComponent::paint (juce::Graphics& g)
  1929. {
  1930. const uitrace::Scope trace ("PlaylistComponent paint", true, g.getClipBounds());
  1931. if (trackTops.size() != (std::size_t) numTracks() + 1) // the track list grew or shrank since the last change message
  1932. refreshTrackLayout();
  1933. if (simpleHeaders || dropLaneProbe.isVisible())
  1934. updateDropLaneProbe();
  1935. if (insertMarkTrack >= 0 || insertMarkLine.isVisible()) // round 190mk (DL-70)
  1936. updateInsertMarkLine();
  1937. heldTitleLeft = keeplabels::on ? (float) gridArea().getX() : -1.0e9f; // (round 190qe: "Keep labels on screen")
  1938. const auto& song = engine.getSong();
  1939. const auto grid = gridArea();
  1940. const auto bar = song.barTicks();
  1941. const auto tracks = numTracks();
  1942. // the overview follows the clips (edits, undo, arrangement switches) and the view
  1943. {
  1944. auto signature = song.playlist.size() * 1000003u + (std::size_t) song.currentArrangement;
  1945. for (const auto& c : song.playlist)
  1946. signature = signature * 31u + (std::size_t) (c.start * 131 + c.length * 7 + c.track * 257 + c.pattern + (c.muted ? 1 : 0));
  1947. if (signature != overviewSignature)
  1948. {
  1949. overviewSignature = signature;
  1950. overview.repaint();
  1951. }
  1952. updateScrollBars();
  1953. }
  1954. using namespace theme;
  1955. const auto live = liveArrangeLook();
  1956. const auto rows = this->paintedRows(); // (round 190jc, SG-2: the Simple layout's real tracks and its drop lane only)
  1957. const auto beatPixels = ppq * pixelsPerTick;
  1958. const auto fl = flClipLook();
  1959. // round 190md (perf): the grid past the song's end in one pass. Since FL's opening zoom (round 190ig, FM-24) a short
  1960. // song leaves most of the grid past its end, and the end-of-song veil (bg0 at 45 %, below) blended each of those
  1961. // pixels once more over the lanes and lines: +46 % paint instructions on the performance gate's inserts50 Playlist
  1962. // vs 0.1.29. With the software renderer at a whole-pixel scale the grid right of the veil's first whole column is
  1963. // now painted once, every colour already veiled by the renderer's own blend (the same pixels), and the window
  1964. // background is no longer painted under the grid (it paints its own). Anything see-through there (half-beat lines,
  1965. // automation lanes, the loop), another renderer or LYNX_PAINT_SAVINGS=0: as before.
  1966. const auto veil = colour::bg0.withAlpha (0.45f);
  1967. const auto veilSplit = [&]() -> std::optional<int> {
  1968. const auto& context = g.getInternalContext();
  1969. const auto scale = context.getPhysicalPixelScaleFactor();
  1970. if (live || ! ui::paintSavings() || song.playlist.empty() || grid.isEmpty() || dynamic_cast<const juce::LowLevelGraphicsSoftwareRenderer*> (&context) == nullptr
  1971. || scale < 1.0f || scale != std::round (scale)
  1972. || ! (colour::bg0.isOpaque() && colour::bg1.isOpaque() && colour::bg2.isOpaque() && colour::textPrimary.isOpaque()
  1973. && colour::gridBar.isOpaque() && colour::gridBeat.isOpaque())
  1974. || (fl && beatPixels >= flHalfBeatLinesFrom && ppq >= 2))
  1975. return std::nullopt;
  1976. const auto endX = tickToX ((double) song.songLength());
  1977. if (! std::isfinite (endX) || endX >= (double) grid.getRight() - 1.0)
  1978. return std::nullopt; // (nothing, or a column or less, to veil)
  1979. const auto split = juce::jmax (grid.getX(), (int) std::ceil (juce::jmax (endX, (double) grid.getX())));
  1980. if (song.hasLoop() && juce::jmax (tickToX ((double) song.loopStart), tickToX ((double) song.loopEnd)) + 2.0 >= (double) split)
  1981. return std::nullopt;
  1982. for (int t = 0; t < rows; ++t)
  1983. if (const auto lanes = laneBlockHeight (t); lanes > 0)
  1984. {
  1985. const auto top = trackToY (t) + heightOf (t);
  1986. if (top <= grid.getBottom() && top + lanes >= grid.getY())
  1987. return std::nullopt;
  1988. }
  1989. return split;
  1990. }();
  1991. if (veilSplit.has_value())
  1992. {
  1993. const juce::Graphics::ScopedSaveState keep (g);
  1994. g.excludeClipRegion (grid);
  1995. g.fillAll (colour::bg1);
  1996. }
  1997. else
  1998. {
  1999. g.fillAll (colour::bg1);
  2000. }
  2001. // --- tracks and grid ---------------------------------------------------
  2002. {
  2003. const uitrace::Scope traceGrid ("Playlist lanes+clips", false);
  2004. juce::Graphics::ScopedSaveState state (g);
  2005. g.reduceClipRegion (grid);
  2006. const auto paintedRows = g.getClipBounds();
  2007. // round 190jn (CL-17): Live's lanes — the bar groups' shading and grid over the whole grid, a 2 px separator under each lane
  2008. const auto liveLanesCached = live && paintLiveLanesCached (g, grid, rows);
  2009. if (live && ! liveLanesCached)
  2010. paintLiveGrid (g, grid);
  2011. // (round 190md) one pass; with the veil's split two: left of it as always, right of it every colour veiled
  2012. const auto veiled = [&veil] (juce::Colour c) {
  2013. auto p = c.getPixelARGB();
  2014. p.blend (veil.getPixelARGB()); // (what the software renderer does to an opaque pixel under the veil)
  2015. return juce::Colour (p);
  2016. };
  2017. for (int pass = 0; pass < (veilSplit.has_value() ? 2 : 1); ++pass)
  2018. {
  2019. const juce::Graphics::ScopedSaveState passState (g);
  2020. const auto rightOfSplit = pass == 1;
  2021. if (veilSplit.has_value() && ! g.reduceClipRegion (rightOfSplit ? grid.withLeft (*veilSplit) : grid.withRight (*veilSplit)))
  2022. continue;
  2023. const auto ink = [&veiled, rightOfSplit] (juce::Colour c) { return rightOfSplit ? veiled (c) : c; };
  2024. if (veilSplit.has_value()) // the grid's own background where no lane covers it (the window's was left out)
  2025. {
  2026. juce::RectangleList<int> background (grid);
  2027. for (int t = 0; t < rows; ++t)
  2028. if (const auto trackHeight = heightOf (t); trackHeight > 0)
  2029. background.subtract (juce::Rectangle<int> (grid.getX(), trackToY (t), grid.getWidth(), trackHeight));
  2030. g.setColour (ink (colour::bg1));
  2031. g.fillRectList (background);
  2032. }
  2033. // PR #264 (FL's Playlist, checked in FL 2026 in round 190qj): the bars come in groups of 4 and every other group
  2034. // (5-8, 13-16...) is a shade darker, in any time signature; with the lanes' alternating shades that is FL's
  2035. // light/dark plaid. Round 190qj (paint gate: the PR's bg0 veil per bar blended half the grid once more, +15 %
  2036. // Playlist paint instructions): each lane is filled in opaque spans, the dark groups in the lane's own colour
  2037. // with that veil already applied, so every pixel is still painted once.
  2038. struct Span { int x0, x1; bool dark; };
  2039. std::vector<Span> spans;
  2040. if (fl)
  2041. {
  2042. const auto from = grid.getIntersection (paintedRows);
  2043. const auto tickFrom = juce::jmax ((std::int64_t) 0, (std::int64_t) xToTick (from.getX()) - bar);
  2044. const auto tickTo = (std::int64_t) xToTick (from.getRight()) + 1;
  2045. const auto groupDark = [] (int number) { return number >= 1 && ((number - 1) / 4) % 2 == 1; };
  2046. auto at = grid.getX();
  2047. std::optional<bool> dark; // (the shade left of the first bar line: that of the bar before it)
  2048. for (const auto& b : song.barsBetween (tickFrom, tickTo))
  2049. {
  2050. const auto x = juce::jlimit (grid.getX(), grid.getRight(), (int) std::lround (tickToX ((double) b.tick)));
  2051. if (! dark.has_value())
  2052. dark = groupDark (b.number - 1);
  2053. if (x > at)
  2054. spans.push_back ({ at, x, *dark });
  2055. at = juce::jmax (at, x);
  2056. dark = groupDark (b.number);
  2057. }
  2058. if (at < grid.getRight())
  2059. spans.push_back ({ at, grid.getRight(), dark.value_or (false) });
  2060. // merge neighbours of one shade (a group is 4 bars: 1 span instead of 4)
  2061. std::vector<Span> merged;
  2062. for (const auto& sp : spans)
  2063. if (! merged.empty() && merged.back().dark == sp.dark && merged.back().x1 == sp.x0)
  2064. merged.back().x1 = sp.x1;
  2065. else
  2066. merged.push_back (sp);
  2067. spans.swap (merged);
  2068. }
  2069. const auto groupShade = [] (juce::Colour c) { return c.overlaidWith (colour::bg0.withAlpha (0.30f)); };
  2070. const auto fillLane = [&] (juce::Colour c, int y, int h) {
  2071. if (spans.empty())
  2072. {
  2073. g.setColour (c);
  2074. g.fillRect (grid.getX(), y, grid.getWidth(), h);
  2075. return;
  2076. }
  2077. const auto shade = groupShade (c); // (rollup 0.1.32 step 2: once per lane, not per span)
  2078. for (const auto& sp : spans)
  2079. {
  2080. g.setColour (sp.dark ? shade : c);
  2081. g.fillRect (sp.x0, y, sp.x1 - sp.x0, h);
  2082. }
  2083. };
  2084. for (int t = 0; t < rows; ++t)
  2085. {
  2086. const auto y = trackToY (t);
  2087. const auto trackHeight = heightOf (t);
  2088. const auto rowsHeight = trackHeight + laneBlockHeight (t);
  2089. if (y > grid.getBottom() || y + rowsHeight < grid.getY() || y > paintedRows.getBottom() || y + rowsHeight < paintedRows.getY())
  2090. continue;
  2091. const uitrace::Part tally (uitrace::part::lanes);
  2092. if (live)
  2093. {
  2094. if (! liveLanesCached) // (the cached image holds them)
  2095. {
  2096. g.setColour (liveLaneSeparator);
  2097. g.fillRect (grid.getX(), y + trackHeight - 2, grid.getWidth(), 2);
  2098. }
  2099. }
  2100. else
  2101. {
  2102. auto lane = projection.row (t) % 2 == 0 ? colour::bg2 : colour::bg2.interpolatedWith (colour::bg1, 0.5f); // (by drawn row)
  2103. if (projection.isChild (t)) // round 190jq: an automation clip lane, in the lanes' colour (round 177b)
  2104. lane = colour::bg1.interpolatedWith (colour::bg2, 0.35f);
  2105. if (t == hover.track && drag == Drag::none)
  2106. lane = lane.interpolatedWith (colour::textPrimary, 0.025f); // the track under the mouse
  2107. fillLane (ink (lane), y, trackHeight);
  2108. g.setColour (ink (colour::bg0));
  2109. g.drawHorizontalLine (y + trackHeight - 1, (float) grid.getX(), (float) grid.getRight());
  2110. }
  2111. if (const auto lanes = laneBlockHeight (t); lanes > 0) // round 177b: the track's automation lanes
  2112. {
  2113. g.setColour (colour::bg1.interpolatedWith (colour::bg2, 0.35f));
  2114. g.fillRect (grid.getX(), y + trackHeight, grid.getWidth(), lanes);
  2115. g.setColour (colour::bg0.withAlpha (0.6f));
  2116. for (int i = 0; i < (int) song.playlistTracks[(std::size_t) t].lanes.size(); ++i)
  2117. g.drawHorizontalLine (laneRow (t, i).getBottom() - 1, (float) grid.getX(), (float) grid.getRight());
  2118. }
  2119. }
  2120. // (only the bars of the repainted columns: a playhead strip is 16 px wide, the view can hold hundreds of bars,
  2121. // and every line is a renderer call even where it is clipped away; round 174e)
  2122. const auto paintedX = grid.getIntersection (g.getClipBounds());
  2123. // round 190ig (Pattern layout, FL): FM-29 — each line on whole physical pixels (at 150 % a 1 px line at x = 37 fell on
  2124. // 55.5 device px and blurred over two columns); FM-24 — bars closer than 12 px: every 4th bar line only, as FL
  2125. // thins its grid when zoomed out (LYNX's 1 650 px "barcode" of the whole song)
  2126. const auto lineScale = juce::jmax (1.0f, g.getInternalContext().getPhysicalPixelScaleFactor());
  2127. const auto lineWidth = juce::jmax (1.0f, std::round (lineScale)) / lineScale;
  2128. const auto vline = [&g, &grid, fl, lineScale, lineWidth] (double x) {
  2129. if (fl)
  2130. g.fillRect (juce::Rectangle<float> ((float) std::floor (x * lineScale) / lineScale, (float) grid.getY(), lineWidth, (float) grid.getHeight()));
  2131. else
  2132. g.drawVerticalLine ((int) x, (float) grid.getY(), (float) grid.getBottom());
  2133. };
  2134. const auto barEvery = fl && bar * pixelsPerTick < 12.0 ? 4 : 1;
  2135. if (! live) // (Live's grid: paintLiveGrid)
  2136. for (const auto& b : song.barsBetween (juce::jmax ((std::int64_t) std::max (0.0, scrollTicks), (std::int64_t) xToTick (paintedX.getX()) - bar),
  2137. juce::jmin ((std::int64_t) xToTick (grid.getRight()), (std::int64_t) xToTick (paintedX.getRight())) + 1))
  2138. {
  2139. if (barEvery > 1 && (b.number - 1) % barEvery != 0)
  2140. continue;
  2141. g.setColour (ink (colour::gridBar));
  2142. vline (fl ? tickToX ((double) b.tick) : (double) (int) tickToX ((double) b.tick));
  2143. // zoomed far out: bar lines only (FL: no beat lines yet at 10 px a beat, fl-playlist-zoom-audioclips.png)
  2144. if (beatPixels < (fl ? flBeatLinesFrom : 8.0))
  2145. continue;
  2146. g.setColour (ink (colour::gridBeat));
  2147. for (auto tick = b.tick + ppq; tick < b.tick + b.length; tick += ppq)
  2148. vline (fl ? tickToX ((double) tick) : (double) (int) tickToX ((double) tick));
  2149. if (fl && beatPixels >= flHalfBeatLinesFrom && ppq >= 2)
  2150. {
  2151. g.setColour (colour::gridBeat.withMultipliedAlpha (flHalfBeatAlpha));
  2152. for (auto tick = b.tick + ppq / 2; tick < b.tick + b.length; tick += ppq)
  2153. vline (tickToX ((double) tick));
  2154. }
  2155. }
  2156. if (rightOfSplit)
  2157. continue; // (round 190md: no lanes, loop or half-beat lines right of the split; the veil is in its colours)
  2158. paintLanes (g, grid); // round 177b (nothing when lanes are off)
  2159. // loop region
  2160. if (song.hasLoop())
  2161. {
  2162. const auto lx0 = (float) tickToX ((double) song.loopStart), lx1 = (float) tickToX ((double) song.loopEnd);
  2163. const auto tint = song.loopOff ? colour::textSecondary : colour::accent; // (round 190cg: grey while the loop is switched off)
  2164. g.setColour (tint.withAlpha (0.06f));
  2165. g.fillRect (juce::Rectangle<float> (lx0, (float) grid.getY(), lx1 - lx0, (float) grid.getHeight()));
  2166. g.setColour (tint.withAlpha (0.45f));
  2167. g.drawVerticalLine ((int) lx0, (float) grid.getY(), (float) grid.getBottom());
  2168. g.drawVerticalLine ((int) lx1, (float) grid.getY(), (float) grid.getBottom());
  2169. }
  2170. // end of song (Live does not shade past the end: round 190jn)
  2171. if (! song.playlist.empty() && ! live)
  2172. {
  2173. const auto endX = (float) tickToX ((double) song.songLength());
  2174. g.setColour (veil);
  2175. g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
  2176. }
  2177. } // (the passes)
  2178. // Performance mode (round 165m): the zone before the Start marker, where clips are launched instead of played
  2179. if (const auto zoneEnd = song.performanceZoneEnd(); zoneEnd > 0)
  2180. {
  2181. const auto zx0 = (float) tickToX (0.0), zx1 = (float) tickToX ((double) zoneEnd);
  2182. if (zx1 > (float) grid.getX())
  2183. {
  2184. g.setColour (colour::info.withAlpha (0.05f));
  2185. g.fillRect (juce::Rectangle<float> (zx0, (float) grid.getY(), zx1 - zx0, (float) grid.getHeight()));
  2186. g.setColour (colour::info.withAlpha (0.55f));
  2187. g.fillRect (juce::Rectangle<float> (zx1 - 1.0f, (float) grid.getY(), 2.0f, (float) grid.getHeight()));
  2188. }
  2189. }
  2190. g.setFont (font (type::caption));
  2191. // what each comp plays from its take lanes (round 177c); nothing is worked out without a comp track
  2192. std::vector<comp::Used> compUsed;
  2193. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  2194. if (song.playlistTracks[(std::size_t) t].compTrack)
  2195. if (const auto group = comp::groupOf (song, t); group.valid() && group.comp == t)
  2196. {
  2197. const auto used = comp::usedRanges (song, group);
  2198. compUsed.insert (compUsed.end(), used.begin(), used.end());
  2199. }
  2200. auto veilIfMuted = [&] (const Clip& clip, juce::Rectangle<float> area) {
  2201. if (! shownMuted (song, clip))
  2202. return;
  2203. std::vector<juce::Rectangle<float>> lit;
  2204. if (! compUsed.empty())
  2205. {
  2206. const auto index = (int) (&clip - song.playlist.data());
  2207. for (const auto& u : compUsed)
  2208. if (u.laneClip == index)
  2209. {
  2210. const auto x0 = juce::jmax (area.getX(), (float) tickToX ((double) u.from));
  2211. const auto x1 = juce::jmin (area.getRight(), (float) tickToX ((double) u.to));
  2212. if (x1 > x0)
  2213. lit.push_back ({ x0, area.getY(), x1 - x0, area.getHeight() });
  2214. }
  2215. }
  2216. paintMutedVeil (g, area, lit);
  2217. };
  2218. SmallClips smallClips;
  2219. const auto physicalScale = g.getInternalContext().getPhysicalPixelScaleFactor();
  2220. for (int i = 0; i < (int) song.playlist.size(); ++i)
  2221. {
  2222. const auto& c = song.playlist[(std::size_t) i];
  2223. const auto x0 = (float) tickToX ((double) c.start);
  2224. const auto x1 = (float) tickToX ((double) c.end());
  2225. const auto y = (float) trackToY (c.track);
  2226. const auto trackHeight = heightOf (c.track);
  2227. if (x1 < grid.getX() || x0 > grid.getRight() || y > grid.getBottom() || y + trackHeight < grid.getY() || trackHeight <= 0)
  2228. continue; // (round 190jf: a hidden collapsed member has no row)
  2229. const auto r = clipRectAt (x0, x1, y, trackHeight);
  2230. if (! g.getClipBounds().toFloat().intersects (r.expanded (1.0f)))
  2231. continue; // outside the area being repainted
  2232. if (noteedit::isFoldedAway (song, c.track)) // a folded group: each member's clips as a thin bar (FL)
  2233. {
  2234. const auto barColour = c.kind == ClipKind::audio ? colour::audioClip
  2235. : c.kind == ClipKind::automation ? colour::automation
  2236. : tame (patternColour (song, c.pattern));
  2237. g.setColour (barColour.withAlpha (shownMuted (song, c) ? 0.35f : 0.9f));
  2238. g.fillRect (juce::Rectangle<float> (x0, y + 2.0f, juce::jmax (2.0f, x1 - x0 - 1.0f), (float) foldedHeight - 4.0f));
  2239. if (isSelected (i))
  2240. {
  2241. g.setColour (colour::textPrimary);
  2242. g.drawRect (juce::Rectangle<float> (x0, y + 1.0f, juce::jmax (2.0f, x1 - x0 - 1.0f), (float) foldedHeight - 2.0f), 1.0f);
  2243. }
  2244. continue;
  2245. }
  2246. if (r.getWidth() < SmallClips::maxWidth && c.kind != ClipKind::automation && ! c.muted && ! isSelected (i))
  2247. {
  2248. addSmallClip (smallClips, physicalScale, c, r, c.kind == ClipKind::pattern && c.pattern == song.currentPattern);
  2249. if (shownMuted (song, c)) // (round 190qm: its track is switched off; the X needs 14 px, as for a muted clip)
  2250. smallClips.veils.addWithoutMerging (r);
  2251. continue;
  2252. }
  2253. if (c.kind == ClipKind::automation && live && projection.isChild (c.track) && c.gridSlot < 0)
  2254. {
  2255. // round 190oo (CS-19): Live draws no block on an automation lane, only its envelope (paintLiveEnvelopeLanes,
  2256. // after the clips); a selected clip shows as Live's selected time range under the line
  2257. if (isSelected (i))
  2258. {
  2259. g.setColour (juce::Colour (0xff5a737a)); // (Live's selection on a lane, warp190cg-08a: #5a737a)
  2260. g.fillRect (r);
  2261. }
  2262. veilIfMuted (c, r);
  2263. continue;
  2264. }
  2265. if (c.kind == ClipKind::automation)
  2266. {
  2267. paintAutomationClip (g, c, r);
  2268. veilIfMuted (c, r);
  2269. if (isSelected (i))
  2270. paintClipOutline (g, r, colour::automation, true, false);
  2271. continue;
  2272. }
  2273. if (c.kind == ClipKind::audio)
  2274. {
  2275. paintAudioClip (g, c, r);
  2276. veilIfMuted (c, r);
  2277. if (isSelected (i))
  2278. paintClipOutline (g, r, colour::audioClip, true, false);
  2279. continue;
  2280. }
  2281. const auto base = tame (patternColour (song, c.pattern));
  2282. const auto current = c.pattern == song.currentPattern;
  2283. const auto selected = isSelected (i);
  2284. const auto simpleLook = simpleClipLook (c); // (round 190jc: the Simple layout's BandLab colours)
  2285. const auto liveLook = live ? std::optional<theme::ClipLook> (liveClipLook (c)) : std::nullopt; // (round 190jn, CL-17)
  2286. // body + name strip
  2287. const auto patternName = juce::String::fromUTF8 (song.patterns[(std::size_t) c.pattern].name.c_str());
  2288. const auto clipBody = liveLook ? paintLiveClipFrame (g, r, *liveLook, patternName)
  2289. : paintClipFrame (g, r, base, patternName, ClipGlyph::pattern, shownMuted (song, c), simpleLook ? &*simpleLook : nullptr);
  2290. // note thumbnail: the pattern's notes as small rounded bars in a light tint of the clip colour,
  2291. // spread over the body's height by pitch (a few keys of padding so single notes don't hug the edges)
  2292. const auto& notes = song.patterns[(std::size_t) c.pattern].notes;
  2293. if (! notes.empty() && r.getWidth() > 6 && clipBody.getHeight() >= 4.0f)
  2294. {
  2295. const uitrace::Part tally (uitrace::part::notes);
  2296. int low = 127, high = 0;
  2297. for (const auto& n : notes)
  2298. {
  2299. low = juce::jmin (low, n.key);
  2300. high = juce::jmax (high, n.key);
  2301. }
  2302. const auto body = clipBody.reduced (1.0f, clipBody.getHeight() >= 12.0f ? 3.0f : 1.0f);
  2303. const auto span = juce::jmax (6, high - low + 2); // a small pitch range stays centred
  2304. const auto bottomKey = (low + high) / 2.0f - span / 2.0f;
  2305. const auto rows = (float) span + 1.0f;
  2306. const auto noteHeight = juce::jlimit (1.5f, 2.5f, body.getHeight() / rows);
  2307. g.setColour (liveLook ? liveLook->content : simpleLook ? simpleLook->content : clipContentColour (base));
  2308. juce::Graphics::ScopedSaveState clip (g);
  2309. g.reduceClipRegion (body.toNearestInt());
  2310. const auto visible = g.getClipBounds().toFloat();
  2311. // small notes as plain rectangles (a rounded one is a path each on the GPU renderer; at 2 px the
  2312. // rounding does not show), notes outside the repainted area skipped
  2313. const auto rounded = noteHeight > 2.0f && r.getWidth() > 60.0f;
  2314. // what plays: a clip stretched past its pattern loops it with the LYNX option (issue #25, default on),
  2315. // else the pattern once and empty after it, as FL plays and shows it (round 168k [EXEC])
  2316. const auto passes = clipPasses (c, song.patterns[(std::size_t) c.pattern].effectiveLength (song.meter()));
  2317. for (auto pass = passes.first; pass <= passes.last; ++pass)
  2318. {
  2319. const auto origin = c.start - c.offset + pass * passes.length;
  2320. if (passes.loops && (tickToX ((double) origin) > visible.getRight() || tickToX ((double) (origin + passes.length)) < visible.getX()))
  2321. continue;
  2322. for (const auto& n : notes)
  2323. {
  2324. const auto at = origin + n.start;
  2325. if ((passes.loops && n.start >= passes.length) || at + n.length <= c.start || at >= c.end())
  2326. continue;
  2327. const auto nx = (float) tickToX ((double) at);
  2328. const auto nw = juce::jmax (rounded ? 2.0f : 1.0f, (float) (n.length * pixelsPerTick) - 1.0f);
  2329. if (nx > visible.getRight() || nx + nw < visible.getX())
  2330. continue;
  2331. const auto ny = body.getBottom() - ((float) n.key - bottomKey + 0.5f) / rows * body.getHeight() - noteHeight * 0.5f;
  2332. if (rounded)
  2333. g.fillRoundedRectangle (nx, ny, nw, noteHeight, juce::jmin (1.0f, noteHeight * 0.5f));
  2334. else
  2335. g.fillRect (nx, ny, nw, noteHeight);
  2336. }
  2337. }
  2338. }
  2339. veilIfMuted (c, r);
  2340. if (! liveLook || selected) // (Live: no outline around a clip; the selection keeps LYNX's)
  2341. paintClipOutline (g, r, base, selected, liveLook ? false : current);
  2342. // round 190ne (core/TrackClips.h): a track clip other clips share (a linked copy): a link at the name strip's end
  2343. if (song.patterns[(std::size_t) c.pattern].trackClip && r.getWidth() >= 44.0f && trackClipUseCount (c.pattern) > 1)
  2344. {
  2345. const auto title = juce::jmin (clipHeaderHeight (r), 14.0f);
  2346. if (title >= 8.0f)
  2347. icons::draw (g, Icon::link, juce::Rectangle<float> (r.getRight() - title - 2.0f, r.getY() + 1.0f, title - 1.0f, title - 1.0f).reduced (1.0f),
  2348. (liveLook ? liveLook->content : simpleLook ? simpleLook->content : clipTitleText (base)).withAlpha (0.85f));
  2349. }
  2350. }
  2351. {
  2352. const uitrace::Part tally (uitrace::part::batch);
  2353. smallClips.fill (g);
  2354. }
  2355. if (live)
  2356. paintLiveEnvelopeLanes (g, grid); // round 190oo (CS-19; nothing without automation clip lanes)
  2357. // round 190jr: the Simple layout's region loop handles (BandLab's circular arrow at a region's top right)
  2358. if (simpleHeaders)
  2359. for (int i = 0; i < (int) song.playlist.size(); ++i)
  2360. if (const auto& c = song.playlist[(std::size_t) i]; (c.kind == ClipKind::pattern || c.kind == ClipKind::audio)
  2361. && tickToX ((double) c.end()) >= (double) g.getClipBounds().getX()
  2362. && tickToX ((double) c.end()) - 16.0 <= (double) g.getClipBounds().getRight())
  2363. if (const auto handle = regionLoopHandle (i); ! handle.isEmpty() && g.getClipBounds().toFloat().intersects (handle))
  2364. {
  2365. const auto lit = (drag == Drag::regionLoop && i == regionloop::regionAt (song, loopTrack, loopStart, loopLike))
  2366. || (drag == Drag::none && hover.clip == i && handle.expanded (2.0f).contains (lastMouse.toFloat()));
  2367. if (lit)
  2368. {
  2369. g.setColour (colour::bg0.withAlpha (0.55f));
  2370. g.fillRoundedRectangle (handle.expanded (1.0f), 2.0f);
  2371. }
  2372. icons::draw (g, Icon::loop, handle, colour::textPrimary.withAlpha (lit ? 1.0f : 0.8f));
  2373. }
  2374. paintSimpleAutomation (g, grid); // round 190jr (nothing unless the Simple automation view is on)
  2375. if (song.performanceZoneEnd() > 0)
  2376. paintPerformance (g, grid);
  2377. if (engine.isLiveRecording())
  2378. paintLiveRecording (g);
  2379. // the clip under the mouse: outline, the grip of the edge it is on, its menu button
  2380. if (hover.clip >= 0 && hover.clip < (int) song.playlist.size() && drag == Drag::none)
  2381. {
  2382. const auto r = clipBounds (hover.clip).toFloat();
  2383. g.setColour (colour::textPrimary.withAlpha (isSelected (hover.clip) ? 0.0f : 0.55f));
  2384. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, 1.2f);
  2385. if (hover.target == gesture::Target::leftEdge || hover.target == gesture::Target::rightEdge)
  2386. {
  2387. const auto x = hover.target == gesture::Target::rightEdge ? r.getRight() - 4.0f : r.getX() + 1.0f;
  2388. g.setColour (colour::textPrimary);
  2389. g.fillRoundedRectangle (x, r.getY() + clipTitleHeight + 3.0f, 3.0f, juce::jmax (4.0f, r.getHeight() - clipTitleHeight - 6.0f), 1.5f);
  2390. }
  2391. if (const auto button = clipMenuButton (hover.clip); ! button.isEmpty())
  2392. {
  2393. const auto b = button.toFloat();
  2394. g.setColour (hover.target == gesture::Target::clipMenu ? colour::bg0.withAlpha (0.75f) : colour::bg0.withAlpha (0.45f));
  2395. g.fillRoundedRectangle (b, 2.0f);
  2396. icons::draw (g, Icon::chevronDown, b.reduced (1.0f), colour::textPrimary);
  2397. }
  2398. }
  2399. // round 190jz (issue #194): FL 2026's fade handles and tension circles: the hovered audio clip's, and the one whose
  2400. // fade is being dragged
  2401. if (const auto fadeClip = drag == Drag::fadeIn || drag == Drag::fadeOut || drag == Drag::fadeTension ? dragClip
  2402. : drag == Drag::none ? hover.clip : -1;
  2403. fadeClip >= 0 && fadeClip < (int) song.playlist.size() && song.playlist[(std::size_t) fadeClip].kind == ClipKind::audio)
  2404. paintFadeHandles (g, fadeClip);
  2405. // FL 2026's gain handle (round 166e): the hovered audio clip's, and the one being dragged
  2406. if (const auto gainClip = drag == Drag::clipGain ? dragClip : drag == Drag::none ? hover.clip : -1; gainClip >= 0 && gainClip < (int) song.playlist.size())
  2407. if (const auto handle = gainHandle (gainClip); ! handle.isEmpty())
  2408. {
  2409. const auto active = drag == Drag::clipGain || hover.target == gesture::Target::gainHandle;
  2410. juce::Path half;
  2411. half.addPieSegment (handle.getX(), handle.getY(), handle.getWidth(), handle.getWidth(), -juce::MathConstants<float>::halfPi,
  2412. juce::MathConstants<float>::halfPi, 0.0f);
  2413. g.setColour (active ? colour::textPrimary : colour::textPrimary.withAlpha (0.7f));
  2414. g.fillPath (half);
  2415. g.setColour (colour::bg0.withAlpha (0.8f));
  2416. g.strokePath (half, juce::PathStrokeType (1.0f));
  2417. }
  2418. paintPointSelection (g); // issue #207 (round 190lw): selected points and their rubber band
  2419. if (! rubberBand.isEmpty())
  2420. {
  2421. g.setColour (colour::selectionFill);
  2422. g.fillRect (rubberBand);
  2423. g.setColour (colour::selection);
  2424. g.drawRect (rubberBand);
  2425. }
  2426. if (drag == Drag::knife)
  2427. {
  2428. juce::Path cut;
  2429. cut.startNewSubPath (knifeFrom.toFloat());
  2430. cut.lineTo (knifeTo.toFloat());
  2431. juce::Path dashed;
  2432. const float dash[] = { 5.0f, 3.0f };
  2433. juce::PathStrokeType (1.5f).createDashedStroke (dashed, cut, dash, 2);
  2434. g.setColour (colour::textPrimary);
  2435. g.fillPath (dashed);
  2436. }
  2437. if (! cachePainting) // (the cached picture gets it from PlayheadCache::paint)
  2438. paintTrackSelectionDim (g);
  2439. paintMutedTracks (g);
  2440. if (! cachePainting) // round 190ig: FL's held clip titles, last before the playhead (as over the cached picture)
  2441. paintStickyTitles (g);
  2442. if (playheadTick >= 0.0 && ! cachePainting && ! gpuPlayhead.isShowing())
  2443. {
  2444. const juce::Graphics::ScopedSaveState trailClip (g);
  2445. if (g.reduceClipRegion (grid))
  2446. paintPlayheadTrail (g, (float) tickToX (playheadTick), grid); // (round 190im: as over the cached picture)
  2447. g.setColour (colour::playhead);
  2448. g.fillRect (juce::Rectangle<float> ((float) tickToX (playheadTick) - 0.5f, (float) grid.getY(), 1.5f, (float) grid.getHeight()));
  2449. }
  2450. }
  2451. // round 190rs: the band between the overview strip and the ruler (FL 2026: a lighter 2 px band), so the two read apart
  2452. if (g.clipRegionIntersects ({ headerWidth, rulerTop - overviewGap, getWidth() - headerWidth, overviewGap }))
  2453. {
  2454. g.setColour (colour::bg4);
  2455. g.fillRect (headerWidth, rulerTop - overviewGap, getWidth() - headerWidth, overviewGap);
  2456. }
  2457. // --- ruler (drawn in its own coordinates, below the toolbar) -----------------
  2458. {
  2459. const uitrace::Scope traceRuler ("Playlist ruler", false);
  2460. juce::Graphics::ScopedSaveState state (g);
  2461. g.setOrigin (0, rulerTop);
  2462. const auto ruler = juce::Rectangle<int> (headerWidth, 0, grid.getWidth(), timelineHeight);
  2463. g.setColour (colour::bg2);
  2464. g.fillRect (ruler);
  2465. g.setColour (colour::border);
  2466. g.fillRect (ruler.withTop (ruler.getBottom() - 1));
  2467. g.reduceClipRegion (ruler);
  2468. g.setFont (font (type::small));
  2469. if (song.hasLoop()) // the time selection
  2470. {
  2471. const auto lx0 = (float) tickToX ((double) song.loopStart), lx1 = (float) tickToX ((double) song.loopEnd);
  2472. const auto tint = song.loopOff ? colour::textSecondary : colour::accent;
  2473. g.setColour (tint.withAlpha (0.16f));
  2474. g.fillRect (juce::Rectangle<float> (lx0, 0.0f, lx1 - lx0, (float) timelineHeight));
  2475. g.setColour (tint.withAlpha (0.75f));
  2476. g.fillRect (juce::Rectangle<float> (lx0, 0.0f, lx1 - lx0, 4.0f));
  2477. }
  2478. const auto barPixels = bar * pixelsPerTick;
  2479. auto every = barPixels < 30.0 ? (barPixels < 10.0 ? 16 : 4) : 1; // numbers spaced further apart when zoomed out
  2480. // round 190ig (FM-25, Pattern layout): FL's ruler — a number every 1, 2, 4, 8… bars, the smallest step that keeps
  2481. // them 28 px apart (FL: every 2 bars at 15.6 px a bar), and every other one larger and brighter (FL's 1, 5, 9…)
  2482. const auto flRuler = flClipLook();
  2483. if (flRuler)
  2484. for (every = 1; barPixels * every < 28.0 && every < (1 << 16); every *= 2) {}
  2485. const auto rulerClip = g.getClipBounds(); // (the numbers reach 40 px right of their bar line)
  2486. for (const auto& b : song.barsBetween (juce::jmax ((std::int64_t) std::max (0.0, scrollTicks), (std::int64_t) xToTick (rulerClip.getX() - 44) - bar),
  2487. juce::jmin ((std::int64_t) xToTick (grid.getRight()), (std::int64_t) xToTick (rulerClip.getRight())) + 1))
  2488. {
  2489. if ((b.number - 1) % every != 0)
  2490. continue;
  2491. const auto x = (int) tickToX ((double) b.tick);
  2492. const auto major = flRuler && (b.number - 1) % juce::jmax (4, every * 2) == 0; // (FL: 1, 5, 9… at 1 and 2-bar steps)
  2493. g.setColour (colour::textDisabled);
  2494. g.drawVerticalLine (x, 12.0f, (float) timelineHeight);
  2495. g.setColour (major ? colour::textPrimary : colour::textSecondary);
  2496. if (flRuler)
  2497. g.setFont (font (major ? type::body : type::small, major));
  2498. textcache::drawText (g, juce::String (b.number), x + 3, 2, 40, timelineHeight - 4, juce::Justification::centredLeft);
  2499. }
  2500. // markers: small flag with the name; time signature changes show the fraction
  2501. g.setFont (font (type::caption, true));
  2502. for (const auto& m : song.markers())
  2503. {
  2504. const auto dragged = drag == Drag::marker && markerDragMoved && &m - song.markers().data() == markerDragIndex;
  2505. const auto x = (float) tickToX ((double) (dragged ? markerDragTick : m.tick));
  2506. if (x < (float) ruler.getX() - 200.0f || x > (float) ruler.getRight())
  2507. continue;
  2508. const auto label = markerLabel (m);
  2509. const auto width = (float) juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), label) + 8.0f;
  2510. const auto tag = juce::Rectangle<float> (x, (float) timelineHeight - 11.0f, width, 11.0f);
  2511. // recording markers (Start / Stop recording) in the accent colour, as the record button
  2512. const auto punch = m.action == Marker::punchIn || m.action == Marker::punchOut;
  2513. const auto acts = ! m.isSignature() && m.action != 0 && ! punch;
  2514. g.setColour (m.isSignature() ? colour::info : punch ? colour::accent : acts ? colour::automation : colour::warning);
  2515. g.fillRoundedRectangle (tag, 2.0f);
  2516. g.drawVerticalLine ((int) x, 0.0f, (float) timelineHeight);
  2517. g.setColour (colour::bg0);
  2518. textcache::drawText (g, label, tag.reduced (3.0f, 0.0f), juce::Justification::centredLeft, false);
  2519. }
  2520. // round 190hq (B11): the tempo markers (LYNX extra, core/TempoMarkers.h), in the automation colour of the tempo clip
  2521. // they write; "/" before a tempo the song glides into. The tag being dragged is drawn where it would land.
  2522. {
  2523. const auto marks = tempomarkers::list (song);
  2524. // round 190im: in the Pattern layout's FL look the tags take the tempo clip's own header colour and ink, as
  2525. // round 190ig draws that clip (FL: its Automation Clip channel's colour); the other looks keep the automation colour
  2526. auto tagFill = colour::automation, tagInk = colour::bg0;
  2527. if (const auto a = tempomarkers::automationIndex (song); ! marks.empty() && a >= 0 && flClipLook())
  2528. {
  2529. const auto* clip = tempomarkers::clipOf (song, a);
  2530. const auto look = theme::clipBody (juce::Colour (song.automations[(std::size_t) a].colour),
  2531. clip != nullptr ? trackColourIn (song, clip->track) : juce::Colour(), ClipKind::automation,
  2532. theme::ClipStyle::flTint);
  2533. tagFill = look.headerTop.interpolatedWith (look.headerBottom, 0.5f);
  2534. tagInk = look.ink;
  2535. }
  2536. for (int i = 0; i < (int) marks.size(); ++i)
  2537. {
  2538. const auto& m = marks[(std::size_t) i];
  2539. const auto x = (float) tickToX ((double) (i == tempoDragMarker && drag == Drag::tempoMarker ? tempoDragTick : m.tick));
  2540. if (x < (float) ruler.getX() - 200.0f || x > (float) ruler.getRight())
  2541. continue;
  2542. const auto label = (m.glide ? juce::String ("/ ") : juce::String()) + juce::String (tempomarkers::tempoText (m.bpm));
  2543. const auto width = (float) juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), label) + 8.0f;
  2544. const auto tag = juce::Rectangle<float> (x, (float) timelineHeight - 11.0f, width, 11.0f);
  2545. g.setColour (tagFill);
  2546. g.fillRoundedRectangle (tag, 2.0f);
  2547. g.drawVerticalLine ((int) x, 0.0f, (float) timelineHeight);
  2548. g.setColour (tagInk);
  2549. textcache::drawText (g, label, tag.reduced (3.0f, 0.0f), juce::Justification::centredLeft, false);
  2550. }
  2551. }
  2552. if (playheadTick >= 0.0 && ! cachePainting && ! gpuPlayhead.isShowing())
  2553. {
  2554. const auto x = (float) tickToX (playheadTick);
  2555. juce::Path tri;
  2556. tri.addTriangle (x - 6, 0, x + 6, 0, x, 9);
  2557. g.setColour (colour::playhead);
  2558. g.fillPath (tri);
  2559. }
  2560. }
  2561. // --- track headers -----------------------------------------------------
  2562. // FL's layout: the name on the left, a group header's fold arrow and the mute LED on the right; grouped
  2563. // tracks sit indented on a block in their header's colour; members of a folded group are thin rows
  2564. {
  2565. const uitrace::Scope traceHeaders ("Playlist headers", false);
  2566. updateMeterColumn(); // round 190w (a --snapshot paints before any frame step)
  2567. const auto headers = juce::Rectangle<int> (0, tracksTop(), headerWidth, grid.getHeight());
  2568. juce::Graphics::ScopedSaveState state (g);
  2569. if (g.reduceClipRegion (headers)) // (not repainted, e.g. the playhead's strip: nothing to draw; round 174e)
  2570. {
  2571. // (FL: contiguous plates, a dark line between rows; Live, round 190jn: its #242424 separators between rows)
  2572. const auto live = liveHeaders();
  2573. g.setColour (live ? liveLaneSeparator : flHeaders() ? colour::bg0 : colour::bg2);
  2574. g.fillRect (headers);
  2575. g.setFont (font (type::small));
  2576. auto colourOf = [&song] (int t) { return t >= 0 && t < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) t].colour : 0u; };
  2577. // group blocks first (behind the headers): from the header's top to the last member's bottom
  2578. for (int t = 0; t < tracks; ++t)
  2579. {
  2580. if (! noteedit::isGroupHeader (song, t))
  2581. continue;
  2582. const auto members = noteedit::groupMembers (song, t);
  2583. const auto last = members.empty() ? t : members.back();
  2584. const auto top = trackToY (t), bottom = trackToY (last) + heightOf (last);
  2585. if (top > headers.getBottom() || bottom < headers.getY())
  2586. continue;
  2587. auto block = colour::bg3;
  2588. if (const auto c = colourOf (t); c != 0)
  2589. block = block.interpolatedWith (tame (juce::Colour (c)), 0.28f);
  2590. // round 190jf (B17): a nested folder's block starts at its header's indent, over its parent's block
  2591. const auto x0 = noteedit::folderDepth (song, t) > 0 ? (float) headerIndent (song, t) : 0.0f;
  2592. if (flHeaders()) // FL (round 190ig, FM-23): the group's own colour, its left side rounded (radius 6)
  2593. {
  2594. g.setColour (flHeaderFill (colourOf (t)));
  2595. g.fillRoundedRectangle (juce::Rectangle<float> (x0, (float) top, (float) (headerWidth - rightColumn()) - x0, (float) (bottom - top) - 1.0f), 6.0f);
  2596. g.fillRect (juce::Rectangle<float> (x0 + 8.0f, (float) top, (float) (headerWidth - rightColumn()) - 8.0f - x0, (float) (bottom - top) - 1.0f));
  2597. continue;
  2598. }
  2599. g.setColour (block);
  2600. g.fillRoundedRectangle (juce::Rectangle<float> (x0 + 1.0f, (float) top + 1.0f, (float) headerWidth - 2.0f - x0, (float) (bottom - top) - 2.0f), radius::md);
  2601. }
  2602. // issue #170 (round 190ib): with the tracks linked to the mixer, a track that only repeats a track above it
  2603. // says whose insert it plays through
  2604. const auto repeats = linkedHeaders() ? autolink::repeatedTracks (song) : std::vector<int>();
  2605. // round 190jc (design190ia SG-2): the Simple headers stop after the real tracks; the drop lane's header is a
  2606. // round "+" (FL Studio Mobile's add button under its tracks), the New-track chooser
  2607. const auto headerRows = paintedRows();
  2608. const auto addRow = simpleHeaders ? dropLaneTrack() : -1;
  2609. for (int t = 0; t < headerRows; ++t)
  2610. {
  2611. const auto y = trackToY (t);
  2612. const auto trackHeight = heightOf (t);
  2613. if (y > headers.getBottom() || y + trackHeight < headers.getY())
  2614. continue;
  2615. if (t == addRow)
  2616. {
  2617. if (const auto add = simpleAddButton().toFloat(); add.getWidth() >= 12.0f)
  2618. {
  2619. const auto lit = hover.header && hover.addTrack;
  2620. g.setColour (lit ? colour::bg5 : colour::bg4);
  2621. g.fillEllipse (add);
  2622. g.setColour (lit ? colour::textPrimary : colour::textSecondary);
  2623. const auto arm = juce::jmin (add.getWidth() * 0.18f, 9.0f);
  2624. const auto c = add.getCentre();
  2625. const auto stroke = ui::simplelook::px (2.0f, 2.5f);
  2626. g.fillRoundedRectangle (juce::Rectangle<float> (2.0f * arm, stroke).withCentre (c), stroke * 0.5f);
  2627. g.fillRoundedRectangle (juce::Rectangle<float> (stroke, 2.0f * arm).withCentre (c), stroke * 0.5f);
  2628. }
  2629. continue;
  2630. }
  2631. if (noteedit::isFoldedAway (song, t))
  2632. continue; // the group block shows through: a thin row, as FL draws a folded group
  2633. if (projection.isChild (t)) // round 190jq (issue #191.3): an automation clip lane under its owner
  2634. {
  2635. if (trackHeight > 0)
  2636. paintClipLaneHeader (g, t, y, trackHeight, hover.header && hover.track == t);
  2637. continue;
  2638. }
  2639. const auto muted = song.isTrackMuted (t);
  2640. const auto custom = t < (int) song.playlistTracks.size() && ! song.playlistTracks[(std::size_t) t].name.empty();
  2641. const auto hovered = hover.header && hover.track == t;
  2642. const auto groupHead = noteedit::isGroupHeader (song, t);
  2643. const auto left = (float) headerIndent (song, t); // (round 190jf: one step per folder level)
  2644. auto plate = muted ? colour::bg2 : colour::bg3;
  2645. const auto trackColour = colourOf (t);
  2646. if (trackColour != 0) // the track's colour (FL projects colour their track headers by group)
  2647. plate = plate.interpolatedWith (tame (juce::Colour (trackColour)), muted ? 0.22f : (groupHead ? 0.62f : 0.5f));
  2648. if (hovered)
  2649. plate = plate.interpolatedWith (colour::bg5, 0.6f);
  2650. if (simpleHeaders && isTrackSelected (t)) // round 190jc (SG-4): the selected plate is lifted
  2651. plate = plate.interpolatedWith (colour::bg6, 0.25f);
  2652. const auto fl = flHeaders() && simpleInsert (t) <= 0;
  2653. // round 190jn (CL-17, live-arrangement.png 1324..1625): Live's header row — the name box in the track colour
  2654. // up to the controls, a 2 px separator, the controls panel (#363636; #464646 for the selected track), all
  2655. // the lane's height above its 2 px separator
  2656. auto liveNameRight = 0.0f;
  2657. if (live)
  2658. {
  2659. auto leftmost = trackLed (t).getX();
  2660. for (const auto& other : { trackArm (t), trackArrow (t), trackAudition (t), trackInput (t) })
  2661. if (! other.isEmpty())
  2662. leftmost = juce::jmin (leftmost, other.getX());
  2663. liveNameRight = (float) leftmost - 6.0f;
  2664. }
  2665. const auto plateArea = live ? juce::Rectangle<float> (left, (float) y, juce::jmax (8.0f, liveNameRight - left), (float) trackHeight - 2.0f)
  2666. : fl ? juce::Rectangle<float> (left, (float) y, (float) (headerWidth - rightColumn()) - left, (float) trackHeight - 1.0f)
  2667. : juce::Rectangle<float> (left, (float) y + 1.0f, (float) (headerWidth - rightColumn()) - 2.0f - left, (float) trackHeight - 3.0f);
  2668. if (live)
  2669. {
  2670. plate = trackColour != 0 ? juce::Colour (trackColour).withAlpha (1.0f) : juce::Colour (0xffa9a9a9); // (Live's grey, palette 41)
  2671. g.setColour (isTrackSelected (t) ? theme::livelook::raised : theme::livelook::surface);
  2672. g.fillRect (juce::Rectangle<float> (plateArea.getRight() + 2.0f, (float) y, (float) headerWidth - plateArea.getRight() - 2.0f, plateArea.getHeight()));
  2673. g.setColour (plate);
  2674. g.fillRect (plateArea);
  2675. }
  2676. else if (fl)
  2677. {
  2678. // FL (round 190ig, FM-23, fl-playlist-zoom-audioclips.png 370,240,472,1000): the plate filled with the
  2679. // track's own colour (FL's grey #485156 when it has none), contiguous; a group header's left side rounded
  2680. // (round 190qw: the Soft look keeps the dark plate tinted with the track colour, as 0.1.29 drew it)
  2681. if (! theme::soft())
  2682. {
  2683. plate = flHeaderFill (trackColour);
  2684. if (muted)
  2685. plate = plate.interpolatedWith (colour::bg1, 0.55f);
  2686. if (hovered)
  2687. plate = plate.brighter (0.12f);
  2688. }
  2689. g.setColour (plate);
  2690. if (groupHead)
  2691. {
  2692. g.fillRoundedRectangle (plateArea, 6.0f);
  2693. g.fillRect (plateArea.withTrimmedLeft (8.0f));
  2694. }
  2695. else
  2696. g.fillRect (plateArea);
  2697. }
  2698. else
  2699. {
  2700. g.setColour (plate);
  2701. g.fillRoundedRectangle (plateArea, radius::sm);
  2702. }
  2703. // round 190w: FL's track header level (View › Show levels on audio / instrument tracks): a stereo peak
  2704. // meter in a column right of the plate, the mixer track's level with its hold line, as FL 2026 draws it
  2705. if (const auto insert = meteredInsertOf (t); insert >= 0 && meterColumn > 0)
  2706. {
  2707. const auto well = juce::Rectangle<int> (headerWidth - rightColumn(), y + 2, rightColumn() - 2, trackHeight - 5);
  2708. g.setColour (colour::bg1);
  2709. g.fillRect (well);
  2710. const auto found = headerLevels.find (insert);
  2711. for (int side = 0; side < 2; ++side)
  2712. {
  2713. const auto bar = juce::Rectangle<int> (well.getX() + 1 + side * (well.getWidth() / 2), well.getY() + 1,
  2714. well.getWidth() / 2 - 1, well.getHeight() - 2);
  2715. if (found == headerLevels.end())
  2716. continue;
  2717. const auto& m = found->second[(std::size_t) side];
  2718. auto position = [] (float gain) { // the Mixer's scale: -60..+6 dB
  2719. return juce::jlimit (0.0f, 1.0f, (juce::Decibels::gainToDecibels (gain, -60.0f) + 60.0f) / 66.0f);
  2720. };
  2721. const auto h = (int) (position (m.level) * (float) bar.getHeight());
  2722. g.setColour (colour::meterLow); // (FL's header meter stays green at every level)
  2723. g.fillRect (bar.withTop (bar.getBottom() - h));
  2724. if (m.peak > 0.001f) // the hold line
  2725. {
  2726. const auto py = bar.getBottom() - (int) (position (m.peak) * (float) bar.getHeight());
  2727. g.setColour (colour::meterLow);
  2728. g.fillRect (bar.getX(), juce::jmax (bar.getY(), py - 1), bar.getWidth(), 1);
  2729. }
  2730. }
  2731. }
  2732. // FL's activity column (round 190ig, FM-28, fl-playing.png 465,330,480,400): lit in a light tint of the track's
  2733. // colour while a clip of the track plays
  2734. if (fl && t < (int) activityShown.size() && activityShown[(std::size_t) t] != 0)
  2735. {
  2736. const auto c = flHeaderFill (trackColour);
  2737. // (round 190im, DC-7: the brightness follows the level, steps 1..4; FL's lit strips are brightest loud)
  2738. const auto step = juce::jlimit (1, 4, (int) activityShown[(std::size_t) t]);
  2739. g.setColour (juce::Colour::fromHSV (c.getHue(), c.getSaturation() * 0.8f, 0.55f + 0.15f * (float) (step - 1), 1.0f));
  2740. g.fillRect (headerWidth - trackhdr::selectionStripWidth + 1, y + 1, trackhdr::selectionStripWidth - 2, juce::jmax (2, trackHeight - 3));
  2741. }
  2742. if (isTrackSelected (t) && simpleHeaders) // the Simple headers (round 190jc, SG-4): a 1 px accent outline
  2743. {
  2744. g.setColour (colour::accent);
  2745. g.drawRoundedRectangle (plateArea.reduced (0.5f), radius::md, 1.0f);
  2746. }
  2747. else if (isTrackSelected (t) && ! live) // FL (live check 190gu B1): an outlined box in the selection strip
  2748. {
  2749. // as FL draws it (rollup 0.1.28, coordinator): a clearly visible lime outline, the whole 9 px column, the
  2750. // whole row's height, on whole pixels (a 1 px line at half-pixel places blurred into a faint box)
  2751. const auto strip = juce::Rectangle<int> (headerWidth - trackhdr::selectionStripWidth, y + 1,
  2752. trackhdr::selectionStripWidth, juce::jmax (4, trackHeight - 2));
  2753. g.setColour (selectionStripLime);
  2754. g.drawRect (strip, 2);
  2755. }
  2756. const auto led = trackLed (t).toFloat();
  2757. auto textRight = led.getX() - 2.0f;
  2758. if (simpleHeaders)
  2759. paintSimpleHeaderControls (g, t, plateArea, hovered);
  2760. else if (simpleInsert (t) > 0)
  2761. {
  2762. // the Simple headers (round 184a): M and S buttons on the track's insert, a colour bar, and on tall
  2763. // rows the insert's volume, pan and effects. Round 190gz: a linked track's header (FL's layout, the
  2764. // project's "Link Playlist tracks to mixer tracks") has the same M, S, volume and pan, no colour bar
  2765. // (FL tints the plate) and no "+FX"; its M is lit by the Playlist track's own mute too
  2766. if (simpleHeaders && trackColour != 0)
  2767. {
  2768. g.setColour (juce::Colour (trackColour));
  2769. g.fillRoundedRectangle (plateArea.withWidth (4.0f).reduced (0.0f, 2.0f).translated (isTrackSelected (t) ? 4.0f : 0.0f, 0.0f), 1.5f);
  2770. }
  2771. const auto insert = simpleInsert (t);
  2772. const auto* m = insert > 0 ? &song.mixer[(std::size_t) insert] : nullptr;
  2773. const auto button = [&g] (juce::Rectangle<float> r, const char* text, bool on, juce::Colour onColour, bool lit) {
  2774. g.setColour (on ? onColour : (lit ? colour::bg6 : colour::bg4));
  2775. g.fillRoundedRectangle (r, radius::sm);
  2776. g.setColour (on ? colour::bg0 : (lit ? colour::textPrimary : colour::textSecondary));
  2777. g.setFont (font (type::caption, true));
  2778. g.drawText (text, r, juce::Justification::centred, false);
  2779. };
  2780. button (led, "M", m != nullptr ? (m->muted || (! simpleHeaders && muted)) : muted, colour::warning, hovered && hover.led);
  2781. if (const auto solo = trackSolo (t).toFloat(); ! solo.isEmpty() && m != nullptr)
  2782. {
  2783. button (solo, "S", m->solo, colour::info, hovered && hover.solo);
  2784. textRight = solo.getX() - 2.0f;
  2785. }
  2786. if (auto menuArea = simpleAutoMenu (t).toFloat(); ! menuArea.isEmpty() && m != nullptr)
  2787. {
  2788. // round 190jr, the Simple automation view (BandLab): the row's parameter as a menu field
  2789. const auto target = simpleAutoTarget (t);
  2790. g.setColour (hovered && menuArea.contains (lastMouse.toFloat()) ? colour::bg6 : colour::bg4);
  2791. g.fillRoundedRectangle (menuArea, radius::sm);
  2792. g.setColour (colour::textPrimary);
  2793. g.setFont (font (type::caption, true));
  2794. const auto name = target.kind == AutomationTargetKind::mixerVolume ? tr ("Volume")
  2795. : target.kind == AutomationTargetKind::mixerPan ? tr ("Pan")
  2796. : describeAutomationTarget (engine, target);
  2797. g.drawText (name, menuArea.reduced (8.0f, 0.0f).withTrimmedRight (14.0f), juce::Justification::centredLeft, true);
  2798. icons::draw (g, Icon::chevronDown, menuArea.removeFromRight (18.0f).reduced (3.0f), colour::textSecondary);
  2799. if (simpleAutoLane (t) >= 0) // the track has automation for it: BandLab's small mark beside the header
  2800. {
  2801. g.setColour (colour::automation.brighter (0.4f));
  2802. g.fillEllipse (juce::Rectangle<float> (5.0f, 5.0f).withCentre ({ menuArea.getX() - 5.0f, menuArea.getCentreY() }));
  2803. }
  2804. }
  2805. else if (const auto bar = trackVolume (t).toFloat(); ! bar.isEmpty() && m != nullptr)
  2806. {
  2807. // volume: a bar filled up to the fader position, a tick at 0 dB
  2808. g.setColour (colour::bg0);
  2809. g.fillRoundedRectangle (bar.withSizeKeepingCentre (bar.getWidth(), 6.0f), 3.0f);
  2810. g.setColour ((hovered && hover.volume) || (levelDrag == 1 && levelInsert == insert) ? colour::accentHover : colour::accent);
  2811. g.fillRoundedRectangle (bar.withSizeKeepingCentre (bar.getWidth(), 6.0f).withWidth (juce::jmax (6.0f, bar.getWidth() * m->volume)), 3.0f);
  2812. g.setColour (colour::textSecondary.withAlpha (0.6f));
  2813. g.fillRect (bar.getX() + bar.getWidth() * unityFader - 0.5f, bar.getY(), 1.0f, bar.getHeight());
  2814. // pan: a small knob, its arc from the top
  2815. const auto pan = trackPan (t).toFloat();
  2816. const auto knob = pan.getWidth() * 0.5f - 1.0f; // (7 px on the Simple headers, 6 on the linked ones)
  2817. g.setColour (colour::bg4);
  2818. g.fillEllipse (pan.reduced (1.0f));
  2819. juce::Path arc;
  2820. const auto angle = m->pan * 2.356f;
  2821. arc.addCentredArc (pan.getCentreX(), pan.getCentreY(), knob, knob, 0.0f, juce::jmin (0.0f, angle), juce::jmax (0.0f, angle), true);
  2822. g.setColour ((hovered && hover.pan) || (levelDrag == 2 && levelInsert == insert) ? colour::accentHover : colour::info);
  2823. g.strokePath (arc, juce::PathStrokeType (2.0f));
  2824. g.setColour (colour::textPrimary);
  2825. g.drawLine (pan.getCentreX(), pan.getCentreY(), pan.getCentreX() + (knob - 1.0f) * std::sin (angle),
  2826. pan.getCentreY() - (knob - 1.0f) * std::cos (angle), 1.4f);
  2827. // "+FX", with the insert's effect count
  2828. if (const auto fx = trackFx (t).toFloat(); ! fx.isEmpty())
  2829. {
  2830. const auto count = (int) m->effects.size();
  2831. g.setColour (hovered && hover.fx ? colour::bg6 : colour::bg4);
  2832. g.fillRoundedRectangle (fx, radius::sm);
  2833. g.setColour (count > 0 ? colour::accent : colour::textSecondary);
  2834. g.setFont (font (type::caption, true));
  2835. g.drawText (count > 0 ? "FX " + juce::String (count) : juce::String ("+ FX"), fx, juce::Justification::centred, false);
  2836. }
  2837. }
  2838. }
  2839. else if (live && liveTakeLane (t))
  2840. textRight = plateArea.getRight() - 2.0f; // round 190oo (CS-20): Live's take lane has no activator / number
  2841. else if (live)
  2842. {
  2843. // Live's track activator (live-arrangement.png x 1509..1554, y 187..199): 44 x 11 px #ffad56 in a 1 px
  2844. // #111111 frame, the track number in #070707; off (the track muted): the #1e1e1e well, its number #696969
  2845. // (captured by round 190jn, shots/ref/live-mixer-solo-deactivated.png: Mello deactivated); no hover state
  2846. const auto box = trackLed (t);
  2847. g.setColour (theme::livelook::knobRing);
  2848. g.fillRect (box);
  2849. g.setColour (muted ? theme::livelook::well : theme::livelook::on);
  2850. g.fillRect (box.reduced (1));
  2851. g.setColour (muted ? juce::Colour (0xff696969) : theme::livelook::ink);
  2852. g.setFont (font (type::small));
  2853. textcache::drawText (g, juce::String (t + 1), box, juce::Justification::centred, false);
  2854. textRight = plateArea.getRight() - 2.0f;
  2855. }
  2856. else if (flHeaders()) // FL's LED (round 190ig): 11 px, a dark rim
  2857. {
  2858. g.setColour (colour::bg0.withAlpha (0.7f));
  2859. g.fillEllipse (led.withSizeKeepingCentre (11.0f, 11.0f));
  2860. g.setColour (muteLed (muted));
  2861. g.fillEllipse (led.withSizeKeepingCentre (8.0f, 8.0f));
  2862. if (hovered && hover.led)
  2863. {
  2864. g.setColour (colour::textPrimary.withAlpha (0.7f));
  2865. g.drawEllipse (led.withSizeKeepingCentre (12.0f, 12.0f), 1.0f);
  2866. }
  2867. }
  2868. else
  2869. {
  2870. g.setColour (muteLed (muted));
  2871. g.fillEllipse (led.withSizeKeepingCentre (8.0f, 8.0f));
  2872. if (hovered && hover.led) // the LED is a button: ring it
  2873. {
  2874. g.setColour (colour::textPrimary.withAlpha (0.7f));
  2875. g.drawEllipse (led.withSizeKeepingCentre (12.0f, 12.0f), 1.0f);
  2876. }
  2877. if (t < (int) repeats.size() && repeats[(std::size_t) t] >= 0 && trackHeight >= 12)
  2878. {
  2879. // "→ 1": plays through Track 1's insert (the hint bar says it in full)
  2880. const auto tag = juce::String::fromUTF8 ("\xe2\x86\x92 ") + juce::String (repeats[(std::size_t) t] + 1);
  2881. const auto box = juce::Rectangle<float> (led.getX() - 30.0f, led.getCentreY() - 8.0f, 28.0f, 16.0f);
  2882. g.setColour (colour::textSecondary);
  2883. g.setFont (font (type::caption));
  2884. g.drawText (tag, box, juce::Justification::centredRight, false);
  2885. textRight = box.getX() - 2.0f;
  2886. }
  2887. }
  2888. paintInserts (g, t, hovered); // issue #154: the insert effects column (LYNX extra)
  2889. // a take lane's audition button (round 177c): a small speaker, lit while this lane plays instead of the comp
  2890. if (const auto box = trackAudition (t); ! box.isEmpty())
  2891. {
  2892. const auto on = song.auditionLane == t;
  2893. const auto b = box.toFloat().withSizeKeepingCentre (10.0f, 10.0f);
  2894. g.setColour (on ? colour::accent : (hovered && hover.audition ? colour::textPrimary : colour::textSecondary));
  2895. juce::Path speaker;
  2896. const auto cy = b.getCentreY();
  2897. speaker.startNewSubPath (b.getX(), cy - 1.8f);
  2898. speaker.lineTo (b.getX() + 2.2f, cy - 1.8f);
  2899. speaker.lineTo (b.getX() + 5.0f, cy - 4.2f);
  2900. speaker.lineTo (b.getX() + 5.0f, cy + 4.2f);
  2901. speaker.lineTo (b.getX() + 2.2f, cy + 1.8f);
  2902. speaker.lineTo (b.getX(), cy + 1.8f);
  2903. speaker.closeSubPath();
  2904. g.fillPath (speaker);
  2905. juce::Path wave;
  2906. wave.addCentredArc (b.getX() + 5.0f, cy, 3.6f, 3.6f, 0.0f, 0.5f, juce::MathConstants<float>::pi - 0.5f, true);
  2907. g.strokePath (wave, juce::PathStrokeType (1.1f));
  2908. }
  2909. // an audio track's record arm (and, on tall rows, input) button: red while its mixer track is armed (FL 2026)
  2910. if (const auto armBox = trackArm (t); ! armBox.isEmpty())
  2911. {
  2912. const auto insert = trackmodes::armableInsert (song, t);
  2913. const auto armed = engine.isInsertArmed (insert);
  2914. const auto b = armBox.toFloat();
  2915. const auto lit = hovered && hover.arm;
  2916. if (armed)
  2917. {
  2918. g.setColour (colour::record);
  2919. g.fillEllipse (b.withSizeKeepingCentre (10.0f, 10.0f));
  2920. }
  2921. else
  2922. {
  2923. g.setColour ((lit ? colour::textPrimary : colour::textSecondary).withAlpha (muted ? 0.5f : 1.0f));
  2924. g.fillEllipse (b.withSizeKeepingCentre (4.0f, 4.0f));
  2925. }
  2926. g.setColour (armed ? colour::record.brighter (lit ? 0.4f : 0.0f) : (lit ? colour::textPrimary : colour::textSecondary.withAlpha (0.7f)));
  2927. g.drawEllipse (b.withSizeKeepingCentre (10.0f, 10.0f), 1.2f);
  2928. textRight = b.getX() - 2.0f;
  2929. if (const auto inBox = trackInput (t); ! inBox.isEmpty())
  2930. {
  2931. // "Audio input source": an arrow into a bar, lit when the mixer track has an input
  2932. const auto r = inBox.toFloat().reduced (1.5f);
  2933. const auto hasInput = song.mixer[(std::size_t) insert].inputChannel >= 0;
  2934. g.setColour (hovered && hover.input ? colour::textPrimary : (hasInput ? colour::accent : colour::textSecondary));
  2935. juce::Path in;
  2936. const auto cy = r.getCentreY();
  2937. in.startNewSubPath (r.getX(), cy);
  2938. in.lineTo (r.getRight() - 3.5f, cy);
  2939. in.startNewSubPath (r.getRight() - 6.5f, cy - 3.0f);
  2940. in.lineTo (r.getRight() - 3.5f, cy);
  2941. in.lineTo (r.getRight() - 6.5f, cy + 3.0f);
  2942. g.strokePath (in, juce::PathStrokeType (1.2f));
  2943. g.fillRect (juce::Rectangle<float> (r.getRight() - 1.5f, r.getY(), 1.3f, r.getHeight()));
  2944. textRight = r.getX() - 2.0f;
  2945. }
  2946. }
  2947. if (const auto arrow = trackArrow (t); ! arrow.isEmpty())
  2948. {
  2949. const auto collapsed = t < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) t].collapsed;
  2950. const auto a = arrow.toFloat().withSizeKeepingCentre (8.0f, 5.0f);
  2951. juce::Path tri;
  2952. if (collapsed) // folded: points down (FL), open: up
  2953. tri.addTriangle (a.getX(), a.getY(), a.getRight(), a.getY(), a.getCentreX(), a.getBottom());
  2954. else
  2955. tri.addTriangle (a.getX(), a.getBottom(), a.getRight(), a.getBottom(), a.getCentreX(), a.getY());
  2956. g.setColour (hovered && hover.arrow ? colour::textPrimary : colour::textSecondary);
  2957. g.fillPath (tri);
  2958. textRight = juce::jmin (textRight, (float) arrow.getX());
  2959. }
  2960. if (const auto box = trackAudition (t); ! box.isEmpty())
  2961. textRight = juce::jmin (textRight, (float) box.getX());
  2962. // round 190oo (CS-24): the insert this Simple header acts on also plays other tracks: a link mark on a small
  2963. // plate, its ink black or white, whichever reads better on it (>= 4.58:1, simplelook::inkOn)
  2964. if (const auto mark = trackSharedMark (t); ! mark.isEmpty())
  2965. {
  2966. const auto box = mark.toFloat();
  2967. const auto fill = plate.overlaidWith (colour::textSecondary.withAlpha (hovered && hover.shared ? 0.36f : 0.24f));
  2968. g.setColour (fill);
  2969. g.fillRoundedRectangle (box, radius::sm);
  2970. icons::draw (g, Icon::link, box.reduced (2.0f), ui::simplelook::inkOn (fill));
  2971. textRight = juce::jmin (textRight, box.getX() - 2.0f);
  2972. }
  2973. // the track's icon before its name, as FL's track header shows it (round 168h)
  2974. auto textLeft = (int) left + (simpleHeaders ? 12 : 6);
  2975. // the Simple headers: the name in the first row, beside the buttons
  2976. const auto nameHeight = ! trackVolume (t).isEmpty() ? juce::jmin (trackHeight, (int) led.getBottom() - y + 4) : trackHeight;
  2977. // round 177b: the lanes' fold arrow (points down while they show) and, on hover, "+A" (add a lane)
  2978. if (const auto laneArrow = trackLaneArrow (t); ! laneArrow.isEmpty())
  2979. {
  2980. const auto folded = song.playlistTracks[(std::size_t) t].lanesFolded;
  2981. const auto a = laneArrow.toFloat().withSizeKeepingCentre (folded ? 5.0f : 8.0f, folded ? 8.0f : 5.0f);
  2982. juce::Path tri;
  2983. if (folded) // points right
  2984. tri.addTriangle (a.getX(), a.getY(), a.getX(), a.getBottom(), a.getRight(), a.getCentreY());
  2985. else
  2986. tri.addTriangle (a.getX(), a.getY(), a.getRight(), a.getY(), a.getCentreX(), a.getBottom());
  2987. g.setColour (hovered && laneArrow.contains (lastMouse) ? colour::textPrimary : colour::automation.brighter (0.2f));
  2988. g.fillPath (tri);
  2989. textLeft = laneArrow.getRight() + 3;
  2990. }
  2991. if (const auto plus = trackAddLane (t); hovered && ! plus.isEmpty())
  2992. {
  2993. const auto lit = plus.contains (lastMouse);
  2994. g.setColour (lit ? colour::automation.withAlpha (0.35f) : colour::bg2.withAlpha (0.8f));
  2995. g.fillRoundedRectangle (plus.toFloat(), radius::sm);
  2996. g.setColour (lit ? colour::textPrimary : colour::automation.brighter (0.3f));
  2997. g.setFont (font (type::caption, true));
  2998. textcache::drawText (g, "+A", plus, juce::Justification::centred);
  2999. textRight = juce::jmin (textRight, (float) plus.getX());
  3000. }
  3001. // issue #222 (round 190ng): FL 2026 also draws a track's icon big in the middle of a tall header (captured
  3002. // 2026-11-19 with Alt+wheel zoom: rows 56 / 68 / 80 px none, 92 / 104 / 116 px a centred icon of half the
  3003. // row's height in the plate's colour x 0.85); the small icon stays where it is (core/TrackIconScale.h)
  3004. // (#222 follow-up, round 190nq: with the LYNX extra's insert effects column shown, the icon is centred in the
  3005. // name / controls part of the header, the column left out: trackiconscale::bigIconArea)
  3006. const auto iconArea = trackiconscale::bigIconArea (plateArea.getX(), plateArea.getWidth(), (float) insertsColumn());
  3007. if (! live && ! simpleHeaders)
  3008. if (const auto big = trackiconscale::bigIconSize (trackHeight, (int) iconArea.second); big > 0)
  3009. if (const auto icon = trackicons::iconFor (t < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) t].icon : 0);
  3010. icon != trackicons::Icon::none)
  3011. {
  3012. const auto box = juce::Rectangle<float> ((float) big, (float) big)
  3013. .withCentre ({ iconArea.first + iconArea.second * 0.5f, (float) y + (float) trackHeight * 0.5f });
  3014. ui::drawTrackIcon (g, icon, box, trackiconscale::shade (plate));
  3015. }
  3016. // round 190ne (core/TrackClips.h, LYNX's own marks): a track whose clips own their notes (a note) and a bus
  3017. // track (lines joining into one), on a small plate left of the name's end
  3018. if (trackHeight >= 14 && textRight - (float) textLeft > 52.0f)
  3019. if (const auto mark = trackclips::owns (song, t) ? Icon::note : trackclips::isBusTrack (song, t) ? Icon::blend : Icon::none; mark != Icon::none)
  3020. {
  3021. const auto size = (float) juce::jmin (14, trackHeight - 4);
  3022. const auto box = juce::Rectangle<float> (textRight - size - 2.0f, (float) led.getCentreY() - size * 0.5f, size, size);
  3023. g.setColour ((mark == Icon::note ? colour::accent : colour::textSecondary).withAlpha (muted ? 0.12f : 0.24f));
  3024. g.fillRoundedRectangle (box, radius::sm);
  3025. icons::draw (g, mark, box.reduced (2.0f), muted ? colour::textDisabled : colour::textPrimary.withAlpha (0.9f));
  3026. textRight = box.getX() - 2.0f;
  3027. }
  3028. const auto flTall = fl && trackHeight >= flTallHeader;
  3029. if (fl)
  3030. {
  3031. // FL: the icon left of the LED and its buttons (on a tall track in their bottom row); the name at the
  3032. // top left on a tall track; "..." at the bottom left (FL's header grip)
  3033. if (const auto icon = trackicons::iconFor (t < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) t].icon : 0);
  3034. icon != trackicons::Icon::none && trackHeight >= 14)
  3035. {
  3036. const auto size = (float) juce::jmin (14, trackHeight - 4);
  3037. const auto box = juce::Rectangle<float> (textRight - size - 1.0f, (float) led.getCentreY() - size * 0.5f, size, size);
  3038. ui::drawTrackIcon (g, icon, box, muted ? colour::textDisabled : flHeaderInk (plate).withMultipliedAlpha (0.85f));
  3039. if (! flTall)
  3040. textRight = box.getX() - 2.0f;
  3041. }
  3042. if (flTall)
  3043. {
  3044. g.setColour (flHeaderInk (plate).withMultipliedAlpha (0.6f));
  3045. for (int k = 0; k < 3; ++k)
  3046. g.fillRect (juce::Rectangle<float> (left + 6.0f + (float) k * 3.0f, (float) (y + trackHeight) - 7.0f, 1.5f, 1.5f));
  3047. }
  3048. g.setColour (muted ? colour::textDisabled : flHeaderInk (plate));
  3049. const auto nameFont = labelFont (type::body, true); // (round 190je: condensed with FL-style labels on)
  3050. g.setFont (nameFont);
  3051. const auto name = custom ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()) : tr ("Track {0}", { juce::String (t + 1) });
  3052. auto nameLeft = (int) left + 6;
  3053. // round 190rs (G-06, FL 2026 pairs/92b): an instrument track without an icon of its own carries a mark
  3054. // before its name, as FL's (LYNX's own keyboard glyph)
  3055. if (t < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) t].mode == PlaylistTrackMode::instrument
  3056. && trackicons::iconFor (song.playlistTracks[(std::size_t) t].icon) == trackicons::Icon::none && trackHeight >= 16)
  3057. {
  3058. const auto size = (float) juce::jmin (12, trackHeight - 6);
  3059. const auto midY = flTall ? (float) y + 11.0f : (float) y + (float) (trackHeight - 1) * 0.5f;
  3060. if (const auto mark = juce::Rectangle<float> ((float) nameLeft, midY - size * 0.5f, size, size);
  3061. g.clipRegionIntersects (mark.getSmallestIntegerContainer())) // (a playhead column leaves this static mark alone)
  3062. ui::drawTrackIconCached (g, trackicons::Icon::keyboard, mark, muted ? colour::textDisabled : flHeaderInk (plate).withMultipliedAlpha (0.85f));
  3063. nameLeft += (int) size + 3;
  3064. }
  3065. const auto nameRight = flTall ? (int) plateArea.getRight() - 4 : (int) textRight - 2;
  3066. const auto nameBox = flTall ? juce::Rectangle<int> (nameLeft, y + 3, juce::jmax (8, nameRight - nameLeft), 16)
  3067. : juce::Rectangle<int> (nameLeft, y, juce::jmax (8, nameRight - nameLeft), trackHeight - 1);
  3068. // round 190qw: a name a little too long is set narrower first (down to 80 %, as FL's condensed header face),
  3069. // then FL's middle ellipsis
  3070. auto fitFont = nameFont;
  3071. if (const auto natural = textcache::stringWidth (nameFont, name); natural > (float) nameBox.getWidth())
  3072. fitFont = nameFont.withHorizontalScale (juce::jmax (0.8f, (float) nameBox.getWidth() / natural));
  3073. g.setFont (fitFont);
  3074. textcache::drawText (g, theme::fitMiddle (name, fitFont, (float) nameBox.getWidth()), nameBox, juce::Justification::centredLeft, false);
  3075. }
  3076. else if (const auto icon = live ? trackicons::Icon::none // (Live's name box has no icon)
  3077. : simpleHeaders ? simpleTrackIcon (song, t)
  3078. : trackicons::iconFor (t < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) t].icon : 0);
  3079. icon != trackicons::Icon::none && trackHeight >= 14)
  3080. {
  3081. // round 190jc (SG-3): a Simple track's type icon, BandLab's, in the track's colour (kept readable on its plate)
  3082. const auto size = (float) juce::jmin (simpleHeaders ? simpleSizes().icon : 14, trackHeight - 4);
  3083. const auto ink = muted ? colour::textDisabled
  3084. : simpleHeaders && trackColour != 0 ? ui::simplelook::readableOn (juce::Colour (trackColour), plate, 3.0f)
  3085. : colour::textSecondary.brighter (0.3f);
  3086. const auto iconBox = juce::Rectangle<float> ((float) textLeft, (float) y + ((float) nameHeight - size) * 0.5f, size, size);
  3087. ui::drawTrackIcon (g, icon, iconBox, ink);
  3088. if (simpleHeaders) // (round 190rc: a click there opens the instrument's window)
  3089. simpleIconBoxes[t] = iconBox.getSmallestIntegerContainer();
  3090. textLeft += (int) size + (simpleHeaders ? 6 : 4);
  3091. }
  3092. if (live)
  3093. {
  3094. // Live: the name in the track colour x 0.24 (live-arrangement.png "Drums" #252f22 on #9bc48d), in the first
  3095. // 17 px of the box (an expanded lane keeps its controls at the top)
  3096. g.setColour (theme::liveMarkOn (plate, 0.24f, 4.5f, colour::textPrimary)); // (round 190oj CS-4: KICK read 1.8:1)
  3097. g.setFont (font (type::small, groupHead));
  3098. const auto nameRight = (int) juce::jmin (textRight, plateArea.getRight() - 3.0f);
  3099. const auto nameBox = juce::Rectangle<int> (textLeft - 1, y, juce::jmax (8, nameRight - textLeft + 1), juce::jmin (trackHeight - 2, liveStripHeight));
  3100. textcache::drawText (g, custom ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()) : tr ("Track {0}", { juce::String (t + 1) }),
  3101. nameBox, juce::Justification::centredLeft, false);
  3102. }
  3103. else if (! fl)
  3104. {
  3105. g.setColour (muted ? colour::textDisabled : (custom ? colour::textPrimary : colour::textSecondary));
  3106. g.setFont (font (simpleHeaders ? type::body : type::small, groupHead || (simpleHeaders && custom)));
  3107. textcache::drawFittedText (g, custom ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str())
  3108. : tr ("Track {0}", { juce::String (t + 1) }),
  3109. textLeft, y, juce::jmax (8, (int) textRight - textLeft - 2), nameHeight, juce::Justification::centredLeft,
  3110. nameHeight >= 30 ? 2 : 1, 0.8f);
  3111. }
  3112. // the divider under the header: lit while hovered or dragged (drag resizes the track)
  3113. if (hover.divider == t || (drag == Drag::trackResize && (resizeTrack == t || resizeAll)))
  3114. {
  3115. g.setColour (colour::accent);
  3116. g.fillRoundedRectangle (juce::Rectangle<float> (6.0f, (float) (y + trackHeight) - 2.0f, (float) headerWidth - 12.0f, 3.0f), 1.5f);
  3117. }
  3118. }
  3119. paintTrackStateMarks (g, headers, headerRows); // round 190op (P4: hidden tracks shown, deactivated tracks)
  3120. paintVersionChips (g, headers, headerRows); // round 190pe (P20: tracks with versions)
  3121. paintLaneHeaders (g, headers); // round 177b (nothing when lanes are off)
  3122. }
  3123. }
  3124. // the Simple workflow's drop lane (round 184a): the first empty row invites files. Round 190jj (BandLab): while the
  3125. // drag's ghost is on it, the lane is an empty track row (the ghost and its tag are drawn later)
  3126. if (const auto laneTrack = dropLaneTrack(); laneTrack >= 0 && dropLaneShown() && ! (dropLaneHot && ! dropGhost.empty() && dropGhost.front().track == laneTrack))
  3127. {
  3128. juce::Graphics::ScopedSaveState state (g);
  3129. const auto y = trackToY (laneTrack), h = heightOf (laneTrack);
  3130. if (g.reduceClipRegion (grid) && y < grid.getBottom() && y + h > grid.getY())
  3131. {
  3132. // round 190jc (design190ia SG-6, BandLab's empty-state lane): the outline on whole pixels in a 3:1 grey, a "note +"
  3133. // icon over one centred line; lit in the accent while something is dragged over it (repainted on enter / exit)
  3134. const auto lane = juce::Rectangle<float> ((float) grid.getX() + 6.5f, (float) y + 4.5f, (float) grid.getWidth() - 13.0f, (float) h - 9.0f);
  3135. if (dropLaneHot)
  3136. {
  3137. g.setColour (colour::accent.withAlpha (0.08f));
  3138. g.fillRoundedRectangle (lane, radius::lg);
  3139. }
  3140. juce::Path outline;
  3141. outline.addRoundedRectangle (lane, radius::lg);
  3142. juce::Path dashed;
  3143. const float dashes[] { 6.0f, 4.0f };
  3144. juce::PathStrokeType (dropLaneHot ? 1.5f : 1.0f).createDashedStroke (dashed, outline, dashes, 2);
  3145. g.setColour (dropLaneHot ? colour::accent : colour::textDisabled);
  3146. g.fillPath (dashed);
  3147. const auto text = tr ("Drop a loop, audio or MIDI file here");
  3148. const auto textFont = font (type::title, true);
  3149. const auto textHeight = std::ceil (textFont.getHeight());
  3150. const auto iconSize = lane.getHeight() >= 44.0f ? 20.0f : 0.0f;
  3151. const auto block = iconSize + (iconSize > 0.0f ? 3.0f : 0.0f) + textHeight;
  3152. auto content = lane.withSizeKeepingCentre (lane.getWidth() - 24.0f, block);
  3153. if (iconSize > 0.0f)
  3154. {
  3155. const auto icon = content.removeFromTop (iconSize).withSizeKeepingCentre (iconSize, iconSize);
  3156. const auto ink = dropLaneHot ? colour::textPrimary : colour::textSecondary;
  3157. icons::draw (g, Icon::note, icon.withTrimmedRight (4.0f).withTrimmedTop (2.0f), ink);
  3158. g.setColour (ink); // the "+" at the note's top right
  3159. const auto c = juce::Point<float> (icon.getRight() - 3.0f, icon.getY() + 4.0f);
  3160. g.fillRect (juce::Rectangle<float> (7.0f, 1.5f).withCentre (c));
  3161. g.fillRect (juce::Rectangle<float> (1.5f, 7.0f).withCentre (c));
  3162. content.removeFromTop (3.0f);
  3163. }
  3164. g.setColour (dropLaneHot ? colour::textPrimary : colour::textSecondary);
  3165. g.setFont (textFont);
  3166. g.drawText (text, content, juce::Justification::centred, true);
  3167. }
  3168. }
  3169. // toolbar band, and the corner left of the ruler
  3170. g.setColour (colour::bg3);
  3171. g.fillRect (0, 0, getWidth(), toolbarHeight);
  3172. g.setColour (colour::bg2);
  3173. g.fillRect (0, toolbarHeight, headerWidth, headerHeight - toolbarHeight);
  3174. g.setColour (colour::border);
  3175. g.fillRect (0, toolbarHeight - 1, getWidth(), 1);
  3176. g.fillRect (0, headerHeight - 1, headerWidth, 1);
  3177. g.fillRect (headerWidth - 1, toolbarHeight, 1, getHeight() - toolbarHeight);
  3178. // the vertical zoom handle above the scroll bar (FL's track height control): a grip of three lines
  3179. {
  3180. const auto r = trackZoomHandle().toFloat().reduced (1.0f, 2.0f);
  3181. const auto active = trackZoomHover || drag == Drag::trackZoom;
  3182. theme::fillRoundRect (g, r, theme::radius::sm, active ? colour::bg4 : colour::bg2);
  3183. g.setColour (active ? colour::accent : (std::abs (trackZoom - 1.0) > 1.0e-3 ? colour::textSecondary : colour::textDisabled));
  3184. const auto cx = r.getCentreX(), cy = r.getCentreY();
  3185. for (int i = -1; i <= 1; ++i)
  3186. g.fillRect (juce::Rectangle<float> (cx - 3.0f, cy + (float) i * 4.0f - 0.5f, 6.0f, 1.2f));
  3187. g.drawLine (cx, r.getY() + 2.0f, cx, cy - 6.0f, 1.0f);
  3188. g.drawLine (cx, cy + 6.0f, cx, r.getBottom() - 2.0f, 1.0f);
  3189. }
  3190. uitrace::flushParts ("Playlist", trace.elapsedMs());
  3191. }
  3192. void PlaylistComponent::paintOverview (juce::Graphics& g, juce::Rectangle<float> area, double total)
  3193. {
  3194. // every clip of the arrangement in miniature (its colour, its track's row), bar lines, the song's end
  3195. using namespace theme;
  3196. const auto& song = engine.getSong();
  3197. const auto scale = area.getWidth() / juce::jmax (1.0, total);
  3198. const auto bar = (double) song.barTicks();
  3199. g.setColour (colour::bg2);
  3200. g.fillRect (area.withWidth (juce::jmin (area.getWidth(), (float) (song.songLength() * scale))));
  3201. const auto every = bar * scale < 3.0 ? 16 : bar * scale < 6.0 ? 4 : 1;
  3202. g.setColour (colour::gridBar.withAlpha (0.5f));
  3203. for (int b = every; b * bar < total; b += every)
  3204. g.fillRect ((float) (area.getX() + b * bar * scale), area.getY(), 1.0f, area.getHeight());
  3205. int rows = 1;
  3206. for (const auto& c : song.playlist)
  3207. rows = juce::jmax (rows, c.track + 1);
  3208. const auto inner = area.reduced (0.0f, 1.0f);
  3209. const auto rowHeight = inner.getHeight() / (float) rows;
  3210. for (const auto& c : song.playlist)
  3211. {
  3212. auto base = colour::automation;
  3213. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  3214. base = tame (patternColour (song, c.pattern));
  3215. else if (c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  3216. base = tame (audioClipColour (song.channels[(std::size_t) c.channel]));
  3217. const auto y = inner.getY() + rowHeight * (float) projection.row (c.track); // (round 190jq: its drawn row)
  3218. g.setColour (c.muted ? base.withAlpha (0.35f) : base);
  3219. g.fillRect ((float) (area.getX() + c.start * scale), y, juce::jmax (1.0f, (float) (c.length * scale) - 0.5f),
  3220. juce::jmax (1.0f, rowHeight - (rowHeight >= 3.0f ? 0.5f : 0.0f)));
  3221. }
  3222. }
  3223. void PlaylistComponent::paintMutedTracks (juce::Graphics& g)
  3224. {
  3225. if (! darkenMutedTracks || ! flClipLook())
  3226. return;
  3227. const auto& song = engine.getSong();
  3228. const auto grid = gridArea();
  3229. if (grid.isEmpty() || song.playlistTracks.empty())
  3230. return;
  3231. std::optional<juce::Graphics::ScopedSaveState> state;
  3232. // PR #268, a LYNX extra (round 190qm: FL 2026 greys the clips and the header of a switched-off track, shownMuted and
  3233. // the header plate, and leaves its lane as it is): the row steps back as a whole - its lane, clips and automation
  3234. // lanes go dark; the tracks that are on keep their colours. (The PR's 30 % header veil is gone: paint() draws the
  3235. // headers after this, so it showed only over the cached picture, and the header is already grey as in FL.)
  3236. // (round 190qm, paint gate: this runs on every playhead frame over the picture, so nothing is set up until a
  3237. // switched-off track is in view)
  3238. bool clipped = false;
  3239. const auto count = juce::jmin ((int) song.playlistTracks.size(), numTracks());
  3240. for (int t = 0; t < count; ++t)
  3241. {
  3242. if (! song.playlistTracks[(std::size_t) t].muted || comp::isTakeLane (song, t)) // (a take lane: shownMuted)
  3243. continue;
  3244. const auto height = heightOf (t);
  3245. const auto y = trackToY (t);
  3246. const auto rowHeight = height + laneBlockHeight (t);
  3247. if (height <= 0 || y >= grid.getBottom() || y + rowHeight <= grid.getY())
  3248. continue;
  3249. if (! clipped)
  3250. {
  3251. state.emplace (g);
  3252. if (! g.reduceClipRegion (grid))
  3253. return;
  3254. clipped = true;
  3255. g.setColour (juce::Colours::black.withAlpha (0.45f));
  3256. }
  3257. g.fillRect (grid.getX(), y, grid.getWidth(), rowHeight);
  3258. }
  3259. }
  3260. // The playhead over the cached image (round 174e): the line in the grid and the triangle on the ruler, as paint()
  3261. // draws them without the cache
  3262. // Round 190ig (FL look, Pattern layout): the titles of the audio and automation clips that start left of the view, held at
  3263. // its left edge, drawn last before the playhead (paint() and over the cached picture alike, so both look the same).
  3264. void PlaylistComponent::paintTrackSelectionDim (juce::Graphics& g)
  3265. {
  3266. if (! dimUnselectedTracks || selectedTracks.empty() || ! flClipLook())
  3267. return;
  3268. const auto grid = gridArea();
  3269. if (grid.isEmpty())
  3270. return;
  3271. juce::Graphics::ScopedSaveState state (g);
  3272. if (! g.reduceClipRegion (grid))
  3273. return;
  3274. g.setColour (juce::Colours::black.withAlpha (0.16f)); // (round 190qj: subtle; clip names and notes on them stay readable)
  3275. for (int t = 0; t < numTracks(); ++t)
  3276. if (! isTrackSelected (t))
  3277. {
  3278. const auto height = heightOf (t);
  3279. if (height <= 0)
  3280. continue;
  3281. g.fillRect (grid.getX(), trackToY (t), grid.getWidth(), height + laneBlockHeight (t)); // (the lanes and clips)
  3282. g.fillRect (0, trackToY (t), headerWidth, height); // (the header too)
  3283. }
  3284. }
  3285. void PlaylistComponent::paintStickyTitles (juce::Graphics& g)
  3286. {
  3287. // round 190qe (D2-PL2): FL's Playlist ▸ View ▸ "Keep labels on screen" (on by default) — every layout's arrangement and
  3288. // every clip kind (FL holds the pattern clips' labels too, verify_190qc shot 06); off: the titles go with the clips
  3289. if (! keeplabels::on)
  3290. return;
  3291. heldTitleLeft = (float) gridArea().getX();
  3292. const auto grid = gridArea();
  3293. const auto left = (float) grid.getX();
  3294. const juce::Graphics::ScopedSaveState state (g);
  3295. if (! g.reduceClipRegion (grid) || ! g.getClipBounds().intersects (juce::Rectangle<int> (grid.getX(), grid.getY(), (int) flStickyTitleMax, grid.getHeight())))
  3296. return;
  3297. const auto& song = engine.getSong();
  3298. const auto fl = flClipLook();
  3299. const auto live = liveArrangeLook();
  3300. // the clips that cross the left edge, found again only when the view or the song changed (a frame of a scroll or of
  3301. // the playhead draws the same few)
  3302. const HeldTitlesKey key { scrollTicks, pixelsPerTick, scrollY, engine.getPublishCount(), song.playlist.size(), grid };
  3303. if (! (key == heldTitlesKey))
  3304. {
  3305. heldTitlesKey = key;
  3306. heldTitles.clear();
  3307. for (int i = 0; i < (int) song.playlist.size(); ++i)
  3308. {
  3309. const auto& c = song.playlist[(std::size_t) i];
  3310. if (shownMuted (song, c) || c.track < 0 || (! heldEveryClip() && (! fl || c.kind == ClipKind::pattern)))
  3311. continue;
  3312. if (const auto x0 = tickToX ((double) c.start), x1 = tickToX ((double) c.end()); x0 >= (double) left || x1 <= (double) left || x1 - (double) left < 16.0)
  3313. continue;
  3314. if (const auto y = trackToY (c.track); y > grid.getBottom() || y + heightOf (c.track) < grid.getY() || noteedit::isFoldedAway (song, c.track))
  3315. continue;
  3316. if (c.kind == ClipKind::automation && live && projection.isChild (c.track) && c.gridSlot < 0) // (a Live lane: no block)
  3317. continue;
  3318. if (const auto x0 = tickToX ((double) c.start), x1 = tickToX ((double) c.end()); x1 - x0 < SmallClips::maxWidth) // (drawn without a title)
  3319. continue;
  3320. heldTitles.push_back (i);
  3321. }
  3322. }
  3323. for (const auto i : heldTitles)
  3324. {
  3325. if (i >= (int) song.playlist.size())
  3326. break;
  3327. const auto& c = song.playlist[(std::size_t) i];
  3328. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  3329. const auto y = trackToY (c.track), h = heightOf (c.track);
  3330. if (y > grid.getBottom() || y + h < grid.getY())
  3331. continue;
  3332. const auto whole = clipRectAt (x0, x1, (float) y, h);
  3333. auto r = whole.withRight (juce::jmin (whole.getRight(), left + flStickyTitleMax)); // (a held title is at most this wide)
  3334. const auto band = r.getHeight() + 1.0f < (float) flBandBelow;
  3335. // FL's look (Pattern layout): the audio and automation clips' FL header
  3336. if (fl && c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  3337. {
  3338. const auto& channel = song.channels[(std::size_t) c.channel];
  3339. const auto look = theme::clipBody (juce::Colour (channel.colour), trackColourIn (song, c.track), ClipKind::audio, theme::ClipStyle::flTint);
  3340. paintFlClipTitle (g, r, look, juce::String::fromUTF8 (channel.name.c_str()), ClipGlyph::audio, false, band, left, true);
  3341. continue;
  3342. }
  3343. if (fl && c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size())
  3344. {
  3345. const auto& automation = song.automations[(std::size_t) c.automation];
  3346. const auto look = theme::clipBody (juce::Colour (automation.colour), trackColourIn (song, c.track), ClipKind::automation, theme::ClipStyle::flTint);
  3347. paintFlClipTitle (g, r, look, juce::String::fromUTF8 (automation.name.c_str()), ClipGlyph::automation, false, band, left, true);
  3348. continue;
  3349. }
  3350. // the name each layout's painter shows (paintClipFrame, paintLiveClipFrame)
  3351. juce::String name;
  3352. ClipGlyph glyph = ClipGlyph::pattern;
  3353. juce::Colour base;
  3354. if (c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  3355. {
  3356. name = juce::String::fromUTF8 (song.channels[(std::size_t) c.channel].name.c_str());
  3357. glyph = ClipGlyph::audio;
  3358. base = audioClipColour (song.channels[(std::size_t) c.channel]);
  3359. }
  3360. else if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size())
  3361. {
  3362. const auto& automation = song.automations[(std::size_t) c.automation];
  3363. name = juce::String::fromUTF8 (automation.name.c_str());
  3364. glyph = ClipGlyph::automation;
  3365. base = automation.target.kind == AutomationTargetKind::none ? theme::colour::textDisabled
  3366. : theme::colour::automation.withMultipliedSaturation (0.75f).withMultipliedBrightness (0.8f);
  3367. }
  3368. else if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  3369. {
  3370. name = juce::String::fromUTF8 (song.patterns[(std::size_t) c.pattern].name.c_str());
  3371. base = theme::tame (patternColour (song, c.pattern));
  3372. }
  3373. else
  3374. continue;
  3375. const auto held = r.withLeft (left);
  3376. if (live)
  3377. {
  3378. paintLiveClipTitle (g, held, liveClipLook (c), name);
  3379. continue;
  3380. }
  3381. const auto simpleLook = c.kind != ClipKind::automation ? simpleClipLook (c) : std::nullopt;
  3382. const auto title = held.withHeight (clipHeaderHeight (whole));
  3383. const auto header = simpleLook ? simpleLook->headerTop : clipHeaderColour (base);
  3384. paintClipFrameTitle (g, title, held.getWidth(), header, name, glyph, false, simpleLook ? &*simpleLook : nullptr);
  3385. }
  3386. }
  3387. // Round 190im (perf): one audio or automation clip exactly as paint()'s clip loop draws it (frame, content, title, the
  3388. // selection outline), for the cache's repair of a held title's band (cacheShift: only where the clip alone is drawn)
  3389. void PlaylistComponent::paintHeldClip (juce::Graphics& g, int index)
  3390. {
  3391. heldTitleLeft = keeplabels::on ? (float) gridArea().getX() : -1.0e9f; // (round 190qe)
  3392. const auto& song = engine.getSong();
  3393. if (index < 0 || index >= (int) song.playlist.size())
  3394. return;
  3395. const juce::ScopedValueSetter<bool> noPlayhead (cachePainting, true);
  3396. const auto& c = song.playlist[(std::size_t) index];
  3397. const auto r = clipRectAt ((float) tickToX ((double) c.start), (float) tickToX ((double) c.end()), (float) trackToY (c.track), heightOf (c.track));
  3398. if (c.kind == ClipKind::automation)
  3399. {
  3400. paintAutomationClip (g, c, r);
  3401. if (isSelected (index))
  3402. paintClipOutline (g, r, theme::colour::automation, true, false);
  3403. }
  3404. else if (c.kind == ClipKind::audio)
  3405. {
  3406. paintAudioClip (g, c, r);
  3407. if (isSelected (index))
  3408. paintClipOutline (g, r, theme::colour::audioClip, true, false);
  3409. }
  3410. }
  3411. void PlaylistComponent::paintPlayheadTrail (juce::Graphics& g, float x, juce::Rectangle<int> grid) const
  3412. {
  3413. if (! trailShown)
  3414. return;
  3415. const auto from = x - 0.5f - (float) playheadTrail;
  3416. juce::ColourGradient glow (theme::colour::playhead.withAlpha (0.0f), from, 0.0f, theme::colour::playhead.withAlpha (0.38f), x - 0.5f, 0.0f, false);
  3417. g.setGradientFill (glow);
  3418. g.fillRect (juce::Rectangle<float> (from, (float) grid.getY(), (float) playheadTrail, (float) grid.getHeight()));
  3419. }
  3420. void PlaylistComponent::paintPlayhead (juce::Graphics& g)
  3421. {
  3422. if (playheadTick >= 0.0)
  3423. paintPlayheadAt (g, (float) tickToX (playheadTick));
  3424. }
  3425. void PlaylistComponent::paintPlayheadAt (juce::Graphics& g, float x)
  3426. {
  3427. using namespace theme;
  3428. const auto grid = gridArea();
  3429. {
  3430. juce::Graphics::ScopedSaveState state (g);
  3431. if (g.reduceClipRegion (grid))
  3432. {
  3433. // round 190im (R5, DC-5): FL's soft glow trail behind the line while playing (shots/fl-playhead-glow-zoom.png:
  3434. // ≈14 px fading in towards the line), in LYNX's playhead colour (decision PL1); Animations off: no trail
  3435. paintPlayheadTrail (g, x, grid);
  3436. g.setColour (colour::playhead);
  3437. g.fillRect (juce::Rectangle<float> (x - 0.5f, (float) grid.getY(), 1.5f, (float) grid.getHeight()));
  3438. }
  3439. }
  3440. juce::Graphics::ScopedSaveState state (g);
  3441. if (g.reduceClipRegion (juce::Rectangle<int> (headerWidth, rulerTop, grid.getWidth(), timelineHeight)))
  3442. {
  3443. juce::Path tri;
  3444. tri.addTriangle (x - 6, (float) rulerTop, x + 6, (float) rulerTop, x, (float) rulerTop + 9.0f);
  3445. g.setColour (colour::playhead);
  3446. g.fillPath (tri);
  3447. }
  3448. }
  3449. // round 190ip: the playhead as the GPU overlay draws it (paintPlayheadAt), over the ruler and the lanes
  3450. ui::MotionOverlay::Mark PlaylistComponent::playheadMark() const
  3451. {
  3452. const auto grid = gridArea();
  3453. ui::MotionOverlay::Mark m;
  3454. m.x = (float) tickToX (playheadTick);
  3455. // (rollup 0.1.30: round 190im's glow trail is part of the picture, left of the line, while it shows)
  3456. m.extent = juce::Rectangle<int>::leftTopRightBottom (trailShown ? -8 - playheadTrail : -8, rulerTop, 8, grid.getBottom());
  3457. m.clip = juce::Rectangle<int>::leftTopRightBottom (grid.getX(), rulerTop, grid.getRight(), grid.getBottom());
  3458. m.look = ((std::uint64_t) (std::uint32_t) theme::colour::playhead.getARGB() << 32)
  3459. ^ ((std::uint64_t) (std::uint32_t) rulerTop << 24) ^ ((std::uint64_t) (std::uint32_t) timelineHeight << 16)
  3460. ^ ((std::uint64_t) (std::uint32_t) grid.getY() * 65537u) ^ (std::uint64_t) (std::uint32_t) grid.getHeight()
  3461. ^ ((std::uint64_t) (std::uint32_t) headerWidth << 40) ^ (trailShown ? (std::uint64_t) 1 << 63 : 0);
  3462. return m;
  3463. }
  3464. juce::Rectangle<int> PlaylistComponent::playheadColumn (double tick, int left) const
  3465. {
  3466. return tick >= 0.0 ? juce::Rectangle<int> ((int) tickToX (tick) - left, 0, left + 8, getHeight()) : juce::Rectangle<int>();
  3467. }
  3468. void PlaylistComponent::repaintPlayheadColumn (double tick)
  3469. {
  3470. // (rollup 0.1.30: with round 190im's glow trail, which the overlay drew too)
  3471. if (const auto r = playheadColumn (tick, 8 + playheadTrail); ! r.isEmpty())
  3472. {
  3473. playheadRepaintOnly = playheadOverlay; // (the cached image under it stays valid)
  3474. repaint (r);
  3475. playheadRepaintOnly = false;
  3476. }
  3477. }
  3478. // Live's select + Enter (round 177c, comp::swipeStyle): the time selection of a take lane goes to its comp.
  3479. void PlaylistComponent::swipeTimeSelectionToComp (int lane)
  3480. {
  3481. const auto& song = engine.getSong();
  3482. const auto g = comp::groupOf (song, lane);
  3483. if (! comp::selectionSwipes (comp::swipeStyle) || ! g.isLane (lane) || ! comp::isComp (song, g.comp) || ! exportopts::hasSelection (song))
  3484. return;
  3485. setSelection ({});
  3486. engine.editSong ([lane] (Song& s) { comp::swipeSelection (s, lane); });
  3487. sortClips();
  3488. }
  3489. // Round 190jf (B17): where an Alt+drag of a header drops the track: a line across the headers and the grid, starting at
  3490. // the indent of the folder level it lands at, and a frame round the folder it joins
  3491. void PlaylistComponent::paintFolderDrop (juce::Graphics& g)
  3492. {
  3493. if (drag != Drag::headerMove || headerMoveBefore < 0)
  3494. return;
  3495. const auto& song = engine.getSong();
  3496. const auto count = numTracks();
  3497. const auto y = headerMoveBefore < count ? trackToY (headerMoveBefore) : trackToY (count - 1) + heightOf (count - 1);
  3498. const juce::Graphics::ScopedSaveState keep (g);
  3499. g.reduceClipRegion (juce::Rectangle<int> (0, tracksTop(), getWidth(), gridArea().getBottom() - tracksTop()));
  3500. const auto x = (float) (headerMoveDepth > 0 ? groupIndent * headerMoveDepth : 2);
  3501. g.setColour (theme::colour::accent);
  3502. g.fillRect (juce::Rectangle<float> (x, (float) y - 1.0f, (float) getWidth() - x, 2.0f));
  3503. g.fillEllipse (juce::Rectangle<float> (x - 3.0f, (float) y - 3.0f, 6.0f, 6.0f));
  3504. if (headerMoveDepth > 0)
  3505. {
  3506. // the folder: the nearest row above the place one level up
  3507. for (int t = headerMoveBefore - 1; t >= 0; --t)
  3508. if (noteedit::folderDepth (song, t) == headerMoveDepth - 1 && (t < headerMoveTrack || t > noteedit::folderEnd (song, headerMoveTrack)))
  3509. {
  3510. const auto top = trackToY (t);
  3511. const auto end = juce::jmax (noteedit::folderEnd (song, t), headerMoveBefore - 1);
  3512. const auto bottom = juce::jmax (y, trackToY (end) + heightOf (end));
  3513. g.drawRect (juce::Rectangle<float> ((float) headerIndent (song, t), (float) top, (float) (headerWidth - headerIndent (song, t)), (float) (bottom - top)), 1.5f);
  3514. break;
  3515. }
  3516. }
  3517. }
  3518. void PlaylistComponent::fadeOut (const std::vector<int>& clips)
  3519. {
  3520. // issue #250 (round 190oq): each deleted clip in view leaves FL's ghost (nothing at all when Animations are off or
  3521. // effects reduced: ui/DeleteFade.h)
  3522. if (! ui::DeleteFade::enabled())
  3523. return;
  3524. const auto& song = engine.getSong();
  3525. const auto grid = gridArea();
  3526. for (const auto i : clips)
  3527. if (i >= 0 && i < (int) song.playlist.size())
  3528. if (const auto r = clipBounds (i); r.intersects (grid))
  3529. deleteFade.add (r.toFloat(), liveClipColour (song.playlist[(std::size_t) i]));
  3530. }
  3531. void PlaylistComponent::paintOverChildren (juce::Graphics& g)
  3532. {
  3533. deleteFade.paint (g, gridArea()); // (issue #250: nothing while no clip is fading)
  3534. paintDropGhost (g); // (round 190im: a drag's landing place)
  3535. paintFolderDrop (g); // round 190jf (B17)
  3536. if (headerGripLit || drag == Drag::headerWidth) // round 190jq (issue #164): the edge being dragged, in the accent
  3537. {
  3538. g.setColour (theme::colour::accent);
  3539. g.fillRect (headerWidth - 1, rulerTop, 2, gridArea().getBottom() - rulerTop);
  3540. }
  3541. if (drag == Drag::swipe && swipeLane >= 0 && swipeEnd != swipeAnchor)
  3542. {
  3543. const auto x0 = (float) tickToX ((double) juce::jmin (swipeAnchor, swipeEnd));
  3544. const auto x1 = (float) tickToX ((double) juce::jmax (swipeAnchor, swipeEnd));
  3545. const auto range = juce::Rectangle<float> (x0, (float) trackToY (swipeLane), x1 - x0, (float) heightOf (swipeLane));
  3546. const juce::Graphics::ScopedSaveState keep (g);
  3547. g.reduceClipRegion (gridArea());
  3548. g.setColour (theme::colour::accent.withAlpha (0.28f));
  3549. g.fillRect (range);
  3550. g.setColour (theme::colour::accent);
  3551. g.drawRect (range, 1.0f);
  3552. }
  3553. if (drag == Drag::range || drag == Drag::rangeMove || ! engine.getSong().trackRange.empty()) // round 190pa (P14)
  3554. paintTrackRange (g);
  3555. const auto& song = engine.getSong();
  3556. if (song.performanceMode)
  3557. {
  3558. // Performance mode: a tag in the grid's top-right corner (left of the Ripple tag), and each playing track's progress on its header
  3559. using namespace theme;
  3560. const auto grid = gridArea();
  3561. const auto tag = juce::Rectangle<float> ((float) grid.getRight() - 176.0f, (float) grid.getY() + 4.0f, 100.0f, 18.0f);
  3562. g.setColour (colour::bg0.withAlpha (0.8f));
  3563. g.fillRoundedRectangle (tag, radius::sm);
  3564. g.setColour (colour::info);
  3565. g.drawRoundedRectangle (tag.reduced (0.5f), radius::sm, 1.0f);
  3566. g.setFont (font (type::caption, true));
  3567. textcache::drawText (g, tr ("Performance"), tag.toNearestInt(), juce::Justification::centred);
  3568. const auto& live = engine.performanceState();
  3569. if (showTrackProgress && live.anyPlaying.load (std::memory_order_relaxed))
  3570. {
  3571. juce::Graphics::ScopedSaveState state (g);
  3572. g.reduceClipRegion (0, grid.getY(), headerWidth, grid.getHeight());
  3573. for (int t = 0; t < juce::jmin (numTracks(), perf::maxTracks); ++t)
  3574. {
  3575. const auto& view = live.tracks[(std::size_t) t];
  3576. if (view.playing.load (std::memory_order_relaxed) < 0)
  3577. continue;
  3578. const auto y = trackToY (t), h = heightOf (t);
  3579. if (y > grid.getBottom() || y + h < grid.getY())
  3580. continue;
  3581. const auto p = juce::jlimit (0.0f, 1.0f, view.progress.load (std::memory_order_relaxed));
  3582. const auto bar = juce::Rectangle<float> (4.0f, (float) (y + h) - 5.0f, (float) headerWidth - 8.0f, 3.0f);
  3583. g.setColour (colour::bg0);
  3584. g.fillRect (bar);
  3585. g.setColour (colour::ledOn);
  3586. g.fillRect (bar.withWidth (bar.getWidth() * p));
  3587. }
  3588. }
  3589. }
  3590. if (! ripple)
  3591. return;
  3592. // ripple editing is on: a small tag in the grid's top-right corner
  3593. const auto grid = gridArea();
  3594. const auto tag = juce::Rectangle<float> ((float) grid.getRight() - 70.0f, (float) grid.getY() + 4.0f, 64.0f, 18.0f);
  3595. g.setColour (theme::colour::accentMuted);
  3596. g.fillRoundedRectangle (tag, theme::radius::sm);
  3597. g.setColour (theme::colour::accent);
  3598. g.drawRoundedRectangle (tag.reduced (0.5f), theme::radius::sm, 1.0f);
  3599. g.setFont (theme::font (theme::type::caption, true));
  3600. textcache::drawText (g, tr ("Ripple"), tag.toNearestInt(), juce::Justification::centred);
  3601. }
  3602. namespace
  3603. {
  3604. // The played span of an audio clip's file, for drawing it (round 190gd). The Playlist loaded the file on every paint to
  3605. // read its span; a channel that plays a time-stretched copy holds only that copy, so every paint of its clips decoded
  3606. // the whole file again and applied its precomputed effects (FL's Thief: ~15 s of the message thread at 85-95 % after
  3607. // the project opened, and the files coming and going in memory). A file nothing holds is now decoded once: its span is
  3608. // kept per path, channel settings (what precompute::playedSpan depends on) and waveform summary (a file read again
  3609. // gets a new one). Message thread.
  3610. precompute::PlayedSpan drawnSpan (SampleLibrary& samples, const ChannelDef& channel, const juce::String& path,
  3611. const std::shared_ptr<const wave::Summary>& summary)
  3612. {
  3613. if (const auto held = samples.findLoaded (path)) // (held by the rack: playedSpan keeps its own span for it)
  3614. return clipops::clipSpan (channel, held);
  3615. const auto whole = channel.instrument == InstrumentKind::audioClip;
  3616. const auto& s = channel.sampler;
  3617. struct Entry
  3618. {
  3619. juce::String path;
  3620. std::weak_ptr<const wave::Summary> summary;
  3621. float regionStart, regionEnd;
  3622. bool reverse, loops, whole;
  3623. std::int64_t loopStart, loopEnd;
  3624. std::vector<std::int32_t> flChannel;
  3625. SamplePrecompute precompute;
  3626. precompute::PlayedSpan span;
  3627. };
  3628. static std::vector<Entry> cache;
  3629. for (const auto& e : cache)
  3630. if (e.path == path && e.whole == whole && e.regionStart == s.regionStart && e.regionEnd == s.regionEnd && e.reverse == s.reverse
  3631. && e.loops == s.useLoopPoints && e.loopStart == s.loopStart && e.loopEnd == s.loopEnd && e.flChannel == s.flChannel
  3632. && e.precompute == s.precompute && ! e.summary.expired() && e.summary.lock() == summary)
  3633. return e.span;
  3634. // round 190rd (perf 9: a 200-450 ms paint after an edit or a project open): a channel without a precomputed effect has
  3635. // its span from the summary's length (the file's); only one with one decodes the file here (nothing holds it)
  3636. auto span = precompute::playedSpanOfLength ((std::int64_t) summary->frames, s, whole).value_or (precompute::PlayedSpan { -1, -1 });
  3637. if (span.first < 0)
  3638. {
  3639. const auto data = samples.load (path);
  3640. span = data != nullptr ? clipops::clipSpan (channel, data) : precompute::PlayedSpan { 0, (std::int64_t) summary->frames };
  3641. }
  3642. std::erase_if (cache, [] (const Entry& e) { return e.summary.expired(); });
  3643. if (cache.size() >= 256)
  3644. cache.erase (cache.begin());
  3645. cache.push_back ({ path, summary, s.regionStart, s.regionEnd, s.reverse, s.useLoopPoints, whole, s.loopStart, s.loopEnd, s.flChannel, s.precompute, span });
  3646. return span;
  3647. }
  3648. } // namespace
  3649. void PlaylistComponent::addSmallClip (SmallClips& batch, float physicalScale, const Clip& c, juce::Rectangle<float> r, bool current)
  3650. {
  3651. const auto& song = engine.getSong();
  3652. juce::Colour base;
  3653. if (c.kind == ClipKind::audio)
  3654. {
  3655. if (c.channel < 0 || c.channel >= (int) song.channels.size())
  3656. return;
  3657. base = audioClipColour (song.channels[(std::size_t) c.channel]);
  3658. }
  3659. else
  3660. base = theme::tame (patternColour (song, c.pattern));
  3661. // round 190ig: an audio clip in FL's recipe in the Pattern layout (the same three colours a full clip has, so the
  3662. // batch stays one fill per colour)
  3663. const auto flAudio = c.kind == ClipKind::audio && flClipLook();
  3664. const auto band = flAudio && r.getHeight() + 1.0f < (float) flBandBelow;
  3665. const auto look = flAudio ? theme::clipBody (juce::Colour (song.channels[(std::size_t) c.channel].colour), trackColourIn (song, c.track), ClipKind::audio,
  3666. theme::ClipStyle::flTint)
  3667. : theme::ClipLook {};
  3668. // round 190jn (CL-17, CL-18): Live's look — the block in the clip colour, its rim, the body under the 17 px strip
  3669. const auto live = liveArrangeLook();
  3670. const auto liveLook = live ? liveClipLook (c) : theme::ClipLook {};
  3671. const auto title = flAudio ? (band ? r : r.withHeight (flHeaderHeight (r))) : r.withHeight (clipHeaderHeight (r));
  3672. const auto body = live ? (r.getHeight() >= (float) liveStripHeight + 4.0f ? r.withTrimmedTop ((float) liveStripHeight).withTrimmedLeft (1.0f) : juce::Rectangle<float>())
  3673. : flAudio ? (band ? r.reduced (0.0f, 1.0f) : r.withTrimmedTop (title.getHeight())) : r.withTrimmedTop (title.getHeight());
  3674. if (live)
  3675. {
  3676. batch.bodies[liveLook.body.getARGB()].addWithoutMerging (r);
  3677. const auto rim = theme::liveShade (liveLook.body, 0.53f).getARGB();
  3678. batch.edges[rim].addWithoutMerging ({ r.getX(), r.getY(), 1.0f, r.getHeight() });
  3679. batch.edges[rim].addWithoutMerging (r.withHeight (1.0f));
  3680. batch.edges[rim].addWithoutMerging ({ r.getX(), r.getY() + juce::jmin ((float) liveStripHeight, r.getHeight()) - 1.0f, r.getWidth(), 1.0f });
  3681. }
  3682. else if (flAudio)
  3683. {
  3684. if (! band)
  3685. batch.bodies[look.body.withMultipliedAlpha (look.bodyAlpha).getARGB()].addWithoutMerging (body);
  3686. batch.bodies[look.headerTop.interpolatedWith (look.headerBottom, 0.5f).getARGB()].addWithoutMerging (title);
  3687. batch.edges[look.edge.getARGB()].addWithoutMerging ({ r.getRight() - 1.0f, r.getY(), 1.0f, r.getHeight() });
  3688. }
  3689. else if (const auto simple = simpleClipLook (c)) // round 190jc: the Simple layout's BandLab colours
  3690. {
  3691. batch.bodies[simple->body.getARGB()].addWithoutMerging (body);
  3692. if (title.getHeight() >= 4.0f)
  3693. batch.bodies[simple->headerTop.getARGB()].addWithoutMerging (title);
  3694. batch.edges[(current ? theme::colour::textPrimary.withAlpha (0.55f) : theme::colour::bg0.withAlpha (0.85f)).getARGB()].addWithoutMerging (
  3695. { r.getRight() - 1.0f, r.getY(), 1.0f, r.getHeight() });
  3696. }
  3697. else
  3698. {
  3699. batch.bodies[clipBodyColour (base).getARGB()].addWithoutMerging (body);
  3700. if (title.getHeight() >= 4.0f)
  3701. batch.bodies[clipHeaderColour (base).getARGB()].addWithoutMerging (title);
  3702. batch.edges[(current ? theme::colour::textPrimary.withAlpha (0.55f) : theme::colour::bg0.withAlpha (0.85f)).getARGB()].addWithoutMerging (
  3703. { r.getRight() - 1.0f, r.getY(), 1.0f, r.getHeight() });
  3704. }
  3705. if (c.kind == ClipKind::audio && body.getWidth() >= 3.0f && body.getHeight() >= 3.0f)
  3706. {
  3707. const auto& channel = song.channels[(std::size_t) c.channel];
  3708. const auto path = juce::String::fromUTF8 (channel.samplePath.c_str());
  3709. const auto summary = ui::WaveformCache::getInstance()->find (path, [this, path] { return engine.getSampleLibrary().load (path); });
  3710. if (summary == nullptr)
  3711. return;
  3712. // the same mapping as paintAudioClip
  3713. const auto wave = body.reduced (0.0f, body.getHeight() >= 14.0f ? 2.0f : 1.0f);
  3714. // what the clip plays of the file (its Trim; round 180d): the same frames as the playback
  3715. const auto span = drawnSpan (engine.getSampleLibrary(), channel, path, summary);
  3716. const auto total = (double) span.frames;
  3717. const auto perTick = clipops::framesPerTick (channel, c, total, summary->sampleRate, song.bpm);
  3718. const auto startTick = (double) c.offset + (double) (wave.getX() - r.getX()) / pixelsPerTick;
  3719. const auto forward = ! clipops::playsBackwards (channel, c);
  3720. const auto startFrame = (double) span.first + (forward ? startTick * perTick : total - startTick * perTick);
  3721. const auto simple = flAudio || live ? std::optional<theme::ClipLook>() : simpleClipLook (c);
  3722. const auto colour = live ? liveLook.content : flAudio ? (band ? look.compactContent : look.content) : simple ? simple->content : clipContentColour (base);
  3723. auto style = ui::currentWaveStyle (colour, juce::jmin (ui::normalisingGain (*summary), 4.0f) * c.gain);
  3724. if (! style.spectral && c.gain > 1.0f)
  3725. style.gain = juce::jmin (style.gain, 8.0f);
  3726. if (! style.spectral)
  3727. ui::appendWaveformPath (batch.waves[colour.getARGB()], physicalScale, wave, wave, *summary, startFrame,
  3728. (forward ? perTick : -perTick) / pixelsPerTick, style);
  3729. return;
  3730. }
  3731. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size() && body.getHeight() >= 4.0f)
  3732. {
  3733. // the notes as one-pixel-wide marks at their pitch (the same placement as the full clip)
  3734. const auto& notes = song.patterns[(std::size_t) c.pattern].notes;
  3735. if (notes.empty())
  3736. return;
  3737. int low = 127, high = 0;
  3738. for (const auto& n : notes)
  3739. {
  3740. low = juce::jmin (low, n.key);
  3741. high = juce::jmax (high, n.key);
  3742. }
  3743. const auto inner = body.reduced (0.0f, body.getHeight() >= 12.0f ? 3.0f : 1.0f);
  3744. const auto span = juce::jmax (6, high - low + 2);
  3745. const auto bottomKey = (low + high) / 2.0f - span / 2.0f;
  3746. const auto rows = (float) span + 1.0f;
  3747. const auto noteHeight = juce::jlimit (1.5f, 2.5f, inner.getHeight() / rows);
  3748. const auto simple = simpleClipLook (c);
  3749. auto& marks = batch.contents[(live ? liveLook.content : simple ? simple->content : clipContentColour (base)).getARGB()];
  3750. // what plays: looped along a stretched clip with the LYNX option (issue #25), else once (FL, round 168k)
  3751. const auto passes = clipPasses (c, song.patterns[(std::size_t) c.pattern].effectiveLength (song.meter()));
  3752. for (auto pass = passes.first; pass <= passes.last; ++pass)
  3753. for (const auto& n : notes)
  3754. {
  3755. const auto at = c.start - c.offset + pass * passes.length + n.start;
  3756. if ((passes.loops && n.start >= passes.length) || at + n.length <= c.start || at >= c.end())
  3757. continue;
  3758. const auto nx = juce::jmax (inner.getX(), (float) tickToX ((double) at));
  3759. const auto nr = juce::jmin (inner.getRight() - 1.0f, nx + juce::jmax (1.0f, (float) (n.length * pixelsPerTick) - 1.0f));
  3760. if (nr <= nx)
  3761. continue;
  3762. const auto ny = inner.getBottom() - ((float) n.key - bottomKey + 0.5f) / rows * inner.getHeight() - noteHeight * 0.5f;
  3763. marks.addWithoutMerging ({ nx, ny, nr - nx, noteHeight });
  3764. }
  3765. }
  3766. }
  3767. namespace
  3768. {
  3769. // the index of a clip painted from the song's own list (-1 for a copy: a clip being dragged is drawn from one)
  3770. int playlistIndexOf (const Song& song, const Clip& c)
  3771. {
  3772. const auto* first = song.playlist.data();
  3773. return ! song.playlist.empty() && std::less_equal<const Clip*>() (first, &c) && std::less<const Clip*>() (&c, first + song.playlist.size())
  3774. ? (int) (&c - first)
  3775. : -1;
  3776. }
  3777. } // namespace
  3778. void PlaylistComponent::paintAudioClip (juce::Graphics& g, const Clip& c, juce::Rectangle<float> r)
  3779. {
  3780. const uitrace::Scope trace ("Playlist audio clip", false);
  3781. const auto& song = engine.getSong();
  3782. if (c.channel < 0 || c.channel >= (int) song.channels.size())
  3783. return;
  3784. const auto& channel = song.channels[(std::size_t) c.channel];
  3785. const auto colour = audioClipColour (channel);
  3786. const auto name = juce::String::fromUTF8 (channel.name.c_str());
  3787. // round 190ig (FM-21): FL's recipe in the Pattern layout — the channel's own colour for the header and the waveform,
  3788. // the track's colour for the body; LYNX's recipe in the other layouts
  3789. const auto fl = flClipLook();
  3790. const auto band = fl && r.getHeight() + 1.0f < (float) flBandBelow;
  3791. const auto look = fl ? theme::clipBody (juce::Colour (channel.colour), trackColourIn (song, c.track), ClipKind::audio, theme::ClipStyle::flTint)
  3792. : theme::ClipLook {};
  3793. const auto simpleLook = simpleClipLook (c); // (round 190jc, SG-5: the Simple layout draws an audio clip in its track's colour)
  3794. // round 190jn (CL-18): Live's audio clip — the block in the clip colour, the waveform dark (colour x 0.15) under the strip
  3795. const auto liveLook = liveArrangeLook() ? std::optional<theme::ClipLook> (liveClipLook (c)) : std::nullopt;
  3796. const auto body = fl ? paintFlClipFrame (g, r, look, band)
  3797. : liveLook ? paintLiveClipFrame (g, r, *liveLook, name)
  3798. : paintClipFrame (g, r, colour, name, ClipGlyph::audio, shownMuted (engine.getSong(), c), simpleLook ? &*simpleLook : nullptr);
  3799. // the waveform (ui/WaveformView, analysed in the background): the clean style fills the body with the
  3800. // peak envelope mirrored around the centre, in a light tint of the clip colour
  3801. const auto path = juce::String::fromUTF8 (channel.samplePath.c_str());
  3802. // (round 190jn: a collapsed Live lane draws no waveform, so it does not ask for one — nor load the file for it)
  3803. const auto summary = liveLook && body.isEmpty() ? nullptr
  3804. : ui::WaveformCache::getInstance()->find (path, [this, path] { return engine.getSampleLibrary().load (path); });
  3805. if (summary != nullptr && body.getHeight() >= 3.0f && body.getWidth() >= 3.0f) // (narrower: the body colour says enough)
  3806. {
  3807. const auto wave = body.reduced (0.0f, body.getHeight() >= 14.0f ? 2.0f : 1.0f);
  3808. // what the clip plays of the file (its Trim; round 180d): the same frames as the playback
  3809. const auto span = drawnSpan (engine.getSampleLibrary(), channel, path, summary);
  3810. const auto total = (double) span.frames;
  3811. const auto perTick = clipops::framesPerTick (channel, c, total, summary->sampleRate, song.bpm);
  3812. // r's left edge is the clip start, i.e. tick `offset` of the audio (counted from the played span's end when
  3813. // the channel is reversed)
  3814. const auto startTick = (double) c.offset + (double) (wave.getX() - r.getX()) / pixelsPerTick;
  3815. const auto forward = ! clipops::playsBackwards (channel, c);
  3816. const auto startFrame = (double) span.first + (forward ? startTick * perTick : total - startTick * perTick);
  3817. auto style = ui::currentWaveStyle (fl ? (band ? look.compactContent : look.content) : liveLook ? liveLook->content : simpleLook ? simpleLook->content : clipContentColour (colour),
  3818. juce::jmin (ui::normalisingGain (*summary), 4.0f) * c.gain);
  3819. if (! style.spectral && c.gain > 1.0f) // louder clip gain: the shape may hit the top, which is honest
  3820. style.gain = juce::jmin (style.gain, 8.0f);
  3821. if (fl || liveLook)
  3822. style.silenceLine = style.classic; // FL's 1 px silence line, in the waveform's colour (Live draws one too: audiolane y 476)
  3823. // issue #277 (round 190qr): zoomed in under ui::sampleDetailFrames frames a pixel (FL's deeper zoom), the samples
  3824. // themselves (the file the summary was made of; WaveformView checks it is the same length)
  3825. if (std::abs (perTick / pixelsPerTick) < ui::sampleDetailFrames)
  3826. style.samples = engine.getSampleLibrary().findLoaded (path);
  3827. // #230 (round 190nq): FL's View › "Show fade previews" (on by default): the waveform with the clip's fades applied
  3828. if (showFadePreviews && (c.effectiveFadeIn() > 0 || c.effectiveFadeOut() > 0))
  3829. style.envelope = [&c, left = r.getX(), ppt = pixelsPerTick] (float x) { return clipops::fadePreviewGain (c, (double) (x - left) / ppt); };
  3830. const uitrace::Part tally (uitrace::part::waveform);
  3831. // warp markers that bend the tempo (round 175a): each stretch between two markers drawn at its own speed
  3832. auto markers = forward ? warpedit::playedMarkers (channel.sampler, total / summary->sampleRate) : std::vector<WarpPoint> {};
  3833. const auto index = playlistIndexOf (song, c);
  3834. if (drag == Drag::warpMarker && warpClip == index && warpIndex >= 0 && warpIndex < (int) markers.size())
  3835. markers[(std::size_t) warpIndex].beats = warpBeat;
  3836. if (markers.size() >= 3)
  3837. {
  3838. for (std::size_t k = 0; k + 1 < markers.size(); ++k)
  3839. {
  3840. const auto x0 = tickToX (warpedit::clipTickOfBeat (c, markers[k].beats)), x1 = tickToX (warpedit::clipTickOfBeat (c, markers[k + 1].beats));
  3841. const auto part = wave.withLeft (juce::jmax (wave.getX(), (float) x0)).withRight (juce::jmin (wave.getRight(), (float) x1));
  3842. if (part.getWidth() <= 0.0f || x1 <= x0)
  3843. continue;
  3844. const auto perPixel = (markers[k + 1].seconds - markers[k].seconds) * summary->sampleRate / (x1 - x0);
  3845. const juce::Graphics::ScopedSaveState keep (g);
  3846. g.reduceClipRegion (part.toNearestIntEdges());
  3847. ui::paintWaveform (g, part, *summary, markers[k].seconds * summary->sampleRate + (part.getX() - x0) * perPixel, perPixel, style);
  3848. }
  3849. }
  3850. else
  3851. ui::paintWaveform (g, wave, *summary, startFrame, (forward ? perTick : -perTick) / pixelsPerTick, style);
  3852. }
  3853. if (fl)
  3854. paintFlClipTitle (g, r, look, name, ClipGlyph::audio, shownMuted (engine.getSong(), c), band, heldTitleLeft, false);
  3855. else if (! liveLook)
  3856. paintClipOutline (g, r, colour, false, false);
  3857. // the warp markers: small flags on the body's top edge, the end marker included (the start one never moves). Live's
  3858. // look (round 190jn, CL-18): only while they are edited — the clip under the mouse or a marker being dragged; none on a
  3859. // collapsed lane
  3860. if (const auto index = playlistIndexOf (song, c);
  3861. ! liveLook || (! body.isEmpty() && index >= 0 && (hover.clip == index || (drag == Drag::warpMarker && warpClip == index))))
  3862. {
  3863. auto markers = index >= 0 ? clipWarpMarkers (index) : std::vector<WarpPoint> {};
  3864. if (drag == Drag::warpMarker && warpClip == index && warpIndex >= 0 && warpIndex < (int) markers.size())
  3865. markers[(std::size_t) warpIndex].beats = warpBeat;
  3866. // the accent (the audio editor's warp marker colour) with a dark outline: readable on any clip colour (the
  3867. // clip's own content colour was hard to see on pale clips, coordinator's review of 175a M3)
  3868. const auto flag = theme::colour::accent;
  3869. for (std::size_t k = 1; k < markers.size(); ++k)
  3870. {
  3871. const auto x = (float) tickToX (warpedit::clipTickOfBeat (c, markers[k].beats));
  3872. if (x < body.getX() - 0.5f || x > body.getRight() + 0.5f)
  3873. continue;
  3874. const auto active = drag == Drag::warpMarker && warpClip == index && warpIndex == (int) k;
  3875. g.setColour (flag.withAlpha (active ? 0.95f : 0.6f));
  3876. g.drawVerticalLine ((int) std::round (x), body.getY() + 6.0f, body.getBottom());
  3877. juce::Path p;
  3878. p.addTriangle (x - 4.5f, body.getY(), x + 4.5f, body.getY(), x, body.getY() + 7.0f);
  3879. g.setColour (active ? flag.brighter (0.3f) : flag);
  3880. g.fillPath (p);
  3881. g.setColour (theme::colour::bg0.withAlpha (0.8f));
  3882. g.strokePath (p, juce::PathStrokeType (1.0f));
  3883. }
  3884. }
  3885. // the clip's own envelope (round 190gi): the lane shown is edited here like an automation clip's curve; a clip whose
  3886. // envelope is hidden still shows its volume line faintly
  3887. // (round 190jn: Live's look on a collapsed lane is the clip's strip only — no envelope, no fades: drawn there they were
  3888. // paths over an empty body, a Direct2D geometry each, for every audio clip of the view)
  3889. const auto liveCollapsed = liveLook.has_value() && body.isEmpty();
  3890. if (const auto* envelope = clipenv::of (song, c); ! liveCollapsed && envelope != nullptr && (envelope->shown != 0 || clipenv::active (*envelope)))
  3891. paintClipEnvelope (g, c, *envelope);
  3892. // fades: the gain curve as the voice plays it (FL's S curve or a straight line, bent by the tension; round 190jz,
  3893. // issue #194: before, every fade but a crossfade was drawn straight), in the waveform's colour as FL 2026 draws it;
  3894. // the other layouts also shade what the fade takes away. An automatic crossfade (round 166e) replaces that side's fade
  3895. // with FL's two crossing S-curves over the overlap. The handles and the tension circles: paintFadeHandles (hover).
  3896. const auto fadeIn = c.effectiveFadeIn(), fadeOut = c.effectiveFadeOut();
  3897. if ((fadeIn > 0 || fadeOut > 0) && ! liveCollapsed && body.getHeight() >= 3.0f)
  3898. {
  3899. const auto inX = r.getX() + (float) (fadeIn * pixelsPerTick);
  3900. const auto outX = r.getRight() - (float) (fadeOut * pixelsPerTick);
  3901. // (round 190oj CS-30, issue #230's reference img4: Live blends the faded part ~50 % toward a mid grey and draws the
  3902. // curve as a thin crimson line; LYNX's other looks keep the darker shade and the content colour)
  3903. const auto shade = liveLook ? juce::Colour (0x80555555) : theme::colour::bg0.withAlpha (0.45f);
  3904. const auto line = liveLook ? juce::Colour (0xff8e425f)
  3905. : fl ? (band ? look.compactContent : look.content) : simpleLook ? simpleLook->content : clipContentColour (colour).withAlpha (0.9f);
  3906. // the gain curve from x0 to x1 (rising: a fade in), as a line along the body
  3907. auto curve = [&body] (float x0, float x1, bool rising, bool cross, bool equalPower, bool linear, float tension) {
  3908. juce::Path p;
  3909. const auto bent = cross || equalPower || ! linear || tension != 0.0f;
  3910. // (a segment every 6 px, at most 16: the S curve reads the same and Thief's ~1 500 clips paint as fast as
  3911. // before round 190jz's curves, --paintbench; a fade under 4 px is a straight line)
  3912. const auto steps = bent && std::abs (x1 - x0) >= 4.0f ? juce::jlimit (2, 16, (int) std::abs (x1 - x0) / 6) : 1;
  3913. for (int k = 0; k <= steps; ++k)
  3914. {
  3915. const auto t = (float) k / (float) steps;
  3916. const auto level = equalPower ? clipops::equalPowerCurve (rising ? t : 1.0f - t)
  3917. : cross ? clipops::crossfadeCurve (rising ? t : 1.0f - t)
  3918. : clipops::fadeLevel (t, rising, linear, tension);
  3919. const juce::Point<float> q { x0 + (x1 - x0) * t, body.getBottom() - level * body.getHeight() };
  3920. if (k == 0)
  3921. p.startNewSubPath (q);
  3922. else
  3923. p.lineTo (q);
  3924. }
  3925. return p;
  3926. };
  3927. // (round 190qk: both fades' shades are one path, filled once before the lines — one fill per clip instead of two; a
  3928. // fade under 3 px has no area to see under its line. With Shade faded audio on, Thief's Playlist cost +2.2 % a frame
  3929. // with a fill per fade, +1.3 % this way)
  3930. const auto shaded = ! fl || shadeFadedAudio;
  3931. juce::Path shadeArea;
  3932. const auto addShade = [&] (float x0, float x1, bool rising, bool cross, bool equalPower, bool linear, float tension) {
  3933. if (! shaded || std::abs (x1 - x0) < 3.0f)
  3934. return;
  3935. auto area = curve (x0, x1, rising, cross, equalPower, linear, tension);
  3936. area.lineTo (x1, body.getY());
  3937. area.lineTo (x0, body.getY());
  3938. area.closeSubPath();
  3939. shadeArea.addPath (area);
  3940. };
  3941. auto paintFade = [&] (float x0, float x1, bool rising, bool cross, bool equalPower, bool linear, float tension) {
  3942. auto edge = curve (x0, x1, rising, cross, equalPower, linear, tension);
  3943. g.setColour (line);
  3944. g.strokePath (edge, juce::PathStrokeType (fl ? 1.6f : 1.2f));
  3945. if (cross || equalPower) // the neighbour's side of the crossfade, which this clip covers
  3946. {
  3947. g.setColour (line.withMultipliedAlpha (0.6f));
  3948. g.strokePath (curve (x0, x1, ! rising, cross, equalPower, false, 0.0f), juce::PathStrokeType (1.0f));
  3949. }
  3950. };
  3951. if (fadeIn > 0)
  3952. addShade (r.getX(), inX, true, c.crossfadeIn > 0, (c.fadeCurve & 1) != 0, (c.linearFades & 1) != 0, c.fadeInTension);
  3953. if (fadeOut > 0)
  3954. addShade (outX, r.getRight(), false, c.crossfadeOut > 0, (c.fadeCurve & 2) != 0, (c.linearFades & 2) != 0, c.fadeOutTension);
  3955. if (! shadeArea.isEmpty())
  3956. {
  3957. g.setColour (shade);
  3958. g.fillPath (shadeArea);
  3959. }
  3960. if (fadeIn > 0)
  3961. paintFade (r.getX(), inX, true, c.crossfadeIn > 0, (c.fadeCurve & 1) != 0, (c.linearFades & 1) != 0, c.fadeInTension);
  3962. if (fadeOut > 0)
  3963. paintFade (outX, r.getRight(), false, c.crossfadeOut > 0, (c.fadeCurve & 2) != 0, (c.linearFades & 2) != 0, c.fadeOutTension);
  3964. }
  3965. }
  3966. juce::Colour PlaylistComponent::audioClipColour (const ChannelDef& channel)
  3967. {
  3968. return channel.colour != 0 ? theme::tame (juce::Colour (channel.colour)) : theme::colour::audioClip;
  3969. }
  3970. std::optional<theme::ClipLook> PlaylistComponent::simpleClipLook (const Clip& c) const
  3971. {
  3972. // round 190jc (design190ia SG-5, BandLab: a clip in its TRACK's colour, audio and MIDI alike; the Simple layout only)
  3973. if (! simpleHeaders || c.kind == ClipKind::automation)
  3974. return std::nullopt;
  3975. const auto& song = engine.getSong();
  3976. juce::Colour own;
  3977. if (c.kind == ClipKind::audio)
  3978. {
  3979. if (c.channel < 0 || c.channel >= (int) song.channels.size())
  3980. return std::nullopt;
  3981. own = audioClipColour (song.channels[(std::size_t) c.channel]);
  3982. }
  3983. else if (c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  3984. own = theme::tame (patternColour (song, c.pattern));
  3985. else
  3986. return std::nullopt;
  3987. return theme::clipBody (own, trackColourIn (song, c.track), c.kind, theme::ClipStyle::bandlabHue);
  3988. }
  3989. void PlaylistComponent::paintAutomationClip (juce::Graphics& g, const Clip& c, juce::Rectangle<float> r)
  3990. {
  3991. const auto& song = engine.getSong();
  3992. if (c.automation < 0 || c.automation >= (int) song.automations.size())
  3993. return;
  3994. const auto& automation = song.automations[(std::size_t) c.automation];
  3995. const auto colour = automation.target.kind == AutomationTargetKind::none ? theme::colour::textDisabled
  3996. : theme::colour::automation.withMultipliedSaturation (0.75f).withMultipliedBrightness (0.8f);
  3997. // round 190ig (FM-22): in the Pattern layout FL's recipe in the clip's own colour (FL: its Automation Clip channel's)
  3998. const auto fl = flClipLook();
  3999. const auto band = fl && r.getHeight() + 1.0f < (float) flBandBelow;
  4000. const auto look = fl ? theme::clipBody (juce::Colour (automation.colour), trackColourIn (song, c.track), ClipKind::automation, theme::ClipStyle::flTint)
  4001. : theme::ClipLook {};
  4002. // round 190jn (CL-17): Live's look — the block in the clip colour, the curve dark under the strip; nothing more on a collapsed lane
  4003. const auto liveLook = liveArrangeLook() ? std::optional<theme::ClipLook> (liveClipLook (c)) : std::nullopt;
  4004. juce::Rectangle<float> liveBody;
  4005. if (fl)
  4006. paintFlClipFrame (g, r, look, band);
  4007. else if (liveLook)
  4008. {
  4009. liveBody = paintLiveClipFrame (g, r, *liveLook, juce::String::fromUTF8 (automation.name.c_str()));
  4010. if (liveBody.getHeight() < 6.0f) // (= automationBody: none on a collapsed lane)
  4011. return;
  4012. }
  4013. else
  4014. {
  4015. paintClipFrame (g, r, colour, juce::String::fromUTF8 (automation.name.c_str()), ClipGlyph::automation, shownMuted (engine.getSong(), c));
  4016. paintClipOutline (g, r, colour, false, false);
  4017. }
  4018. // automation curve over the clip's range
  4019. const auto body = liveLook ? liveBody.reduced (1.0f, 2.0f)
  4020. : fl && ! band ? r.withTrimmedTop (flHeaderHeight (r)).reduced (1.0f, 2.0f)
  4021. : r.withTrimmedTop (juce::jmin (14.0f, r.getHeight() * 0.4f)).reduced (1.0f, 2.0f); // = automationBody
  4022. const auto clip = g.getClipBounds().toFloat();
  4023. juce::Path curve;
  4024. bool started = false;
  4025. auto lastY = 0.0f;
  4026. // (samples every 2 px on the body's own grid, from a little before the repainted area to a little after it: a
  4027. // repaint of part of the clip draws the same line as a paint of all of it; round 174f)
  4028. const auto lastX = std::min (body.getRight(), clip.getRight() + 4.0f);
  4029. for (auto k = (int) std::floor (juce::jmax (0.0f, clip.getX() - 4.0f - body.getX()) / 2.0f);; ++k)
  4030. {
  4031. const auto x = body.getX() + 2.0f * (float) k;
  4032. if (x > lastX)
  4033. break;
  4034. const auto yAt = [&] (int sx) {
  4035. const auto songTick = xToTick (sx);
  4036. return body.getBottom() - automation.playAt ((double) c.offset + songTick - (double) c.start, songTick) * body.getHeight(); // (with its LFO)
  4037. };
  4038. const auto y = yAt ((int) x);
  4039. if (! started)
  4040. curve.startNewSubPath (x, y);
  4041. else // (round 190bw: Hold, Stairs and Pulse segments keep square corners)
  4042. automationLineTo (curve, x - 2.0f, lastY, x, y, [&] { return yAt ((int) x - 1); });
  4043. lastY = y;
  4044. started = true;
  4045. }
  4046. if (fl)
  4047. {
  4048. // FL: the area under the curve lit faintly, the curve in the clip's light tint, then the header's glyph and name
  4049. if (started && ! look.contentFill.isTransparent())
  4050. {
  4051. auto under = curve;
  4052. under.lineTo (lastX, body.getBottom() + 2.0f);
  4053. under.lineTo (curve.getBounds().getX(), body.getBottom() + 2.0f);
  4054. under.closeSubPath();
  4055. g.setColour (look.contentFill);
  4056. g.fillPath (under);
  4057. }
  4058. g.setColour (look.content);
  4059. g.strokePath (curve, juce::PathStrokeType (1.5f));
  4060. paintFlClipTitle (g, r, look, juce::String::fromUTF8 (automation.name.c_str()), ClipGlyph::automation, shownMuted (engine.getSong(), c), band, heldTitleLeft, false);
  4061. }
  4062. else
  4063. {
  4064. g.setColour (liveLook ? liveLook->content
  4065. : automation.target.kind == AutomationTargetKind::none ? theme::colour::textSecondary : theme::colour::automation.brighter (0.3f));
  4066. g.strokePath (curve, juce::PathStrokeType (1.5f));
  4067. }
  4068. // round 165: FL's tension handles between the points (hollow circles: drag up / down bends the segment)
  4069. if (r.getWidth() > 24.0f && body.getHeight() >= 10.0f)
  4070. for (int i = 0; i + 1 < (int) automation.points.size(); ++i)
  4071. {
  4072. const auto& a = automation.points[(std::size_t) i];
  4073. const auto& b = automation.points[(std::size_t) i + 1];
  4074. const auto x0 = tickToX ((double) (c.start + a.tick - c.offset)), x1 = tickToX ((double) (c.start + b.tick - c.offset));
  4075. const auto mid = 0.5 * (double) (a.tick + b.tick);
  4076. const auto midX = (float) (0.5 * (x0 + x1));
  4077. if (x1 - x0 < 16.0 || midX < body.getX() || midX > body.getRight())
  4078. continue;
  4079. const auto y = body.getBottom() - automation.valueAt (mid) * body.getHeight();
  4080. g.setColour (theme::colour::automation.brighter (0.2f).withAlpha (0.9f));
  4081. g.drawEllipse (midX - 3.0f, y - 3.0f, 6.0f, 6.0f, 1.2f);
  4082. }
  4083. // the points inside the clip, as handles (edited right here)
  4084. if (r.getWidth() > 24.0f)
  4085. for (const auto& p : automation.points)
  4086. {
  4087. const auto songTick = (double) (c.start + p.tick - c.offset);
  4088. if (songTick < (double) c.start || songTick > (double) c.end())
  4089. continue;
  4090. const auto x = (float) tickToX (songTick);
  4091. const auto y = body.getBottom() - p.value * body.getHeight();
  4092. g.setColour (theme::colour::bg0);
  4093. g.fillEllipse (x - 3.5f, y - 3.5f, 7.0f, 7.0f);
  4094. g.setColour (theme::colour::automation.brighter (0.5f));
  4095. g.fillEllipse (x - 2.5f, y - 2.5f, 5.0f, 5.0f);
  4096. }
  4097. }
  4098. // Round 190oo (CS-19, Live 12 warp190cg-08a-live-automation-lane-before-fold.png, measured): an automation lane is one
  4099. // envelope over the lane's whole width — a 2 px #ff4d47 line, each breakpoint a hollow ring of 6 px in the same red —
  4100. // over the lane's own background, no clip block. The clips of the lane join into the one line: before the first clip it
  4101. // holds the first clip's start value, between and after them the value the clip before ended on (what LYNX plays there).
  4102. // Only the repainted columns are sampled (every 2 px on each clip's own grid, as paintAutomationClip, so a partial repaint
  4103. // draws the same line); a lane list is worked out with the projection, not here.
  4104. void PlaylistComponent::paintLiveEnvelopeLanes (juce::Graphics& g, juce::Rectangle<int> grid)
  4105. {
  4106. if (laneClips.empty())
  4107. return;
  4108. const auto& song = engine.getSong();
  4109. const auto visible = g.getClipBounds().toFloat().getIntersection (grid.toFloat());
  4110. if (visible.isEmpty())
  4111. return;
  4112. const auto rows = juce::jmin ((int) laneClips.size(), numTracks());
  4113. // (the lists are made at the change message after an edit: a paint before it must not read a removed clip)
  4114. const auto valid = [&song] (int i) {
  4115. if (i < 0 || i >= (int) song.playlist.size())
  4116. return false;
  4117. const auto& c = song.playlist[(std::size_t) i];
  4118. return c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size();
  4119. };
  4120. // round 190pb: the lanes' drawings stay while the song, the lists, the view and the display scale do
  4121. const auto scale = g.getInternalContext().getPhysicalPixelScaleFactor();
  4122. auto& cache = envelopeCache;
  4123. if (cache.publish != engine.getPublishCount() || cache.projection != projectionStamp || cache.pixelsPerTick != pixelsPerTick
  4124. || cache.scrollTicks != scrollTicks || cache.grid != grid || cache.scale != scale || cache.lanes.size() != laneClips.size())
  4125. {
  4126. cache.publish = engine.getPublishCount();
  4127. cache.projection = projectionStamp;
  4128. cache.pixelsPerTick = pixelsPerTick;
  4129. cache.scrollTicks = scrollTicks;
  4130. cache.grid = grid;
  4131. cache.scale = scale;
  4132. cache.lanes.assign (laneClips.size(), {});
  4133. }
  4134. const juce::Colour envelope { 0xffff4d47 };
  4135. g.setColour (envelope);
  4136. // (a partial repaint: its own part of each line, as before round 190pb, drawn and not kept)
  4137. const auto from = juce::jmax ((float) grid.getX(), visible.getX() - 4.0f), to = juce::jmin ((float) grid.getRight(), visible.getRight() + 4.0f);
  4138. const auto whole = from <= (float) grid.getX() && to >= (float) grid.getRight();
  4139. EnvelopeLane part;
  4140. for (int t = 0; t < rows; ++t)
  4141. {
  4142. const auto& list = laneClips[(std::size_t) t];
  4143. if (list.empty() || ! std::all_of (list.begin(), list.end(), valid))
  4144. continue;
  4145. const auto h = heightOf (t);
  4146. const auto y = trackToY (t);
  4147. if (h < 6 || (float) y > visible.getBottom() || (float) (y + h) < visible.getY())
  4148. continue;
  4149. if (! whole)
  4150. makeEnvelopeLane (part, t, y, h, grid, from, to, scale);
  4151. auto& lane = whole ? cache.lanes[(std::size_t) t] : part;
  4152. if (whole && (lane.track != t || lane.y != y || lane.h != h))
  4153. makeEnvelopeLane (lane, t, y, h, grid, (float) grid.getX(), (float) grid.getRight(), scale);
  4154. // (the flat stretches, then the line, then the rings: the order they were drawn in)
  4155. for (const auto& r : lane.flats)
  4156. g.fillRect (r);
  4157. if (! lane.stroke.isEmpty())
  4158. g.fillPath (lane.stroke);
  4159. if (! lane.rings.isEmpty())
  4160. g.fillPath (lane.rings);
  4161. }
  4162. }
  4163. // Round 190oo (CS-19, Live 12 warp190cg-08a-live-automation-lane-before-fold.png, measured): an automation lane is one
  4164. // envelope over the lane's whole width — a 2 px #ff4d47 line, each breakpoint a hollow ring of 6 px in the same red —
  4165. // over the lane's own background, no clip block. The clips of the lane join into the one line: before the first clip it
  4166. // holds the first clip's start value, between and after them the value the clip before ended on (what LYNX plays there).
  4167. // Sampled every 2 px on each clip's own grid, as paintAutomationClip; a lane list is worked out with the projection, not
  4168. // here. Round 190pb: worked out into `lane` (a whole frame's is kept by paintLiveEnvelopeLanes).
  4169. void PlaylistComponent::makeEnvelopeLane (EnvelopeLane& lane, int t, int y, int h, juce::Rectangle<int> grid, float from, float to, float scale) const
  4170. {
  4171. lane = {};
  4172. lane.track = t;
  4173. lane.y = y;
  4174. lane.h = h;
  4175. const auto& song = engine.getSong();
  4176. const auto& list = laneClips[(std::size_t) t];
  4177. // the line's range: the lane above Live's 2 px separator, room for the rings at the top and the bottom
  4178. const auto body = juce::Rectangle<float> ((float) grid.getX(), (float) y + 3.0f, (float) grid.getWidth(), juce::jmax (1.0f, (float) h - 8.0f));
  4179. const auto yOf = [&body] (float v) { return body.getBottom() - juce::jlimit (0.0f, 1.0f, v) * body.getHeight(); };
  4180. juce::Path line;
  4181. bool started = false;
  4182. const auto lineTo = [&line, &started] (float px, float py) {
  4183. if (! started)
  4184. line.startNewSubPath (px, py);
  4185. else
  4186. line.lineTo (px, py);
  4187. started = true;
  4188. };
  4189. // (perf: the flat stretches between and after the clips are filled 2 px bars, not stroked path — a lane is mostly
  4190. // flat and stroking the whole width of every lane cost +1.3 % in the tall-lane arrangement, --paintbench)
  4191. const auto flat = [&lane] (float x0, float x1, float py) {
  4192. if (x1 > x0)
  4193. lane.flats.push_back (juce::Rectangle<float> (x0, py - 1.0f, x1 - x0, 2.0f));
  4194. };
  4195. auto level = cliplanes::clipStartValue (song, song.playlist[(std::size_t) list.front()]);
  4196. auto cursor = from;
  4197. for (const auto i : list)
  4198. {
  4199. const auto& c = song.playlist[(std::size_t) i];
  4200. const auto& automation = song.automations[(std::size_t) c.automation];
  4201. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  4202. if (x1 <= from)
  4203. {
  4204. level = cliplanes::clipEndValue (song, c);
  4205. continue;
  4206. }
  4207. if (x0 >= to)
  4208. break;
  4209. if (x0 > cursor) // (flat up to the clip)
  4210. flat (cursor, x0, yOf (level));
  4211. const auto a = juce::jmax (x0, cursor), b = juce::jmin (x1, to); // (an overlapping clip: from where the last one ended)
  4212. if (a >= b)
  4213. continue;
  4214. // (the clip's curve: a new subpath from the flat level, so the step into its first value is drawn)
  4215. line.startNewSubPath (a, yOf (level));
  4216. started = true;
  4217. const auto yAt = [&] (float sx) {
  4218. const auto songTick = xToTick ((int) sx);
  4219. return yOf (automation.playAt ((double) c.offset + songTick - (double) c.start, songTick)); // (with its LFO)
  4220. };
  4221. auto lastY = 0.0f;
  4222. bool first = true;
  4223. for (auto k = (int) std::floor ((a - x0) / 2.0f);; ++k)
  4224. {
  4225. const auto x = juce::jmin (b, x0 + 2.0f * (float) k);
  4226. const auto py = yAt (x);
  4227. if (first || ! started)
  4228. lineTo (juce::jmax (a, x), py);
  4229. else // (Hold, Stairs and Pulse segments keep square corners, as in the clip)
  4230. automationLineTo (line, x - 2.0f, lastY, x, py, [&] { return yAt (x - 1.0f); });
  4231. lastY = py;
  4232. first = false;
  4233. if (x >= b)
  4234. break;
  4235. }
  4236. cursor = b;
  4237. level = cliplanes::clipEndValue (song, c);
  4238. }
  4239. if (cursor < to) // (after the last clip: the value it ended on, to the lane's end)
  4240. flat (cursor, to, yOf (level));
  4241. if (started && ! line.isEmpty()) // (what Graphics::strokePath fills: the outline made at the display's scale)
  4242. juce::PathStrokeType (2.0f).createStrokedPath (lane.stroke, line, {}, scale);
  4243. // the breakpoints: hollow rings (the lane shows through), the clips' own points
  4244. // (Live shows a breakpoint as a ring only where it can be picked: on a densely recorded envelope the rings would
  4245. // merge into a thick band, so a ring closer than 8 px to the last one drawn is left out; the line still has it)
  4246. if (h < 10)
  4247. return;
  4248. auto lastRing = -1.0e9f;
  4249. for (const auto i : list)
  4250. {
  4251. const auto& c = song.playlist[(std::size_t) i];
  4252. const auto x0 = tickToX ((double) c.start), x1 = tickToX ((double) c.end());
  4253. if (x1 < (double) from - 4.0 || x0 > (double) to + 4.0)
  4254. continue;
  4255. for (const auto& p : song.automations[(std::size_t) c.automation].points)
  4256. {
  4257. const auto songTick = (double) (c.start + p.tick - c.offset);
  4258. if (songTick < (double) c.start || songTick > (double) c.end())
  4259. continue;
  4260. const auto x = (float) tickToX (songTick);
  4261. if (x < from - 4.0f || x > to + 4.0f || x - lastRing < 8.0f)
  4262. continue;
  4263. lastRing = x;
  4264. // (Graphics::drawEllipse of a circle with a 1.5 px line: the circle 0.75 px larger and 0.75 px smaller, even-odd;
  4265. // the rings are 8 px apart or more, so one path of them all covers each pixel as drawing them one by one)
  4266. const auto area = juce::Rectangle<float> (x - 2.5f, yOf (p.value) - 2.5f, 5.0f, 5.0f);
  4267. lane.rings.addEllipse (area.expanded (0.75f));
  4268. lane.rings.addEllipse (area.reduced (0.75f));
  4269. }
  4270. }
  4271. lane.rings.setUsingNonZeroWinding (false);
  4272. }
  4273. void PlaylistComponent::paintClipEnvelope (juce::Graphics& g, const Clip& c, const ClipEnvelope& envelope)
  4274. {
  4275. const auto lane = envelope.shown != 0 ? envelope.shown : clipenv::volumeLane;
  4276. const auto& points = clipenv::laneOf (envelope, lane);
  4277. if (envelope.shown == 0 && clipenv::flat (points, clipenv::neutralOf (lane)))
  4278. return;
  4279. const auto body = automationBody (c);
  4280. const auto shown = envelope.shown != 0;
  4281. const auto clip = g.getClipBounds().toFloat();
  4282. const auto valueAt = [&] (double tick) { return points.empty() ? clipenv::neutralOf (lane) : automationCurveAt (points, tick); };
  4283. const auto yAt = [&] (int sx) { return body.getBottom() - valueAt (clipenv::clipTick (c, xToTick (sx))) * body.getHeight(); };
  4284. // the pan lane's centre line, so left and right read at a glance
  4285. if (shown && lane == clipenv::panLane)
  4286. {
  4287. g.setColour (theme::colour::bg0.withAlpha (0.35f));
  4288. g.drawHorizontalLine ((int) std::round (body.getCentreY()), body.getX(), body.getRight());
  4289. }
  4290. juce::Path curve;
  4291. bool started = false;
  4292. auto lastY = 0.0f;
  4293. // (sampled every 2 px on the body's grid from a little before the repainted area, as the automation clips are)
  4294. const auto lastX = std::min (body.getRight(), clip.getRight() + 4.0f);
  4295. for (auto k = (int) std::floor (juce::jmax (0.0f, clip.getX() - 4.0f - body.getX()) / 2.0f);; ++k)
  4296. {
  4297. const auto x = body.getX() + 2.0f * (float) k;
  4298. if (x > lastX)
  4299. break;
  4300. const auto y = yAt ((int) x);
  4301. if (! started)
  4302. curve.startNewSubPath (x, y);
  4303. else
  4304. automationLineTo (curve, x - 2.0f, lastY, x, y, [&] { return yAt ((int) x - 1); });
  4305. lastY = y;
  4306. started = true;
  4307. }
  4308. // dark under-stroke: readable over any waveform colour
  4309. g.setColour (theme::colour::bg0.withAlpha (shown ? 0.7f : 0.35f));
  4310. g.strokePath (curve, juce::PathStrokeType (shown ? 3.0f : 2.0f));
  4311. g.setColour (theme::colour::automation.brighter (0.3f).withAlpha (shown ? 1.0f : 0.55f));
  4312. g.strokePath (curve, juce::PathStrokeType (shown ? 1.5f : 1.0f));
  4313. if (! shown || body.getWidth() <= 24.0f)
  4314. return;
  4315. // the tension handles between points and the points, as on an automation clip (round 165)
  4316. for (int i = 0; i + 1 < (int) points.size(); ++i)
  4317. {
  4318. const auto& a = points[(std::size_t) i];
  4319. const auto& b = points[(std::size_t) i + 1];
  4320. const auto x0 = tickToX ((double) (c.start + a.tick - c.offset)), x1 = tickToX ((double) (c.start + b.tick - c.offset));
  4321. const auto midX = (float) (0.5 * (x0 + x1));
  4322. if (x1 - x0 < 16.0 || midX < body.getX() || midX > body.getRight() || body.getHeight() < 10.0f)
  4323. continue;
  4324. const auto y = body.getBottom() - valueAt (0.5 * (double) (a.tick + b.tick)) * body.getHeight();
  4325. g.setColour (theme::colour::automation.brighter (0.2f).withAlpha (0.9f));
  4326. g.drawEllipse (midX - 3.0f, y - 3.0f, 6.0f, 6.0f, 1.2f);
  4327. }
  4328. for (const auto& p : points)
  4329. {
  4330. const auto songTick = (double) (c.start + p.tick - c.offset);
  4331. if (songTick < (double) c.start || songTick > (double) c.end())
  4332. continue;
  4333. const auto x = (float) tickToX (songTick);
  4334. const auto y = body.getBottom() - p.value * body.getHeight();
  4335. g.setColour (theme::colour::bg0);
  4336. g.fillEllipse (x - 3.5f, y - 3.5f, 7.0f, 7.0f);
  4337. g.setColour (theme::colour::automation.brighter (0.5f));
  4338. g.fillEllipse (x - 2.5f, y - 2.5f, 5.0f, 5.0f);
  4339. }
  4340. // the lane's name at the body's top left: "Volume" / "Pan"
  4341. g.setColour (theme::colour::automation.brighter (0.4f));
  4342. g.setFont (theme::font (theme::type::caption));
  4343. g.drawText (lane == clipenv::panLane ? tr ("Pan") : tr ("Volume"), body.reduced (4.0f, 1.0f).withHeight (12.0f).toNearestInt(),
  4344. juce::Justification::topRight, false);
  4345. }
  4346. juce::Rectangle<float> PlaylistComponent::automationBody (const Clip& c) const
  4347. {
  4348. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  4349. const auto y = (float) trackToY (c.track);
  4350. const auto r = clipRectAt (x0, x1, y, heightOf (c.track));
  4351. if (flClipLook() && heightOf (c.track) >= flBandBelow) // (FL: the curve under the header band)
  4352. return r.withTrimmedTop (flHeaderHeight (r)).reduced (1.0f, 2.0f);
  4353. if (liveArrangeLook()) // (round 190jn: Live's body under the 17 px strip, as paintLiveClipFrame; none on a collapsed lane)
  4354. return r.getHeight() >= (float) liveStripHeight + 6.0f ? r.withTrimmedTop ((float) liveStripHeight).withTrimmedLeft (1.0f).reduced (1.0f, 2.0f)
  4355. : juce::Rectangle<float>();
  4356. return r.withTrimmedTop (juce::jmin (14.0f, r.getHeight() * 0.4f)).reduced (1.0f, 2.0f);
  4357. }
  4358. // --- automation lanes (round 177b) -------------------------------------------------------------------------------
  4359. // Optional, off by default (Playlist › Automation lanes). A track's lanes sit under its row; a lane's points are in
  4360. // song time. Gestures, the same in every tool: [LMB] adds a point (and drags it), drag a point moves it, [RMB] on a
  4361. // point deletes it, [Alt]+drag on the line bends the segment, [RMB] elsewhere opens the lane menu.
  4362. int PlaylistComponent::laneHeightOf (const AutomationLane& lane) const
  4363. {
  4364. return scaledHeight (lane.height > 0 ? polish::clampTrackHeight (lane.height) : 34);
  4365. }
  4366. int PlaylistComponent::laneBlockHeight (int track) const
  4367. {
  4368. const auto& song = engine.getSong();
  4369. if (! autolanes::shown() || track < 0 || track >= (int) song.playlistTracks.size() || simpleAutoOn (track))
  4370. return 0; // (round 190jr: the Simple automation view draws one lane over the track's own row instead)
  4371. const auto& t = song.playlistTracks[(std::size_t) track];
  4372. if (t.lanes.empty() || t.lanesFolded || t.folded || noteedit::isFoldedAway (song, track) || (t.hidden && ! showHiddenTracks))
  4373. return 0;
  4374. int h = 0;
  4375. for (const auto& lane : t.lanes)
  4376. h += laneHeightOf (lane);
  4377. return h;
  4378. }
  4379. juce::Rectangle<int> PlaylistComponent::laneRow (int track, int lane) const
  4380. {
  4381. if (simpleAutoOn (track)) // round 190jr: the shown parameter's lane is the track's own row
  4382. return lane >= 0 && lane == simpleAutoLane (track) ? juce::Rectangle<int> (0, trackToY (track), getWidth(), heightOf (track)) : juce::Rectangle<int>();
  4383. if (laneBlockHeight (track) <= 0)
  4384. return {};
  4385. const auto& lanes = engine.getSong().playlistTracks[(std::size_t) track].lanes;
  4386. if (lane < 0 || lane >= (int) lanes.size())
  4387. return {};
  4388. auto y = trackToY (track) + heightOf (track);
  4389. for (int i = 0; i < lane; ++i)
  4390. y += laneHeightOf (lanes[(std::size_t) i]);
  4391. return { 0, y, getWidth(), laneHeightOf (lanes[(std::size_t) lane]) };
  4392. }
  4393. juce::Rectangle<float> PlaylistComponent::laneBody (int track, int lane) const
  4394. {
  4395. const auto row = laneRow (track, lane);
  4396. const auto grid = gridArea();
  4397. return juce::Rectangle<float> ((float) grid.getX(), (float) row.getY() + 4.0f, (float) grid.getWidth(), juce::jmax (2.0f, (float) row.getHeight() - 8.0f));
  4398. }
  4399. PlaylistComponent::LaneHit PlaylistComponent::laneAt (juce::Point<int> p) const
  4400. {
  4401. if (simpleAutomation && p.x >= headerWidth && p.y >= tracksTop() && p.y < gridArea().getBottom()) // round 190jr
  4402. if (const auto track = yToTrack (p.y); simpleAutoOn (track))
  4403. {
  4404. const auto lane = simpleAutoLane (track);
  4405. return lane >= 0 ? LaneHit { track, lane } : LaneHit {};
  4406. }
  4407. if (! autolanes::shown() || p.y < headerHeight || p.y >= gridArea().getBottom())
  4408. return {};
  4409. const auto track = yToTrack (p.y);
  4410. if (laneBlockHeight (track) <= 0 || p.y < trackToY (track) + heightOf (track))
  4411. return {};
  4412. const auto& lanes = engine.getSong().playlistTracks[(std::size_t) track].lanes;
  4413. for (int i = 0; i < (int) lanes.size(); ++i)
  4414. if (const auto row = laneRow (track, i); p.y >= row.getY() && p.y < row.getBottom())
  4415. return { track, i };
  4416. return {};
  4417. }
  4418. int PlaylistComponent::laneAutomation (int track, int lane) const
  4419. {
  4420. const auto& song = engine.getSong();
  4421. if (track < 0 || track >= (int) song.playlistTracks.size() || lane < 0 || lane >= (int) song.playlistTracks[(std::size_t) track].lanes.size())
  4422. return -1;
  4423. const auto a = song.playlistTracks[(std::size_t) track].lanes[(std::size_t) lane].automation;
  4424. return a >= 0 && a < (int) song.automations.size() ? a : -1;
  4425. }
  4426. int PlaylistComponent::lanePointAt (int track, int lane, juce::Point<int> p) const
  4427. {
  4428. const auto a = laneAutomation (track, lane);
  4429. if (a < 0)
  4430. return -1;
  4431. const auto body = laneBody (track, lane);
  4432. const auto& points = engine.getSong().automations[(std::size_t) a].points;
  4433. int best = -1;
  4434. auto bestDistance = 6.0f;
  4435. for (int i = 0; i < (int) points.size(); ++i)
  4436. {
  4437. const auto x = (float) tickToX ((double) points[(std::size_t) i].tick);
  4438. const auto y = body.getBottom() - laneShown (a, points[(std::size_t) i].value) * body.getHeight();
  4439. if (const auto d = juce::Point<float> (x, y).getDistanceFrom (p.toFloat()); d <= bestDistance)
  4440. {
  4441. bestDistance = d;
  4442. best = i;
  4443. }
  4444. }
  4445. return best;
  4446. }
  4447. juce::Rectangle<int> PlaylistComponent::trackLaneArrow (int track) const
  4448. {
  4449. const auto& song = engine.getSong();
  4450. if (track < 0 || track >= (int) song.playlistTracks.size() || noteedit::isFoldedAway (song, track))
  4451. return {};
  4452. // (round 177b's lanes, or round 190jq's automation clips drawn as lanes under it: one arrow folds both)
  4453. if (! (autolanes::shown() && ! song.playlistTracks[(std::size_t) track].lanes.empty()) && projection.childCount (track) == 0)
  4454. return {};
  4455. const auto left = headerIndent (song, track);
  4456. // (the Simple headers: in the first row, beside the M and S buttons, clear of the volume row)
  4457. const auto centreY = simpleHeaders || ! trackVolume (track).isEmpty() ? trackLed (track).getCentreY() : trackToY (track) + heightOf (track) / 2;
  4458. return { left + 4, centreY - 6, 12, 12 };
  4459. }
  4460. juce::Rectangle<int> PlaylistComponent::trackAddLane (int track) const
  4461. {
  4462. if (! autolanes::shown() || heightOf (track) < 16 || noteedit::isFoldedAway (engine.getSong(), track))
  4463. return {};
  4464. // left of the header's buttons (input, record, group arrow, Simple solo, LED)
  4465. auto right = trackLed (track).getX();
  4466. for (const auto& r : { trackSolo (track), trackArrow (track), trackArm (track), trackInput (track) })
  4467. if (! r.isEmpty())
  4468. right = juce::jmin (right, r.getX());
  4469. const auto led = trackLed (track);
  4470. return { right - 22, led.getCentreY() - 7, 20, 14 };
  4471. }
  4472. void PlaylistComponent::paintLanes (juce::Graphics& g, juce::Rectangle<int> grid)
  4473. {
  4474. const auto& song = engine.getSong();
  4475. if (! autolanes::shown())
  4476. return;
  4477. using namespace theme;
  4478. const auto clipArea = g.getClipBounds();
  4479. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  4480. {
  4481. if (laneBlockHeight (t) <= 0)
  4482. continue;
  4483. const auto top = trackToY (t) + heightOf (t);
  4484. if (top > grid.getBottom() || top + laneBlockHeight (t) < grid.getY())
  4485. continue;
  4486. const auto muted = song.isTrackMuted (t);
  4487. for (int i = 0; i < (int) song.playlistTracks[(std::size_t) t].lanes.size(); ++i)
  4488. {
  4489. const auto row = laneRow (t, i);
  4490. if (row.getBottom() < clipArea.getY() || row.getY() > clipArea.getBottom())
  4491. continue;
  4492. const auto a = laneAutomation (t, i);
  4493. if (a < 0)
  4494. continue;
  4495. const auto& automation = song.automations[(std::size_t) a];
  4496. const auto body = laneBody (t, i);
  4497. // where a clip of the same target plays, the clip wins: those spans are shaded
  4498. for (const auto& c : song.playlist)
  4499. {
  4500. if (c.kind != ClipKind::automation || c.muted || song.isTrackMuted (c.track) || c.automation < 0
  4501. || c.automation >= (int) song.automations.size() || c.automation == a
  4502. || ! (song.automations[(std::size_t) c.automation].target == automation.target))
  4503. continue;
  4504. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  4505. if (x1 < (float) grid.getX() || x0 > (float) grid.getRight())
  4506. continue;
  4507. g.setColour (colour::bg0.withAlpha (0.45f));
  4508. g.fillRect (juce::Rectangle<float> (x0, (float) row.getY(), x1 - x0, (float) row.getHeight() - 1.0f));
  4509. }
  4510. const auto line = muted ? colour::textDisabled : colour::automation.brighter (0.3f);
  4511. juce::Path curve, fill;
  4512. bool started = false;
  4513. const auto from = (float) juce::jmax (grid.getX(), clipArea.getX()), to = (float) juce::jmin (grid.getRight(), clipArea.getRight());
  4514. auto lastY = 0.0f;
  4515. for (auto x = from; x <= to; x += 2.0f)
  4516. {
  4517. const auto yAt = [&] (int sx) { return body.getBottom() - laneShown (a, automation.valueAt (xToTick (sx))) * body.getHeight(); };
  4518. const auto y = yAt ((int) x);
  4519. if (! started)
  4520. {
  4521. curve.startNewSubPath (x, y);
  4522. fill.startNewSubPath (x, body.getBottom());
  4523. curve.lineTo (x, y);
  4524. fill.lineTo (x, y);
  4525. }
  4526. else // (round 190bw: Hold, Stairs and Pulse segments keep square corners)
  4527. {
  4528. automationLineTo (curve, x - 2.0f, lastY, x, y, [&] { return yAt ((int) x - 1); });
  4529. automationLineTo (fill, x - 2.0f, lastY, x, y, [&] { return yAt ((int) x - 1); });
  4530. }
  4531. lastY = y;
  4532. started = true;
  4533. }
  4534. if (started)
  4535. {
  4536. fill.lineTo (to, body.getBottom());
  4537. fill.closeSubPath();
  4538. g.setColour (line.withAlpha (0.10f));
  4539. g.fillPath (fill);
  4540. g.setColour (line);
  4541. g.strokePath (curve, juce::PathStrokeType (1.5f));
  4542. }
  4543. for (const auto& p : automation.points)
  4544. {
  4545. const auto x = (float) tickToX ((double) p.tick);
  4546. if (x < from - 4.0f || x > to + 4.0f)
  4547. continue;
  4548. const auto y = body.getBottom() - laneShown (a, p.value) * body.getHeight();
  4549. g.setColour (colour::bg0);
  4550. g.fillEllipse (x - 3.5f, y - 3.5f, 7.0f, 7.0f);
  4551. g.setColour (muted ? colour::textDisabled : colour::automation.brighter (0.5f));
  4552. g.fillEllipse (x - 2.5f, y - 2.5f, 5.0f, 5.0f);
  4553. }
  4554. }
  4555. }
  4556. }
  4557. void PlaylistComponent::paintLaneHeaders (juce::Graphics& g, juce::Rectangle<int> headers)
  4558. {
  4559. const auto& song = engine.getSong();
  4560. if (! autolanes::shown())
  4561. return;
  4562. using namespace theme;
  4563. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  4564. {
  4565. if (laneBlockHeight (t) <= 0)
  4566. continue;
  4567. const auto left = (float) headerIndent (song, t) + 10.0f; // indented under the track
  4568. for (int i = 0; i < (int) song.playlistTracks[(std::size_t) t].lanes.size(); ++i)
  4569. {
  4570. const auto row = laneRow (t, i);
  4571. if (row.getBottom() < headers.getY() || row.getY() > headers.getBottom())
  4572. continue;
  4573. const auto a = laneAutomation (t, i);
  4574. const auto plate = juce::Rectangle<float> (left, (float) row.getY() + 1.0f, (float) headerWidth - 2.0f - left, (float) row.getHeight() - 3.0f);
  4575. g.setColour (colour::bg2.interpolatedWith (colour::automation, 0.08f));
  4576. g.fillRoundedRectangle (plate, radius::sm);
  4577. g.setColour (colour::automation.withAlpha (song.isTrackMuted (t) ? 0.3f : 0.9f));
  4578. g.fillRoundedRectangle (plate.withWidth (3.0f).reduced (0.0f, 3.0f), 1.5f);
  4579. g.setColour (song.isTrackMuted (t) ? colour::textDisabled : colour::textSecondary);
  4580. g.setFont (font (type::caption));
  4581. textcache::drawFittedText (g, a >= 0 ? juce::String::fromUTF8 (song.automations[(std::size_t) a].name.c_str()) : juce::String(),
  4582. (int) plate.getX() + 7, row.getY(), (int) plate.getWidth() - 10, row.getHeight(), juce::Justification::centredLeft,
  4583. row.getHeight() >= 30 ? 2 : 1, 0.8f);
  4584. }
  4585. }
  4586. }
  4587. bool PlaylistComponent::dragOutToClipGrid (const juce::MouseEvent& e)
  4588. {
  4589. // only in the Clip-launch layout, with the mouse off the Playlist and over the clip grid beside it
  4590. if (layoutstyle::current() != layoutstyle::Style::clipLaunch || getLocalBounds().contains (e.getPosition()))
  4591. return false;
  4592. const auto& song = engine.getSong();
  4593. if (dragClip < 0 || dragClip >= (int) song.playlist.size() || dragIndices.size() != dragOriginals.size())
  4594. return false;
  4595. const auto kind = song.playlist[(std::size_t) dragClip].kind;
  4596. if (kind != ClipKind::pattern && kind != ClipKind::audio)
  4597. return false;
  4598. if (! isClipGrid (juce::Desktop::getInstance().findComponentAt (e.getScreenPosition())))
  4599. return false;
  4600. auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this);
  4601. if (container == nullptr || container->isDragAndDropActive())
  4602. return false;
  4603. engine.editSong ([this] (Song& s) {
  4604. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  4605. if (const auto i = dragIndices[j]; i >= 0 && i < (int) s.playlist.size())
  4606. s.playlist[(std::size_t) i] = dragOriginals[j];
  4607. });
  4608. juce::Image image (juce::Image::ARGB, 96, 22, true);
  4609. {
  4610. juce::Graphics g (image);
  4611. g.setColour (theme::colour::accent.withAlpha (0.85f));
  4612. g.fillRoundedRectangle (image.getBounds().toFloat().reduced (1.0f), 3.0f);
  4613. }
  4614. container->startDragging (playlistClipDragDescription (dragClip, dragClip >= 0 && dragClip < (int) engine.getSong().playlist.size()
  4615. ? engine.getSong().playlist[(std::size_t) dragClip].uid : 0),
  4616. this, juce::ScaledImage (image), false);
  4617. drag = Drag::none;
  4618. repaint();
  4619. return true;
  4620. }
  4621. bool PlaylistComponent::laneMouseDown (const juce::MouseEvent& e)
  4622. {
  4623. const auto hit = laneAt (e.getPosition());
  4624. if (hit.track < 0)
  4625. return false;
  4626. const auto a = laneAutomation (hit.track, hit.lane);
  4627. if (a < 0)
  4628. return true;
  4629. if (e.x < headerWidth) // the lane's header: its menu; a double click opens the point editor
  4630. {
  4631. if (flmods::popup (e.mods))
  4632. showLaneMenu (hit.track, hit.lane);
  4633. else if (e.getNumberOfClicks() >= 2)
  4634. openAutomationEditor (engine, a);
  4635. return true;
  4636. }
  4637. const auto& points = engine.getSong().automations[(std::size_t) a].points;
  4638. const auto point = lanePointAt (hit.track, hit.lane, e.getPosition());
  4639. const auto body = laneBody (hit.track, hit.lane);
  4640. // round 190ef, Draw Mode (the Clip-launch layout's B, core/DrawMode.h): a press draws the cell under the mouse at the
  4641. // grid width, a drag goes on drawing (freehand without a grid or with Alt, the Playlist's "no snap"); the right button
  4642. // keeps its point menu
  4643. if (drawmode::isOn() && ! flmods::popup (e.mods) && e.mods.isLeftButtonDown())
  4644. {
  4645. laneTrack = hit.track;
  4646. laneIndex = hit.lane;
  4647. setSelection ({});
  4648. drag = Drag::laneDraw;
  4649. drawFreehand = grid::resolve (snapBox).kind == grid::Kind::none || gridTicks() <= 1 || e.mods.isAltDown();
  4650. drawTick = juce::jmax<std::int64_t> (0, (std::int64_t) std::floor (xToTick (e.x)));
  4651. drawValue = laneValueOf (a, juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight())));
  4652. laneDrawTo (e);
  4653. return true;
  4654. }
  4655. if (flmods::popup (e.mods) || (e.mods.isAltDown() && point >= 0)) // on a point: delete it (FL's Alt+click too)
  4656. {
  4657. if (point >= 0 && points.size() > 1)
  4658. engine.editSong ([a, point] (Song& s) {
  4659. eraseAutomationPoint (s.automations[(std::size_t) a].points, point);
  4660. });
  4661. else if (point < 0)
  4662. showLaneMenu (hit.track, hit.lane);
  4663. return true;
  4664. }
  4665. if (! e.mods.isLeftButtonDown())
  4666. return true;
  4667. laneTrack = hit.track;
  4668. laneIndex = hit.lane;
  4669. setSelection ({});
  4670. if (point >= 0)
  4671. {
  4672. drag = Drag::lanePoint;
  4673. autoPoint = point;
  4674. return true;
  4675. }
  4676. const auto tick = (double) juce::jmax<std::int64_t> (0, (std::int64_t) xToTick (e.x));
  4677. if (e.mods.isAltDown()) // [Alt]+drag on the line bends the segment under the mouse
  4678. {
  4679. for (int i = 0; i + 1 < (int) points.size(); ++i)
  4680. if ((double) points[(std::size_t) i].tick <= tick && tick < (double) points[(std::size_t) i + 1].tick)
  4681. {
  4682. drag = Drag::laneTension;
  4683. autoPoint = i;
  4684. tensionStart = points[(std::size_t) i].tension;
  4685. tensionSign = points[(std::size_t) i + 1].value >= points[(std::size_t) i].value ? -1.0f : 1.0f;
  4686. return true;
  4687. }
  4688. return true;
  4689. }
  4690. // a new point here (snapped; [Shift]: on the line), then dragged
  4691. AutomationPoint p;
  4692. p.tick = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), true));
  4693. p.value = e.mods.isShiftDown() ? engine.getSong().automations[(std::size_t) a].valueAt ((double) p.tick)
  4694. : laneValueOf (a, juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight())));
  4695. int added = -1;
  4696. engine.editSong ([a, p, &added] (Song& s) { added = insertAutomationPoint (s.automations[(std::size_t) a].points, p); });
  4697. drag = Drag::lanePoint;
  4698. autoPoint = added;
  4699. return true;
  4700. }
  4701. // round 190ef: one move of a Draw Mode drag, from the last position to the mouse (one undo step per press: editSong
  4702. // joins the edits made while the button is held)
  4703. void PlaylistComponent::laneDrawTo (const juce::MouseEvent& e)
  4704. {
  4705. const auto a = laneAutomation (laneTrack, laneIndex);
  4706. if (a < 0)
  4707. return;
  4708. const auto body = laneBody (laneTrack, laneIndex);
  4709. const auto tick = juce::jmax<std::int64_t> (0, (std::int64_t) std::floor (xToTick (e.x)));
  4710. const auto value = laneValueOf (a, juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight())));
  4711. const auto from = drawTick;
  4712. const auto fromValue = drawValue;
  4713. if (drawFreehand)
  4714. engine.editSong ([a, from, fromValue, tick, value] (Song& s) {
  4715. drawmode::drawLine (s.automations[(std::size_t) a].points, from, fromValue, tick, value);
  4716. });
  4717. else
  4718. {
  4719. const auto steps = drawmode::stepsAlong (from, fromValue, tick, value, gridTicks());
  4720. engine.editSong ([a, steps] (Song& s) {
  4721. for (const auto& step : steps)
  4722. drawmode::drawStep (s.automations[(std::size_t) a].points, step.cell.from, step.cell.to, step.value);
  4723. });
  4724. }
  4725. drawTick = tick;
  4726. drawValue = value;
  4727. }
  4728. // round 190cg: a tempo lane shows the song's own range (Song::tempoViewLow / High, the reference's lowest / highest BPM
  4729. // of the tempo lane) when one is set; every other lane, and a tempo lane without a range, shows 0 … 1 as before
  4730. float PlaylistComponent::laneShown (int automation, float value) const
  4731. {
  4732. const auto& song = engine.getSong();
  4733. if (automation < 0 || automation >= (int) song.automations.size() || song.automations[(std::size_t) automation].target.kind != AutomationTargetKind::tempo
  4734. || ! (song.tempoViewHigh > song.tempoViewLow))
  4735. return value;
  4736. return (float) juce::jlimit (0.0, 1.0, (tempoFromValue (value) - song.tempoViewLow) / (song.tempoViewHigh - song.tempoViewLow));
  4737. }
  4738. float PlaylistComponent::laneValueOf (int automation, float shown) const
  4739. {
  4740. const auto& song = engine.getSong();
  4741. if (automation < 0 || automation >= (int) song.automations.size() || song.automations[(std::size_t) automation].target.kind != AutomationTargetKind::tempo
  4742. || ! (song.tempoViewHigh > song.tempoViewLow))
  4743. return shown;
  4744. return juce::jlimit (0.0f, 1.0f, valueFromTempo (song.tempoViewLow + (double) shown * (song.tempoViewHigh - song.tempoViewLow)));
  4745. }
  4746. void PlaylistComponent::showLaneMenu (int track, int lane)
  4747. {
  4748. const auto a = laneAutomation (track, lane);
  4749. if (a < 0)
  4750. return;
  4751. juce::PopupMenu menu;
  4752. menu.addSectionHeader (juce::String::fromUTF8 (engine.getSong().automations[(std::size_t) a].name.c_str()));
  4753. if (engine.getSong().automations[(std::size_t) a].target.kind == AutomationTargetKind::tempo)
  4754. {
  4755. // the lane's range [xml TempoAutomationViewBottom / Top: 60 / 200 in a new set of the reference]
  4756. juce::PopupMenu range;
  4757. const auto& song = engine.getSong();
  4758. const auto whole = ! (song.tempoViewHigh > song.tempoViewLow);
  4759. range.addItem (tr ("Whole range"), true, whole, [this] { engine.editSong ([] (Song& s) { s.tempoViewLow = s.tempoViewHigh = 0.0; }); });
  4760. for (const auto [low, high] : { std::pair { 60.0, 200.0 }, { 40.0, 120.0 }, { 80.0, 160.0 }, { 100.0, 200.0 }, { 20.0, 300.0 } })
  4761. range.addItem (juce::String ((int) low) + " - " + juce::String ((int) high) + " BPM", true,
  4762. ! whole && song.tempoViewLow == low && song.tempoViewHigh == high,
  4763. [this, low = low, high = high] { engine.editSong ([low, high] (Song& s) { s.tempoViewLow = low; s.tempoViewHigh = high; }); });
  4764. range.addItem (tr ("Set the range..."), [this] { askTempoRange(); });
  4765. menu.addSubMenu (tr ("Tempo range shown"), range);
  4766. }
  4767. menu.addItem (tr ("Edit points..."), [this, a] { openAutomationEditor (engine, a); });
  4768. menu.addItem (tr ("To automation clip"), [this, track, lane] {
  4769. engine.editSong ([track, lane] (Song& s) { autolanes::laneToClip (s, track, lane); });
  4770. });
  4771. // round 190qu (Discord 11-24, Live's arrangement automation with Bitwig's clip automation): the time selection's part
  4772. // of the lane as an automation clip under the track; the lane keeps its points (the clip wins where it plays)
  4773. {
  4774. const auto& song = engine.getSong();
  4775. const auto from = song.loopStart, to = song.loopEnd;
  4776. menu.addItem (tr ("Time selection to automation clip"), song.hasLoop(), false, [this, track, lane, from, to] {
  4777. int made = -1;
  4778. engine.editSong ([&made, track, lane, from, to] (Song& s) { made = laneview::laneRangeToClip (s, track, lane, from, to); });
  4779. if (made >= 0)
  4780. setSelection ({ made });
  4781. });
  4782. }
  4783. menu.addItem (tr ("Remove the lane"), [this, track, lane] {
  4784. engine.editSong ([track, lane] (Song& s) { autolanes::removeLane (s, track, lane); });
  4785. });
  4786. menu.addSeparator();
  4787. menu.addItem (tr ("Fold the lanes"), [this, track] { editTrack (track, [] (PlaylistTrack& t) { t.lanesFolded = true; }); });
  4788. menu.addItem (tr ("Hide all lanes"), [this] { toggleAutomationLanes(); });
  4789. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  4790. }
  4791. void PlaylistComponent::showAddLaneMenu (int track)
  4792. {
  4793. const auto& song = engine.getSong();
  4794. std::vector<AutomationTarget> targets;
  4795. juce::PopupMenu menu;
  4796. auto add = [&] (const AutomationTarget& target) {
  4797. if (target.kind == AutomationTargetKind::none || std::find (targets.begin(), targets.end(), target) != targets.end())
  4798. return;
  4799. targets.push_back (target);
  4800. menu.addItem (describeAutomationTarget (engine, target), [this, target, track] { createAutomationLane (engine, target, track); });
  4801. };
  4802. // the track's own channel and mixer track first
  4803. const auto* info = track >= 0 && track < (int) song.playlistTracks.size() ? &song.playlistTracks[(std::size_t) track] : nullptr;
  4804. if (info != nullptr && info->mode == PlaylistTrackMode::instrument && info->channel >= 0 && info->channel < (int) song.channels.size())
  4805. {
  4806. menu.addSectionHeader (tr ("This track"));
  4807. add ({ AutomationTargetKind::channelVolume, info->channel, 0, 0 });
  4808. add ({ AutomationTargetKind::channelPan, info->channel, 0, 0 });
  4809. }
  4810. if (info != nullptr && info->mode != PlaylistTrackMode::unassigned && info->mixerTrack > 0 && info->mixerTrack < (int) song.mixer.size())
  4811. {
  4812. if (targets.empty())
  4813. menu.addSectionHeader (tr ("This track"));
  4814. add ({ AutomationTargetKind::mixerVolume, info->mixerTrack, 0, 0 });
  4815. add ({ AutomationTargetKind::mixerPan, info->mixerTrack, 0, 0 });
  4816. }
  4817. const auto before = targets.size();
  4818. for (int which = 0; which < 2; ++which)
  4819. if (const auto last = engine.getLastTweaked (which); last.has_value() && std::find (targets.begin(), targets.end(), *last) == targets.end())
  4820. {
  4821. if (targets.size() == before)
  4822. menu.addSectionHeader (tr ("Last tweaked"));
  4823. add (*last);
  4824. }
  4825. menu.addSectionHeader (tr ("Song"));
  4826. add ({ AutomationTargetKind::tempo, 0, 0, 0 });
  4827. add ({ AutomationTargetKind::mixerVolume, 0, 0, 0 });
  4828. menu.addSeparator();
  4829. menu.addItem (tr ("Any control: right-click it > Automate in lane"), false, false, [] {});
  4830. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  4831. }
  4832. // --- round 190jr (BUILD-LIST 13): the Simple layout's region loop ----------------------------------------------------
  4833. bool PlaylistComponent::regionLoopContinues (int clip) const
  4834. {
  4835. const auto& song = engine.getSong();
  4836. if (clip < 0 || clip >= (int) song.playlist.size())
  4837. return false;
  4838. const auto& c = song.playlist[(std::size_t) clip];
  4839. for (const auto& o : song.playlist)
  4840. if (o.track == c.track && o.start == c.end() && o.kind == c.kind && o.pattern == c.pattern && o.channel == c.channel
  4841. && o.offset == c.offset && o.length <= c.length && o.gridSlot < 0 && o.gain == c.gain && o.pitch == c.pitch && o.muted == c.muted)
  4842. return true;
  4843. return false;
  4844. }
  4845. juce::Rectangle<float> PlaylistComponent::regionLoopHandle (int clip) const
  4846. {
  4847. if (! simpleHeaders || ! regionloop::loopable (engine.getSong(), clip) || noteedit::isFoldedAway (engine.getSong(), engine.getSong().playlist[(std::size_t) clip].track))
  4848. return {};
  4849. const auto r = clipBounds (clip).toFloat();
  4850. const auto title = clipHeaderHeight (r);
  4851. if (r.getWidth() < 34.0f || title < 9.0f || regionLoopContinues (clip))
  4852. return {};
  4853. // BandLab: a small circular arrow at the right end of the region's name strip
  4854. const auto size = juce::jmin (11.0f, title - 2.0f);
  4855. return { r.getRight() - size - 3.0f, r.getY() + (title - size) * 0.5f, size, size };
  4856. }
  4857. void PlaylistComponent::regionLoopDragTo (int x)
  4858. {
  4859. const auto& song = engine.getSong();
  4860. const auto region = regionloop::regionAt (song, loopTrack, loopStart, loopLike);
  4861. if (region < 0)
  4862. return;
  4863. const auto snapOn = ! juce::ModifierKeys::currentModifiers.isAltDown();
  4864. const auto run = regionloop::runOf (song, region);
  4865. const auto cap = regionloop::nextStart (song, run);
  4866. const auto first = song.playlist[(std::size_t) region].end();
  4867. const auto end = juce::jmax (first, juce::jmin (cap, snap (xToTick (x) + (snapOn ? gridTicks() / 2.0 : 0.0), snapOn)));
  4868. if (end == run.end)
  4869. return;
  4870. engine.editSong ([region, end] (Song& s) { regionloop::loopTo (s, region, end); });
  4871. postDragHint();
  4872. repaint();
  4873. }
  4874. // --- round 190jr (BUILD-LIST 13): the Simple layout's automation view (BandLab's automation switch) ---------------------
  4875. void PlaylistComponent::setSimpleAutomation (bool on)
  4876. {
  4877. if (on == simpleAutomation)
  4878. return;
  4879. simpleAutomation = on;
  4880. hover = {};
  4881. refreshTrackLayout(); // (the lanes under Simple tracks give way to the rows' own line)
  4882. updateScrollBars();
  4883. repaint();
  4884. if (onSimpleAutomationChanged)
  4885. onSimpleAutomationChanged (on);
  4886. }
  4887. bool PlaylistComponent::simpleAutoOn (int track) const
  4888. {
  4889. return simpleAutomation && simpleHeaders && track >= 0 && track < (int) engine.getSong().playlistTracks.size() && simpleInsert (track) > 0
  4890. && ! noteedit::isFoldedAway (engine.getSong(), track);
  4891. }
  4892. AutomationTarget PlaylistComponent::simpleAutoTarget (int track) const
  4893. {
  4894. const auto insert = simpleInsert (track);
  4895. if (const auto it = simpleAutoTargets.find (track); it != simpleAutoTargets.end() && it->second.index == insert)
  4896. {
  4897. const auto& t = it->second;
  4898. const auto& song = engine.getSong();
  4899. if (t.kind != AutomationTargetKind::effectParam
  4900. || (insert > 0 && insert < (int) song.mixer.size() && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) insert].effects.size()))
  4901. return t;
  4902. }
  4903. return { AutomationTargetKind::mixerVolume, insert, 0, 0 };
  4904. }
  4905. int PlaylistComponent::simpleAutoLane (int track) const
  4906. {
  4907. const auto& song = engine.getSong();
  4908. if (track < 0 || track >= (int) song.playlistTracks.size())
  4909. return -1;
  4910. const auto target = simpleAutoTarget (track);
  4911. const auto& lanes = song.playlistTracks[(std::size_t) track].lanes;
  4912. for (int i = 0; i < (int) lanes.size(); ++i)
  4913. if (const auto a = lanes[(std::size_t) i].automation; a >= 0 && a < (int) song.automations.size() && song.automations[(std::size_t) a].target == target)
  4914. return i;
  4915. return -1;
  4916. }
  4917. float PlaylistComponent::simpleAutoCurrent (const AutomationTarget& target) const
  4918. {
  4919. const auto& song = engine.getSong();
  4920. if (target.index <= 0 || target.index >= (int) song.mixer.size())
  4921. return 0.5f;
  4922. const auto& m = song.mixer[(std::size_t) target.index];
  4923. switch (target.kind)
  4924. {
  4925. case AutomationTargetKind::mixerVolume: return m.volume;
  4926. case AutomationTargetKind::mixerPan: return juce::jlimit (0.0f, 1.0f, (m.pan + 1.0f) * 0.5f);
  4927. case AutomationTargetKind::effectParam:
  4928. if (target.slot >= 0 && target.slot < (int) m.effects.size() && target.param >= 0 && target.param < maxEffectParams)
  4929. return m.effects[(std::size_t) target.slot].params[(std::size_t) target.param];
  4930. return 0.5f;
  4931. default: return 0.5f;
  4932. }
  4933. }
  4934. juce::Rectangle<int> PlaylistComponent::simpleAutoMenu (int track) const
  4935. {
  4936. if (! simpleAutoOn (track))
  4937. return {};
  4938. const auto v = trackVolume (track);
  4939. if (v.isEmpty())
  4940. return {};
  4941. const auto fx = trackFx (track);
  4942. const auto right = fx.isEmpty() ? v.getRight() : fx.getRight();
  4943. return { v.getX(), v.getCentreY() - 10, right - v.getX(), 20 };
  4944. }
  4945. void PlaylistComponent::showSimpleAutoMenu (int track)
  4946. {
  4947. auto menu = buildSimpleAutoMenu (track);
  4948. if (menu.getNumItems() > 0)
  4949. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withTargetScreenArea (localAreaToGlobal (simpleAutoMenu (track))));
  4950. }
  4951. juce::PopupMenu PlaylistComponent::buildSimpleAutoMenu (int track)
  4952. {
  4953. const auto& song = engine.getSong();
  4954. const auto insert = simpleInsert (track);
  4955. juce::PopupMenu menu;
  4956. if (insert <= 0 || insert >= (int) song.mixer.size())
  4957. return menu;
  4958. const auto current = simpleAutoTarget (track);
  4959. auto pick = [this, track] (AutomationTarget t) {
  4960. return [this, track, t] {
  4961. simpleAutoTargets[track] = t;
  4962. repaint();
  4963. };
  4964. };
  4965. // BandLab's order: Track (Pan, Volume), then each effect's parameters under the effect's name
  4966. menu.addSectionHeader (tr ("Track"));
  4967. for (const auto kind : { AutomationTargetKind::mixerPan, AutomationTargetKind::mixerVolume })
  4968. {
  4969. const AutomationTarget t { kind, insert, 0, 0 };
  4970. menu.addItem (kind == AutomationTargetKind::mixerPan ? tr ("Pan") : tr ("Volume"), true, current == t, pick (t));
  4971. }
  4972. const auto& effects = song.mixer[(std::size_t) insert].effects;
  4973. for (int slot = 0; slot < (int) effects.size(); ++slot)
  4974. {
  4975. const auto& fx = effects[(std::size_t) slot];
  4976. if (fx.kind == EffectKind::plugin || fx.kind == EffectKind::parallel || fx.kind == EffectKind::patcher)
  4977. continue; // (hosted plugins and containers: their parameters through "Automate in lane" on the control)
  4978. const auto& info = effectInfo (fx.kind);
  4979. if (info.params.empty())
  4980. continue;
  4981. menu.addSectionHeader (tr (info.name));
  4982. for (int p = 0; p < (int) info.params.size() && p < maxEffectParams; ++p)
  4983. {
  4984. const AutomationTarget t { AutomationTargetKind::effectParam, insert, slot, p };
  4985. menu.addItem (tr (info.params[(std::size_t) p].name), true, current == t, pick (t));
  4986. }
  4987. }
  4988. return menu;
  4989. }
  4990. bool PlaylistComponent::simpleAutoMouseDown (const juce::MouseEvent& e)
  4991. {
  4992. if (! simpleAutomation || e.y < tracksTop() || e.y >= gridArea().getBottom())
  4993. return false;
  4994. const auto track = yToTrack (e.y);
  4995. if (! simpleAutoOn (track))
  4996. return false;
  4997. if (e.x < headerWidth) // the header's parameter menu
  4998. {
  4999. if (simpleAutoMenu (track).contains (e.getPosition()) && ! flmods::popup (e.mods))
  5000. {
  5001. showSimpleAutoMenu (track);
  5002. return true;
  5003. }
  5004. return false; // (M, S, the name: as ever)
  5005. }
  5006. if (simpleAutoLane (track) >= 0 || flmods::popup (e.mods) || ! e.mods.isLeftButtonDown())
  5007. return false; // (the lane exists: laneMouseDown edits it; a right-click on a flat line does nothing)
  5008. // the first point on this row: the lane is made now, flat at the parameter's current value (one undo step with the
  5009. // point laneMouseDown adds next: editSong joins the edits made while the button is held)
  5010. const auto target = simpleAutoTarget (track);
  5011. const auto value = simpleAutoCurrent (target);
  5012. const auto name = describeAutomationTarget (engine, target).toStdString();
  5013. engine.editSong ([track, target, name, value] (Song& s) { autolanes::addLane (s, track, target, name, value); });
  5014. return false;
  5015. }
  5016. void PlaylistComponent::paintSimpleAutomation (juce::Graphics& g, juce::Rectangle<int> grid)
  5017. {
  5018. if (! simpleAutomation || ! simpleHeaders)
  5019. return;
  5020. using namespace theme;
  5021. const auto& song = engine.getSong();
  5022. const auto clipArea = g.getClipBounds();
  5023. const auto from = (float) juce::jmax (grid.getX(), clipArea.getX()), to = (float) juce::jmin (grid.getRight(), clipArea.getRight());
  5024. for (int t = 0; t < numTracks(); ++t)
  5025. {
  5026. if (! simpleAutoOn (t))
  5027. continue;
  5028. const auto row = juce::Rectangle<int> (grid.getX(), trackToY (t), grid.getWidth(), heightOf (t));
  5029. if (! row.intersects (clipArea))
  5030. continue;
  5031. // BandLab: the regions dim under the line
  5032. g.setColour (colour::bg0.withAlpha (0.45f));
  5033. g.fillRect (row.withTrimmedBottom (1));
  5034. const auto body = row.toFloat().reduced (0.0f, 4.0f); // (laneBody's rule for the row)
  5035. const auto lane = simpleAutoLane (t);
  5036. const auto a = lane >= 0 ? laneAutomation (t, lane) : -1;
  5037. const auto line = song.isTrackMuted (t) ? colour::textDisabled : colour::textPrimary;
  5038. if (a < 0)
  5039. {
  5040. // no automation yet: a dashed line at the parameter's current value (a click on it adds the first point)
  5041. const auto y = body.getBottom() - simpleAutoCurrent (simpleAutoTarget (t)) * body.getHeight();
  5042. juce::Path flat, dashed;
  5043. flat.startNewSubPath (from, y);
  5044. flat.lineTo (to, y);
  5045. const float dash[] = { 2.0f, 3.0f };
  5046. juce::PathStrokeType (1.0f).createDashedStroke (dashed, flat, dash, 2);
  5047. g.setColour (line.withAlpha (0.6f));
  5048. g.fillPath (dashed);
  5049. continue;
  5050. }
  5051. const auto& automation = song.automations[(std::size_t) a];
  5052. juce::Path curve;
  5053. auto lastY = 0.0f;
  5054. for (auto x = from; x <= to; x += 2.0f)
  5055. {
  5056. const auto yAt = [&] (int sx) { return body.getBottom() - laneShown (a, automation.valueAt (xToTick (sx))) * body.getHeight(); };
  5057. const auto y = yAt ((int) x);
  5058. if (x == from)
  5059. curve.startNewSubPath (x, y);
  5060. else
  5061. automationLineTo (curve, x - 2.0f, lastY, x, y, [&] { return yAt ((int) x - 1); });
  5062. lastY = y;
  5063. }
  5064. g.setColour (line);
  5065. g.strokePath (curve, juce::PathStrokeType (1.2f));
  5066. for (const auto& p : automation.points) // the points: small rings (BandLab)
  5067. {
  5068. const auto x = (float) tickToX ((double) p.tick);
  5069. if (x < from - 4.0f || x > to + 4.0f)
  5070. continue;
  5071. const auto y = body.getBottom() - laneShown (a, p.value) * body.getHeight();
  5072. g.setColour (colour::bg0);
  5073. g.fillEllipse (x - 3.0f, y - 3.0f, 6.0f, 6.0f);
  5074. g.setColour (line);
  5075. g.drawEllipse (x - 3.0f, y - 3.0f, 6.0f, 6.0f, 1.2f);
  5076. }
  5077. }
  5078. }
  5079. void PlaylistComponent::toggleAutomationLanes()
  5080. {
  5081. autolanes::setShown (! autolanes::shown());
  5082. refreshTrackLayout();
  5083. updateScrollBars();
  5084. repaint();
  5085. if (onViewOptionChanged)
  5086. onViewOptionChanged();
  5087. }
  5088. juce::Rectangle<float> PlaylistComponent::curveBodyForSnapshot (int clip) const
  5089. {
  5090. const auto& song = engine.getSong();
  5091. return clip >= 0 && clip < (int) song.playlist.size() ? automationBody (song.playlist[(std::size_t) clip]) : juce::Rectangle<float>();
  5092. }
  5093. PlaylistComponent::CurveRef PlaylistComponent::curveOf (int clip) const
  5094. {
  5095. const auto& song = engine.getSong();
  5096. if (clip < 0 || clip >= (int) song.playlist.size())
  5097. return {};
  5098. const auto& c = song.playlist[(std::size_t) clip];
  5099. if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size())
  5100. return { &song.automations[(std::size_t) c.automation].points, c.automation, 0 };
  5101. if (const auto* e = clipenv::of (song, c); e != nullptr && e->shown != 0)
  5102. return { &clipenv::laneOf (*e, e->shown), -1, e->shown };
  5103. return {};
  5104. }
  5105. void PlaylistComponent::editCurve (int clip, const std::function<void (std::vector<AutomationPoint>&)>& fn)
  5106. {
  5107. engine.editSong ([clip, &fn] (Song& s) {
  5108. if (clip < 0 || clip >= (int) s.playlist.size())
  5109. return;
  5110. auto& c = s.playlist[(std::size_t) clip];
  5111. if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) s.automations.size())
  5112. fn (s.automations[(std::size_t) c.automation].points);
  5113. else if (const auto* e = clipenv::of (s, c); e != nullptr && e->shown != 0)
  5114. {
  5115. auto& own = clipenv::own (s, c);
  5116. fn (clipenv::laneOf (own, own.shown));
  5117. }
  5118. });
  5119. }
  5120. float PlaylistComponent::curveValueAt (int clip, double clipTick) const
  5121. {
  5122. const auto curve = curveOf (clip);
  5123. if (curve.automation >= 0)
  5124. return engine.getSong().automations[(std::size_t) curve.automation].valueAt (clipTick);
  5125. return curve.points != nullptr && ! curve.points->empty() ? automationCurveAt (*curve.points, clipTick) : clipenv::neutralOf (curve.lane);
  5126. }
  5127. // a point's value as the hint shows it: the automation target's, or the envelope's dB / pan
  5128. juce::String PlaylistComponent::curveValueText (int clip, float value) const
  5129. {
  5130. const auto curve = curveOf (clip);
  5131. if (curve.automation >= 0)
  5132. return automationPointValueText (engine.getSong().automations[(std::size_t) curve.automation].target, value);
  5133. if (curve.lane == clipenv::panLane)
  5134. {
  5135. const auto pan = juce::roundToInt (clipenv::panOf (value) * 100.0f);
  5136. return pan == 0 ? tr ("Centered") : juce::String (std::abs (pan)) + (pan < 0 ? "% L" : "% R");
  5137. }
  5138. const auto gain = clipenv::gainOf (value);
  5139. return gain <= 0.0f ? juce::String ("-inf dB") : juce::String (juce::Decibels::gainToDecibels (gain), 1) + " dB";
  5140. }
  5141. // round 190im (DE-118): a segment's tension as the hint shows it, in FL's sign (LYNX keeps the opposite one, core/Song.h)
  5142. juce::String PlaylistComponent::tensionText (float tension)
  5143. {
  5144. const auto percent = juce::roundToInt (-tension * 100.0f);
  5145. return tr ("Tension: {0}", { juce::String (percent) + "%" });
  5146. }
  5147. int PlaylistComponent::automationPointAt (int clip, juce::Point<int> pos) const
  5148. {
  5149. const auto& song = engine.getSong();
  5150. const auto curve = curveOf (clip);
  5151. if (curve.points == nullptr)
  5152. return -1;
  5153. const auto& c = song.playlist[(std::size_t) clip];
  5154. const auto body = automationBody (c);
  5155. const auto& points = *curve.points;
  5156. for (int i = (int) points.size() - 1; i >= 0; --i)
  5157. {
  5158. const auto songTick = (double) (c.start + points[(std::size_t) i].tick - c.offset);
  5159. if (songTick < (double) c.start || songTick > (double) c.end())
  5160. continue;
  5161. const juce::Point<float> at ((float) tickToX (songTick), body.getBottom() - points[(std::size_t) i].value * body.getHeight());
  5162. if (at.getDistanceFrom (pos.toFloat()) <= 6.0f)
  5163. return i;
  5164. }
  5165. return -1;
  5166. }
  5167. bool PlaylistComponent::isOnAutomationCurve (int clip, juce::Point<int> pos) const
  5168. {
  5169. const auto& song = engine.getSong();
  5170. if (curveOf (clip).points == nullptr)
  5171. return false;
  5172. const auto& c = song.playlist[(std::size_t) clip];
  5173. const auto body = automationBody (c);
  5174. if (! body.expanded (0.0f, 4.0f).contains (pos.toFloat()))
  5175. return false;
  5176. const auto value = curveValueAt (clip, (double) c.offset + xToTick (pos.x) - (double) c.start);
  5177. return std::abs (body.getBottom() - value * body.getHeight() - (float) pos.y) <= 5.0f;
  5178. }
  5179. bool PlaylistComponent::automationEditable (int clip) const
  5180. {
  5181. const auto& song = engine.getSong();
  5182. if (clip < 0 || clip >= (int) song.playlist.size())
  5183. return false;
  5184. if (curveOf (clip).points == nullptr)
  5185. return false;
  5186. const auto body = automationBody (song.playlist[(std::size_t) clip]);
  5187. return body.getWidth() > 24.0f && body.getHeight() >= 10.0f;
  5188. }
  5189. juce::Point<float> PlaylistComponent::automationHandlePos (int clip, int point) const
  5190. {
  5191. if (! automationEditable (clip))
  5192. return { -1.0f, -1.0f };
  5193. const auto& song = engine.getSong();
  5194. const auto& c = song.playlist[(std::size_t) clip];
  5195. const auto& points = *curveOf (clip).points;
  5196. if (point < 0 || point + 1 >= (int) points.size())
  5197. return { -1.0f, -1.0f };
  5198. const auto& a = points[(std::size_t) point];
  5199. const auto& b = points[(std::size_t) point + 1];
  5200. const auto x0 = tickToX ((double) (c.start + a.tick - c.offset)), x1 = tickToX ((double) (c.start + b.tick - c.offset));
  5201. const auto body = automationBody (c);
  5202. const auto midX = (float) (0.5 * (x0 + x1));
  5203. if (x1 - x0 < 16.0 || midX < body.getX() || midX > body.getRight())
  5204. return { -1.0f, -1.0f };
  5205. return { midX, body.getBottom() - curveValueAt (clip, 0.5 * (double) (a.tick + b.tick)) * body.getHeight() };
  5206. }
  5207. int PlaylistComponent::automationHandleAt (int clip, juce::Point<int> p) const
  5208. {
  5209. if (! automationEditable (clip))
  5210. return -1;
  5211. const auto n = (int) curveOf (clip).points->size();
  5212. for (int i = 0; i + 1 < n; ++i)
  5213. if (const auto h = automationHandlePos (clip, i); h.x >= 0.0f && h.getDistanceFrom (p.toFloat()) <= 5.0f)
  5214. return i;
  5215. return -1;
  5216. }
  5217. void PlaylistComponent::showAutomationPointMenu (int clip, int point)
  5218. {
  5219. auto menu = getAutomationPointMenuForSnapshot (clip, point);
  5220. if (menu.getNumItems() > 0)
  5221. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  5222. }
  5223. juce::PopupMenu PlaylistComponent::getAutomationPointMenuForSnapshot (int clip, int point)
  5224. {
  5225. // FL's point menu [RES FLEngine TFruityLoopsMainForm.EEACPointMenu]: Delete, the Mode block (13 curve modes, round
  5226. // 190bw), then Copy value / Paste value / Type in value...; LYNX's own commands follow
  5227. const auto& song = engine.getSong();
  5228. if (clip < 0 || clip >= (int) song.playlist.size())
  5229. return {};
  5230. // an audio clip's envelope (round 190gi): the same point menu without the value clipboard and the automation editor
  5231. if (const auto curve = curveOf (clip); curve.lane != 0)
  5232. {
  5233. const auto& points = *curve.points;
  5234. if (point < 0 || point >= (int) points.size())
  5235. return {};
  5236. juce::PopupMenu menu;
  5237. menu.addSectionHeader (automationPointMenuHeader (point, (int) points.size()));
  5238. menu.addItem (tr ("Delete"), points.size() > 1, false, [this, clip, point] {
  5239. editCurve (clip, [point] (std::vector<AutomationPoint>& list) {
  5240. if (list.size() > 1)
  5241. eraseAutomationPoint (list, point);
  5242. });
  5243. });
  5244. addAutomationModeItems (menu, automationPointMode (points, point), point > 0, [this, clip, point] (int mode) {
  5245. editCurve (clip, [point, mode] (std::vector<AutomationPoint>& list) { setAutomationPointMode (list, point, mode); });
  5246. });
  5247. menu.addSeparator();
  5248. menu.addItem (tr ("Straight segment (reset the curve)"), point + 1 < (int) points.size(), false, [this, clip, point] {
  5249. editCurve (clip, [point] (std::vector<AutomationPoint>& list) { setAutomationSegmentTension (list, point, 0.0f); });
  5250. });
  5251. return menu;
  5252. }
  5253. const auto a = song.playlist[(std::size_t) clip].automation;
  5254. if (a < 0 || a >= (int) song.automations.size() || point < 0 || point >= (int) song.automations[(std::size_t) a].points.size())
  5255. return {};
  5256. const auto& automation = song.automations[(std::size_t) a];
  5257. const auto value = automation.points[(std::size_t) point].value;
  5258. juce::PopupMenu menu;
  5259. menu.addSectionHeader (automationPointMenuHeader (point, (int) automation.points.size())); // FL: "Point 2/14"
  5260. menu.addItem (tr ("Delete"), automation.points.size() > 1, false, [this, a, point] {
  5261. engine.editSong ([a, point] (Song& s) {
  5262. auto& points = s.automations[(std::size_t) a].points;
  5263. if (points.size() > 1)
  5264. eraseAutomationPoint (points, point);
  5265. });
  5266. });
  5267. addAutomationModeItems (menu, automationPointMode (automation.points, point), point > 0, [this, a, point] (int mode) {
  5268. engine.editSong ([a, point, mode] (Song& s) { setAutomationPointMode (s.automations[(std::size_t) a].points, point, mode); });
  5269. });
  5270. menu.addSeparator();
  5271. menu.addItem (tr ("Copy value"), [value] { copiedAutomationValue() = value; });
  5272. menu.addItem (tr ("Paste value"), copiedAutomationValue() >= 0.0f, false, [this, a, point] {
  5273. engine.editSong ([a, point, v = copiedAutomationValue()] (Song& s) {
  5274. auto& points = s.automations[(std::size_t) a].points;
  5275. if (point < (int) points.size())
  5276. points[(std::size_t) point].value = v;
  5277. });
  5278. });
  5279. menu.addItem (tr ("Type in value..."), [this, a, point] { typeAutomationPointValue (engine, a, point); });
  5280. menu.addSeparator();
  5281. menu.addItem (tr ("Straight segment (reset the curve)"), point + 1 < (int) automation.points.size(), false, [this, a, point] {
  5282. engine.editSong ([a, point] (Song& s) { setAutomationSegmentTension (s.automations[(std::size_t) a].points, point, 0.0f); });
  5283. });
  5284. menu.addItem (tr ("Edit points..."), [this, a] { openAutomationEditor (engine, a); });
  5285. return menu;
  5286. }
  5287. double PlaylistComponent::clipFileSeconds (int index) const
  5288. {
  5289. const auto& song = engine.getSong();
  5290. if (index < 0 || index >= (int) song.playlist.size() || song.playlist[(std::size_t) index].kind != ClipKind::audio)
  5291. return 0.0;
  5292. const auto channel = song.playlist[(std::size_t) index].channel;
  5293. if (channel < 0 || channel >= (int) song.channels.size())
  5294. return 0.0;
  5295. const auto path = juce::String::fromUTF8 (song.channels[(std::size_t) channel].samplePath.c_str());
  5296. if (const auto data = engine.getSampleLibrary().findLoaded (path); data != nullptr && data->sampleRate > 0.0)
  5297. return (double) data->frames() / data->sampleRate;
  5298. // (not held by the engine: the waveform's own summary, as the clip is painted from it)
  5299. if (const auto summary = ui::WaveformCache::getInstance()->find (path); summary != nullptr && summary->sampleRate > 0.0)
  5300. return (double) summary->frames / summary->sampleRate;
  5301. return 0.0;
  5302. }
  5303. std::vector<WarpPoint> PlaylistComponent::clipWarpMarkers (int index) const
  5304. {
  5305. const auto& song = engine.getSong();
  5306. if (index < 0 || index >= (int) song.playlist.size())
  5307. return {};
  5308. const auto& c = song.playlist[(std::size_t) index];
  5309. if (c.kind != ClipKind::audio || c.channel < 0 || c.channel >= (int) song.channels.size()
  5310. || clipops::playsBackwards (song.channels[(std::size_t) c.channel], c))
  5311. return {};
  5312. return warpedit::editableMarkers (song.channels[(std::size_t) c.channel].sampler, clipFileSeconds (index)); // (190gi: one-tempo markers too)
  5313. }
  5314. // round 190gi: Alt + drag — the marker whose line is within 5 px of `p`, anywhere on the clip's body (the start one never moves)
  5315. int PlaylistComponent::warpMarkerNear (int index, juce::Point<int> p) const
  5316. {
  5317. const auto markers = clipWarpMarkers (index);
  5318. if (markers.size() < 2)
  5319. return -1;
  5320. const auto& c = engine.getSong().playlist[(std::size_t) index];
  5321. const auto bounds = clipBounds (index);
  5322. if (p.y < bounds.getY() + (int) clipTitleHeight || p.y > bounds.getBottom())
  5323. return -1;
  5324. int best = -1;
  5325. double bestDx = 5.0;
  5326. for (std::size_t k = 1; k < markers.size(); ++k)
  5327. if (const auto dx = std::abs (tickToX (warpedit::clipTickOfBeat (c, markers[k].beats)) - p.x); dx <= bestDx)
  5328. {
  5329. bestDx = dx;
  5330. best = (int) k;
  5331. }
  5332. return best;
  5333. }
  5334. // round 190gi: a double-click on the flag strip of a clip that has warp markers adds one there (file seconds; −1 = none)
  5335. double PlaylistComponent::warpStripSeconds (int index, juce::Point<int> p) const
  5336. {
  5337. const auto markers = clipWarpMarkers (index);
  5338. const auto& song = engine.getSong();
  5339. if (markers.size() < 2 || index < 0 || index >= (int) song.playlist.size())
  5340. return -1.0;
  5341. const auto& c = song.playlist[(std::size_t) index];
  5342. if (c.channel < 0 || c.channel >= (int) song.channels.size() || song.channels[(std::size_t) c.channel].sampler.warp.size() < 2)
  5343. return -1.0;
  5344. const auto top = (float) clipBounds (index).getY() + (float) clipTitleHeight;
  5345. if (p.y < top - 1.0f || p.y > top + 8.0f)
  5346. return -1.0;
  5347. const auto beats = (xToTick (p.x) - warpedit::clipTickOfBeat (c, 0.0)) / (ppq * std::clamp (c.stretch, 0.01, 100.0));
  5348. const auto seconds = warpedit::secondsAt (markers, beats);
  5349. return seconds > 0.0 && seconds < clipFileSeconds (index) ? seconds : -1.0;
  5350. }
  5351. int PlaylistComponent::warpMarkerAt (int index, juce::Point<int> p) const
  5352. {
  5353. const auto markers = clipWarpMarkers (index);
  5354. if (markers.size() < 3)
  5355. return -1;
  5356. const auto& c = engine.getSong().playlist[(std::size_t) index];
  5357. const auto top = (float) clipBounds (index).getY() + (float) clipTitleHeight;
  5358. if (p.y < top - 1.0f || p.y > top + 8.0f)
  5359. return -1;
  5360. int best = -1;
  5361. double bestDx = 5.0;
  5362. for (std::size_t k = 1; k < markers.size(); ++k)
  5363. if (const auto dx = std::abs (tickToX (warpedit::clipTickOfBeat (c, markers[k].beats)) - p.x); dx <= bestDx)
  5364. {
  5365. bestDx = dx;
  5366. best = (int) k;
  5367. }
  5368. return best;
  5369. }
  5370. int PlaylistComponent::fadeHandleAt (int index, juce::Point<int> p) const
  5371. {
  5372. const auto& song = engine.getSong();
  5373. if (index < 0 || index >= (int) song.playlist.size() || song.playlist[(std::size_t) index].kind != ClipKind::audio)
  5374. return 0;
  5375. // round 190jz (issue #194, FL 2026): the handles sit in the top corners of the clip's body, under its header, at the
  5376. // ends of the fades (FL's triangles, 7 px when hovered); the nearer one wins on a narrow clip
  5377. const auto in = fadeHandlePoint (index, 0), out = fadeHandlePoint (index, 1);
  5378. const auto q = p.toFloat();
  5379. if (q.y < in.y - 3.0f || q.y > in.y + 9.0f)
  5380. return 0;
  5381. const auto dIn = std::abs (q.x - (in.x + 3.0f)), dOut = std::abs (q.x - (out.x - 3.0f));
  5382. if (dIn <= 6.0f && (dIn <= dOut || dOut > 6.0f))
  5383. return 1;
  5384. if (dOut <= 6.0f)
  5385. return 2;
  5386. return 0;
  5387. }
  5388. juce::Rectangle<float> PlaylistComponent::audioClipBody (int index) const
  5389. {
  5390. // (as paintAudioClip: FL's header band on a tall track, the whole band on a short one; LYNX's header elsewhere)
  5391. const auto r = clipBounds (index).toFloat();
  5392. if (flClipLook())
  5393. return r.getHeight() + 1.0f < (float) flBandBelow ? r.reduced (0.0f, 1.0f) : r.withTrimmedTop (flHeaderHeight (r));
  5394. return r.withTrimmedTop (clipHeaderHeight (r));
  5395. }
  5396. juce::Point<float> PlaylistComponent::fadeHandlePoint (int index, int side) const
  5397. {
  5398. const auto& c = engine.getSong().playlist[(std::size_t) index];
  5399. const auto body = audioClipBody (index);
  5400. const auto r = clipBounds (index).toFloat();
  5401. return side == 0 ? juce::Point<float> { r.getX() + (float) ((double) c.effectiveFadeIn() * pixelsPerTick), body.getY() }
  5402. : juce::Point<float> { r.getRight() - (float) ((double) c.effectiveFadeOut() * pixelsPerTick), body.getY() };
  5403. }
  5404. std::optional<juce::Point<float>> PlaylistComponent::fadeTensionPoint (int index, int side) const
  5405. {
  5406. // FL 2026: the circle in the middle of the fade, on its curve (none on a crossfade: LYNX's automatic and comp crossfades
  5407. // have no tension of their own, core Scheduler)
  5408. const auto& song = engine.getSong();
  5409. if (index < 0 || index >= (int) song.playlist.size())
  5410. return std::nullopt;
  5411. const auto& c = song.playlist[(std::size_t) index];
  5412. const auto length = side == 0 ? c.fadeIn : c.fadeOut;
  5413. const auto bit = side == 0 ? 1 : 2;
  5414. if (c.kind != ClipKind::audio || length <= 0 || (side == 0 ? c.crossfadeIn : c.crossfadeOut) > 0 || (c.fadeCurve & bit) != 0)
  5415. return std::nullopt;
  5416. const auto body = audioClipBody (index);
  5417. const auto r = clipBounds (index).toFloat();
  5418. const auto width = (float) ((double) length * pixelsPerTick);
  5419. if (width < 8.0f || body.getHeight() < 10.0f)
  5420. return std::nullopt;
  5421. const auto x = side == 0 ? r.getX() + width * 0.5f : r.getRight() - width * 0.5f;
  5422. const auto level = clipops::fadeLevel (0.5f, side == 0, (c.linearFades & bit) != 0, side == 0 ? c.fadeInTension : c.fadeOutTension);
  5423. return juce::Point<float> { x, body.getBottom() - level * body.getHeight() };
  5424. }
  5425. int PlaylistComponent::fadeTensionAt (int index, juce::Point<int> p) const
  5426. {
  5427. for (int side = 0; side < 2; ++side)
  5428. if (const auto at = fadeTensionPoint (index, side); at && at->getDistanceFrom (p.toFloat()) <= 6.0f)
  5429. return side + 1;
  5430. return 0;
  5431. }
  5432. juce::Colour PlaylistComponent::fadeInk (int index) const
  5433. {
  5434. // the waveform's colour, as paintAudioClip picks it
  5435. const auto& song = engine.getSong();
  5436. const auto& c = song.playlist[(std::size_t) index];
  5437. if (c.channel < 0 || c.channel >= (int) song.channels.size())
  5438. return theme::colour::textPrimary;
  5439. const auto& channel = song.channels[(std::size_t) c.channel];
  5440. const auto colour = audioClipColour (channel);
  5441. if (flClipLook())
  5442. {
  5443. const auto r = clipBounds (index).toFloat();
  5444. const auto look = theme::clipBody (juce::Colour (channel.colour), trackColourIn (song, c.track), ClipKind::audio, theme::ClipStyle::flTint);
  5445. return r.getHeight() + 1.0f < (float) flBandBelow ? look.compactContent : look.content;
  5446. }
  5447. if (const auto simpleLook = simpleClipLook (c))
  5448. return simpleLook->content;
  5449. return clipContentColour (colour);
  5450. }
  5451. juce::String PlaylistComponent::fadeLengthText (std::int64_t ticks) const
  5452. {
  5453. // FL 2026's hint: minutes'seconds.milliseconds'' ("Fade in: 0'15.750''")
  5454. const auto ms = juce::roundToInt ((double) juce::jmax<std::int64_t> (0, ticks) * 60000.0 / (juce::jmax (1.0, engine.getSong().bpm) * ppq));
  5455. return juce::String (ms / 60000) + "'" + juce::String ((ms / 1000) % 60).paddedLeft ('0', 2) + "." + juce::String (ms % 1000).paddedLeft ('0', 3) + "''";
  5456. }
  5457. // Round 190jz (issue #194): FL 2026's fade handles over the hovered audio clip (FL shots fl-194-*): small triangles in the
  5458. // waveform's colour at the body's top corners where the fades end (4 px), the hovered or dragged one white (7 px) with a
  5459. // faint line down the clip, and on each fade the tension circle (a 7 px ring on the curve; hovered or dragged, a 12 px
  5460. // disc). Drawn over the cached clips, for one clip only: nothing while nothing is hovered.
  5461. void PlaylistComponent::paintFadeHandles (juce::Graphics& g, int index)
  5462. {
  5463. const auto& song = engine.getSong();
  5464. if (index < 0 || index >= (int) song.playlist.size() || song.playlist[(std::size_t) index].kind != ClipKind::audio)
  5465. return;
  5466. const auto body = audioClipBody (index);
  5467. const auto r = clipBounds (index).toFloat();
  5468. if (r.getWidth() < 6.0f || body.getHeight() < 6.0f)
  5469. return;
  5470. const auto ink = fadeInk (index);
  5471. const juce::Graphics::ScopedSaveState keep (g);
  5472. g.reduceClipRegion (r.toNearestIntEdges());
  5473. const auto active = [&] (int target) {
  5474. if (dragClip == index && drag == Drag::fadeIn)
  5475. return target == 1;
  5476. if (dragClip == index && drag == Drag::fadeOut)
  5477. return target == 2;
  5478. if (dragClip == index && drag == Drag::fadeTension)
  5479. return target == 3 + fadeSide;
  5480. return drag == Drag::none && hover.clip == index && hover.fade == target;
  5481. };
  5482. for (int side = 0; side < 2; ++side)
  5483. {
  5484. const auto at = fadeHandlePoint (index, side);
  5485. const auto on = active (side + 1);
  5486. const auto size = on ? 7.0f : 4.0f;
  5487. const auto dir = side == 0 ? 1.0f : -1.0f;
  5488. if (on) // FL: a faint line down the clip under the handle
  5489. {
  5490. g.setColour (juce::Colours::white.withAlpha (0.12f));
  5491. g.fillRect (juce::Rectangle<float> (std::round (at.x) - (side == 0 ? 0.0f : 1.0f), body.getY(), 1.0f, body.getHeight()));
  5492. }
  5493. juce::Path corner;
  5494. corner.addTriangle (at.x, at.y, at.x + dir * size, at.y, at.x, at.y + size);
  5495. g.setColour (on ? juce::Colour (0xfff3ffff) : ink);
  5496. g.fillPath (corner);
  5497. }
  5498. for (int side = 0; side < 2; ++side)
  5499. if (const auto at = fadeTensionPoint (index, side))
  5500. {
  5501. if (active (3 + side))
  5502. {
  5503. const auto disc = juce::Rectangle<float> (12.0f, 12.0f).withCentre (*at);
  5504. g.setColour (ink.brighter (0.45f));
  5505. g.fillEllipse (disc);
  5506. g.setColour (juce::Colour (0xffe2eeef));
  5507. g.drawEllipse (disc.reduced (0.5f), 1.0f);
  5508. }
  5509. else
  5510. {
  5511. const auto ring = juce::Rectangle<float> (7.0f, 7.0f).withCentre (*at);
  5512. g.setColour (theme::colour::bg0.withAlpha (0.55f));
  5513. g.fillEllipse (ring);
  5514. g.setColour (ink);
  5515. g.drawEllipse (ring, 1.2f);
  5516. }
  5517. }
  5518. }
  5519. juce::Rectangle<float> PlaylistComponent::gainHandle (int index) const
  5520. {
  5521. const auto& song = engine.getSong();
  5522. if (index < 0 || index >= (int) song.playlist.size() || song.playlist[(std::size_t) index].kind != ClipKind::audio)
  5523. return {};
  5524. const auto r = clipBounds (index).toFloat();
  5525. if (r.getWidth() < 30.0f || r.getHeight() - clipTitleHeight < 16.0f)
  5526. return {};
  5527. // FL 2026: a semicircle sitting on the clip's bottom edge, in the middle
  5528. constexpr float radius = 5.0f;
  5529. auto centreX = r.getCentreX();
  5530. // issue #274 (round 190qr, the LYNX extra "The clip gain handle stays in view", off by default): when the clip's middle
  5531. // is scrolled out of view, the handle sits in the middle of the part that shows, so it can always be reached
  5532. if (const auto grid = gridArea().toFloat(); cliphandle::gainFollowsView() && (centreX < grid.getX() || centreX > grid.getRight()))
  5533. {
  5534. const auto shown = r.getHorizontalRange().getIntersectionWith (grid.getHorizontalRange());
  5535. if (shown.getLength() < 30.0f)
  5536. return {};
  5537. centreX = shown.getStart() + shown.getLength() * 0.5f;
  5538. }
  5539. return { centreX - radius, r.getBottom() - radius - 1.0f, radius * 2.0f, radius + 1.0f };
  5540. }
  5541. void PlaylistComponent::showGainMenu (int index)
  5542. {
  5543. if (index < 0 || index >= (int) engine.getSong().playlist.size())
  5544. return;
  5545. gainMenu (index).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  5546. }
  5547. juce::PopupMenu PlaylistComponent::gainMenu (int index)
  5548. {
  5549. const auto& song = engine.getSong();
  5550. juce::PopupMenu menu;
  5551. if (index < 0 || index >= (int) song.playlist.size())
  5552. return menu;
  5553. std::vector<int> targets;
  5554. for (auto i : isSelected (index) ? selection : std::vector<int> { index })
  5555. if (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio)
  5556. targets.push_back (i);
  5557. const auto db = clipops::clipGainToDb (song.playlist[(std::size_t) index].gain);
  5558. auto setDb = [this, targets] (double value) {
  5559. const auto g = clipops::clipGainFromDb (value);
  5560. engine.editSong ([targets, g] (Song& s) {
  5561. for (auto i : targets)
  5562. if (i < (int) s.playlist.size())
  5563. s.playlist[(std::size_t) i].gain = g;
  5564. });
  5565. };
  5566. // FL 2026's gain handle menu [SHOT round 166e]
  5567. menu.addSectionHeader (tr ("Gain: {0}", { gainText (song.playlist[(std::size_t) index].gain) }));
  5568. menu.addItem (tr ("Reset gain"), [setDb] { setDb (0.0); });
  5569. // FL's popup (FUN_00cfcdf0, handle kind 5): with two or more clips selected and the clicked one among them, Normalize
  5570. // reads "Normalize selection individually" and "Normalize selection as a group" appears (round 189n)
  5571. const auto many = selection.size() >= 2 && isSelected (index);
  5572. menu.addItem (many ? tr ("Normalize selection individually") : tr ("Normalize"), [this, targets] { normalizeClips (targets, false); });
  5573. if (many)
  5574. menu.addItem (tr ("Normalize selection as a group"), [this] { normalizeClips (selection, true); });
  5575. menu.addSeparator();
  5576. menu.addItem (tr ("Copy value"), [db] { copiedGainDb = db; hasCopiedGain = true; });
  5577. menu.addItem (tr ("Paste value"), hasCopiedGain, false, [setDb] { setDb (copiedGainDb); });
  5578. menu.addItem (tr ("Type in value..."), [db, setDb] {
  5579. auto* window = new juce::AlertWindow (tr ("Clip gain"), tr ("Decibels ({0} to {1})", { juce::String (clipops::clipGainMinDb, 1), "+" + juce::String (clipops::clipGainMaxDb, 0) }),
  5580. juce::MessageBoxIconType::NoIcon);
  5581. window->addTextEditor ("value", juce::String (db, 2));
  5582. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5583. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5584. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, setDb] (int result) {
  5585. if (result != 1)
  5586. return;
  5587. const auto typed = window->getTextEditorContents ("value").trim();
  5588. setDb (typed.containsIgnoreCase ("inf") ? clipops::clipGainMinDb
  5589. : typed.retainCharacters ("0123456789.,-+").replaceCharacter (',', '.').getDoubleValue());
  5590. }),
  5591. true);
  5592. });
  5593. // issue #274 (round 190qr): the LYNX extra's switch
  5594. menu.addSeparator();
  5595. menu.addItem (tr ("The clip gain handle stays in view") + " (LYNX)", true, cliphandle::gainFollowsView(),
  5596. [] { workflowextras::setExtra ("playlist.gainHandleFollowsView", ! cliphandle::gainFollowsView()); });
  5597. return menu;
  5598. }
  5599. // FL's fade handle menu (EventEditForm PLFadeHandleMenu, PLFadeHandleMenuClick 0xea9040 -> FUN_00d01bc0; checks from its
  5600. // popup FUN_00cfcdf0, round 189i; FL 2026's own menu compared in round 189l): on the clicked clip, or on every selected
  5601. // audio clip when it is selected; `side` 0 = the fade in, 1 = the fade out. Create crossfade: round 189n. (Normalize and
  5602. // Normalize selection as a group belong to the gain handle's menu, showGainMenu.)
  5603. void PlaylistComponent::showFadeHandleMenu (int index, int side)
  5604. {
  5605. if (index < 0 || index >= (int) engine.getSong().playlist.size())
  5606. return;
  5607. fadeHandleMenu (index, side).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  5608. }
  5609. juce::PopupMenu PlaylistComponent::fadeHandleMenu (int index, int side, bool clipMenu)
  5610. {
  5611. const auto& song = engine.getSong();
  5612. juce::PopupMenu menu;
  5613. if (index < 0 || index >= (int) song.playlist.size())
  5614. return menu;
  5615. std::vector<int> targets;
  5616. for (auto i : isSelected (index) ? selection : std::vector<int> { index })
  5617. if (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio)
  5618. targets.push_back (i);
  5619. const auto& clip = song.playlist[(std::size_t) index];
  5620. const auto msPerTick = 60000.0 / (juce::jmax (1.0, song.bpm) * ppq);
  5621. const auto lengthMs = (double) (side == 0 ? clip.fadeIn : clip.fadeOut) * msPerTick;
  5622. auto edit = [this, targets] (std::function<void (Clip&)> change) {
  5623. engine.editSong ([targets, change] (Song& s) {
  5624. for (auto i : targets)
  5625. if (i < (int) s.playlist.size())
  5626. change (s.playlist[(std::size_t) i]);
  5627. });
  5628. repaint();
  5629. };
  5630. auto setMs = [edit, side, msPerTick] (double ms) {
  5631. edit ([side, ticks = (std::int64_t) std::llround (juce::jmax (0.0, ms) / msPerTick)] (Clip& c) {
  5632. auto& fade = side == 0 ? c.fadeIn : c.fadeOut;
  5633. fade = juce::jlimit<std::int64_t> (0, c.length, ticks);
  5634. if (fade > 0)
  5635. clipops::setManualFade (c, side, true); // a set fade is a manual one (FL's fade flags bit 0 / 1)
  5636. });
  5637. };
  5638. // FL 2026's fade handle menu (GUI, rounds 189l / 189n: shots FL-fade-in-menu-overlap.png): "Reset fade in" / "Reset fade
  5639. // out" even on a crossfaded side, then "Create crossfade", enabled when the side has a clip to cross (FUN_00d023d0).
  5640. // ("Reset ... tension" belongs to FL's tension handle, the circle in a fade: fadeTensionMenu, round 190jz.)
  5641. // (round 190ey, live check 190ew PL-7: the clip menu's "Fade in / out curve" submenu reads "Reset", then the gain
  5642. // handle's Normalize items; core flclipmenu::fadeCurve)
  5643. menu.addItem (clipMenu ? tr ("Reset") : side == 0 ? tr ("Reset fade in") : tr ("Reset fade out"), [edit, side] {
  5644. edit ([side] (Clip& c) {
  5645. (side == 0 ? c.fadeIn : c.fadeOut) = 0;
  5646. (side == 0 ? c.fadeInTension : c.fadeOutTension) = 0.0f;
  5647. });
  5648. });
  5649. if (clipMenu)
  5650. {
  5651. menu.addItem (tr ("Normalize"), [this, targets] { normalizeClips (targets, false); });
  5652. menu.addItem (tr ("Normalize selection as a group"), [this, targets] { normalizeClips (targets, true); });
  5653. }
  5654. std::vector<int> menuClips; // FL's FUN_00cf9770: the selection when the clicked clip is in it, else the clicked clip
  5655. for (auto i : isSelected (index) ? selection : std::vector<int> { index })
  5656. if (i >= 0 && i < (int) song.playlist.size())
  5657. menuClips.push_back (i);
  5658. menu.addItem (tr ("Create crossfade"), clipops::canCreateCrossfade (song.playlist, menuClips, side, selection), false,
  5659. [this, index, side, chosen = selection] {
  5660. engine.editSong ([index, side, chosen] (Song& s) { clipops::createCrossfades (s.playlist, index, side, chosen); });
  5661. repaint();
  5662. });
  5663. if (! clipMenu)
  5664. {
  5665. menu.addItem (tr ("Copy value"), [lengthMs] { copiedFadeMs = lengthMs; hasCopiedFade = true; });
  5666. menu.addItem (tr ("Paste value"), hasCopiedFade, false, [setMs] { setMs (copiedFadeMs); });
  5667. menu.addItem (tr ("Type in value..."), [lengthMs, setMs] {
  5668. auto* window = new juce::AlertWindow (tr ("Fade"), tr ("Milliseconds"), juce::MessageBoxIconType::NoIcon);
  5669. window->addTextEditor ("value", juce::String (lengthMs, 1));
  5670. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5671. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5672. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, setMs] (int result) {
  5673. if (result == 1)
  5674. setMs (window->getTextEditorContents ("value").retainCharacters ("0123456789.,").replaceCharacter (',', '.').getDoubleValue());
  5675. }),
  5676. true);
  5677. });
  5678. }
  5679. // (the clip menu shows Manual greyed, with the side's state: FL's faded tick)
  5680. menu.addItem (tr ("Manual"), ! clipMenu, clipops::manualFade (clip, side), [edit, side, on = ! clipops::manualFade (clip, side)] {
  5681. edit ([side, on] (Clip& c) { clipops::setManualFade (c, side, on); });
  5682. });
  5683. menu.addSectionHeader (tr ("Declicker"));
  5684. const auto choice = clipops::declickChoice (clip, side);
  5685. const auto addChoice = [&] (const juce::String& text, int value, bool ticked) {
  5686. menu.addItem (text, true, ticked, [edit, side, value] { edit ([side, value] (Clip& c) { clipops::setDeclickChoice (c, side, value); }); });
  5687. };
  5688. addChoice (tr ("Automatic"), clipops::declickAutomatic, choice == clipops::declickAutomatic || choice == clipops::declickJoined);
  5689. addChoice (tr ("Disabled"), clipops::declickDisabled, choice == clipops::declickDisabled);
  5690. addChoice (tr ("Enabled"), clipops::declickEnabled, choice == clipops::declickEnabled);
  5691. menu.addSectionHeader (tr ("Curve shape"));
  5692. const auto linear = (clip.linearFades & (side == 0 ? 1 : 2)) != 0;
  5693. const auto setLinear = [edit, side] (bool on) {
  5694. edit ([side, on] (Clip& c) {
  5695. const auto bit = (std::uint8_t) (side == 0 ? 1 : 2);
  5696. c.linearFades = on ? (std::uint8_t) (c.linearFades | bit) : (std::uint8_t) (c.linearFades & ~bit);
  5697. });
  5698. };
  5699. menu.addItem (tr ("Smooth curve"), true, ! linear, [setLinear] { setLinear (false); });
  5700. menu.addItem (tr ("Single curve"), true, linear, [setLinear] { setLinear (true); });
  5701. return menu;
  5702. }
  5703. // Round 190jz (issue #194): FL 2026's menu on a fade's tension handle (GUI shot fl-194-tension-menu.png): Reset fade in /
  5704. // out tension, Create crossfade, Copy value, Paste value, Type in value... (FL's field: "Tension ±0-1 or %"), and the
  5705. // Curve shape choice. On the clicked clip, or every selected audio clip when it is selected (as the fade handle's menu).
  5706. juce::PopupMenu PlaylistComponent::fadeTensionMenu (int index, int side)
  5707. {
  5708. const auto& song = engine.getSong();
  5709. juce::PopupMenu menu;
  5710. if (index < 0 || index >= (int) song.playlist.size())
  5711. return menu;
  5712. std::vector<int> targets;
  5713. for (auto i : isSelected (index) ? selection : std::vector<int> { index })
  5714. if (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio)
  5715. targets.push_back (i);
  5716. const auto& clip = song.playlist[(std::size_t) index];
  5717. const auto handle = clipops::fadeTensionHandle (side == 0 ? clip.fadeInTension : clip.fadeOutTension);
  5718. auto setHandle = [this, targets, side] (double v) {
  5719. engine.editSong ([targets, side, raw = clipops::fadeTensionFromHandle (v)] (Song& s) {
  5720. for (auto i : targets)
  5721. if (i < (int) s.playlist.size())
  5722. (side == 0 ? s.playlist[(std::size_t) i].fadeInTension : s.playlist[(std::size_t) i].fadeOutTension) = raw;
  5723. });
  5724. repaint();
  5725. };
  5726. menu.addItem (side == 0 ? tr ("Reset fade in tension") : tr ("Reset fade out tension"), [setHandle] { setHandle (0.0); });
  5727. std::vector<int> menuClips;
  5728. for (auto i : isSelected (index) ? selection : std::vector<int> { index })
  5729. if (i >= 0 && i < (int) song.playlist.size())
  5730. menuClips.push_back (i);
  5731. menu.addItem (tr ("Create crossfade"), clipops::canCreateCrossfade (song.playlist, menuClips, side, selection), false,
  5732. [this, index, side, chosen = selection] {
  5733. engine.editSong ([index, side, chosen] (Song& s) { clipops::createCrossfades (s.playlist, index, side, chosen); });
  5734. repaint();
  5735. });
  5736. menu.addItem (tr ("Copy value"), [handle] { copiedFadeTension = handle; hasCopiedFadeTension = true; });
  5737. menu.addItem (tr ("Paste value"), hasCopiedFadeTension, false, [setHandle] { setHandle (copiedFadeTension); });
  5738. menu.addItem (tr ("Type in value..."), [handle, setHandle] {
  5739. auto* window = new juce::AlertWindow (tr ("Tension"), tr ("Tension ±0-1 or %"), juce::MessageBoxIconType::NoIcon);
  5740. window->addTextEditor ("value", juce::String (handle, 4));
  5741. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5742. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5743. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, setHandle] (int result) {
  5744. if (result != 1)
  5745. return;
  5746. const auto text = window->getTextEditorContents ("value").trim();
  5747. const auto number = text.retainCharacters ("-+0123456789.,").replaceCharacter (',', '.').getDoubleValue();
  5748. setHandle (text.containsChar ('%') ? number / 100.0 : number);
  5749. }),
  5750. true);
  5751. });
  5752. menu.addSectionHeader (tr ("Curve shape"));
  5753. const auto linear = (clip.linearFades & (side == 0 ? 1 : 2)) != 0;
  5754. auto setLinear = [this, targets, side] (bool on) {
  5755. engine.editSong ([targets, side, on] (Song& s) {
  5756. const auto bit = (std::uint8_t) (side == 0 ? 1 : 2);
  5757. for (auto i : targets)
  5758. if (i < (int) s.playlist.size())
  5759. {
  5760. auto& c = s.playlist[(std::size_t) i];
  5761. c.linearFades = on ? (std::uint8_t) (c.linearFades | bit) : (std::uint8_t) (c.linearFades & ~bit);
  5762. }
  5763. });
  5764. repaint();
  5765. };
  5766. menu.addItem (tr ("Smooth curve"), true, ! linear, [setLinear] { setLinear (false); });
  5767. menu.addItem (tr ("Single curve"), true, linear, [setLinear] { setLinear (true); });
  5768. return menu;
  5769. }
  5770. int PlaylistComponent::clipAt (int x, int y, bool& onRightEdge) const
  5771. {
  5772. bool left = false;
  5773. return clipAt (x, y, onRightEdge, left);
  5774. }
  5775. int PlaylistComponent::clipAt (int x, int y, bool& onRightEdge, bool& onLeftEdge) const
  5776. {
  5777. const auto& playlist = engine.getSong().playlist;
  5778. const auto track = yToTrack (y);
  5779. onRightEdge = onLeftEdge = false;
  5780. for (int i = (int) playlist.size() - 1; i >= 0; --i)
  5781. {
  5782. const auto& c = playlist[(std::size_t) i];
  5783. if (c.track != track)
  5784. continue;
  5785. // the left edge only on clips wide enough to still be grabbed in the middle
  5786. gesture::EdgeRules rules;
  5787. rules.minimumForLeft = 24.0;
  5788. // FL's Edit › "Allow resizing from left" off (FUN_00e8e840): the left edge is part of the body, it moves the clip
  5789. rules.allowLeft = EditorGlobals::get().leftResizing;
  5790. if (const auto zone = gesture::zoneAt (x, tickToX ((double) c.start), tickToX ((double) c.end()), rules); zone != gesture::Zone::outside)
  5791. {
  5792. onRightEdge = zone == gesture::Zone::rightEdge;
  5793. onLeftEdge = zone == gesture::Zone::leftEdge;
  5794. return i;
  5795. }
  5796. }
  5797. return -1;
  5798. }
  5799. std::int64_t PlaylistComponent::snapLine (double tick) const
  5800. {
  5801. // the grid line nearest to `tick` (FL's ruler click, round 169d); "Nearest" (clip edges) as snap() does
  5802. const auto& option = grid::resolve (snapBox);
  5803. if (option.kind == grid::Kind::nearest)
  5804. return snap (tick, true);
  5805. const auto step = gridTicks();
  5806. if (step == engine.getSong().barTicks()) // (whole bars: time signatures)
  5807. {
  5808. const auto b = engine.getSong().barAt ((std::int64_t) std::max (0.0, std::floor (tick)));
  5809. return tick - (double) b.tick >= (double) b.length * 0.5 ? b.tick + b.length : b.tick;
  5810. }
  5811. return noteedit::snapRound (tick, step);
  5812. }
  5813. void PlaylistComponent::seekTo (int x, bool snapOn)
  5814. {
  5815. const auto tick = juce::jmax (0.0, snapOn ? (double) snapLine (xToTick (x)) : xToTick (x));
  5816. insertMarkTrack = -1; // (round 190mk: the ruler and the tools move the position elsewhere: Live's marker goes)
  5817. if (engine.getSong().mode != PlayMode::song)
  5818. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  5819. // while playing, FL's "Quantize song jumps" makes the jump wait for the next beat / bar
  5820. const auto waits = engine.getTransport().playing.load() && engine.quantizeSongJumps.load() > 0;
  5821. engine.jumpTo (tick);
  5822. EditorGlobals::get().markSeek ((std::int64_t) tick, true); // FL: Stop goes back here (issue #169)
  5823. if (! waits)
  5824. playheadTick = tick;
  5825. repaint();
  5826. }
  5827. bool PlaylistComponent::isSelected (int index) const
  5828. {
  5829. return std::binary_search (selection.begin(), selection.end(), index);
  5830. }
  5831. void PlaylistComponent::setSelection (std::vector<int> indices)
  5832. {
  5833. std::sort (indices.begin(), indices.end());
  5834. indices.erase (std::unique (indices.begin(), indices.end()), indices.end());
  5835. const auto changed = indices != selection;
  5836. selection = std::move (indices);
  5837. knownClipCount = engine.getSong().playlist.size();
  5838. repaint();
  5839. if (changed && onSelectionChanged) // (round 190qu)
  5840. onSelectionChanged();
  5841. }
  5842. std::vector<int> PlaylistComponent::sortClips (std::vector<int> placed, bool changedTrack)
  5843. {
  5844. auto tracked = selection;
  5845. const auto selected = tracked.size();
  5846. tracked.insert (tracked.end(), placed.begin(), placed.end());
  5847. std::vector<int> conflicts;
  5848. engine.editSong ([&tracked, &conflicts, selected, changedTrack] (Song& s) {
  5849. noteedit::sortByStartTracking (s.playlist, tracked);
  5850. // the placed audio clips on an audio track play through its mixer track (round 146a; issue #15: only those,
  5851. // FL's way — a shared channel waits for the "Make clip unique?" answer)
  5852. const std::vector<int> moved (tracked.begin() + (std::ptrdiff_t) selected, tracked.end());
  5853. conflicts = trackmodes::audioTrackConflicts (s, moved);
  5854. trackmodes::followAudioTracks (s, moved);
  5855. if (changedTrack && trackonly::clipsFollowTracks()) // (round 190re: 1 track = 1 instrument)
  5856. trackonly::followTracks (s, moved);
  5857. }, false);
  5858. placed.assign (tracked.begin() + (std::ptrdiff_t) selected, tracked.end());
  5859. tracked.resize (selected);
  5860. setSelection (tracked);
  5861. if (! conflicts.empty())
  5862. askToMakeClipsUnique (placed, std::move (conflicts));
  5863. return placed;
  5864. }
  5865. void PlaylistComponent::askToMakeClipsUnique (std::vector<int> placed, std::vector<int> channels)
  5866. {
  5867. // FL 2026 asks once per channel; Yes = a copy of the channel for the placed clips, routed to the audio track
  5868. if (channels.empty())
  5869. return;
  5870. const auto channel = channels.front();
  5871. channels.erase (channels.begin());
  5872. const auto& song = engine.getSong();
  5873. if (channel < 0 || channel >= (int) song.channels.size())
  5874. return askToMakeClipsUnique (std::move (placed), std::move (channels));
  5875. // what the clips were when asked: an edit in between (the box is not modal) must not hit other clips
  5876. std::vector<std::tuple<int, int, std::int64_t>> was;
  5877. for (const auto i : placed)
  5878. if (i >= 0 && i < (int) song.playlist.size())
  5879. was.emplace_back (i, song.playlist[(std::size_t) i].track, song.playlist[(std::size_t) i].start);
  5880. const auto name = juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str());
  5881. auto options = juce::MessageBoxOptions()
  5882. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  5883. .withTitle (tr ("Make clip unique?"))
  5884. .withMessage (tr ("The clip \"{0}\" is also used on another audio track.\n\nDo you want to make this instance unique and then route it to this audio track?",
  5885. { name }))
  5886. .withButton (tr ("Yes"))
  5887. .withButton (tr ("No"))
  5888. .withAssociatedComponent (this);
  5889. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<PlaylistComponent> (this), placed, channels, channel, was] (int result) mutable {
  5890. if (safe == nullptr)
  5891. return;
  5892. if (result == 1)
  5893. {
  5894. std::vector<int> still;
  5895. const auto& now = safe->engine.getSong().playlist;
  5896. for (const auto& [i, track, start] : was)
  5897. if (i < (int) now.size() && now[(std::size_t) i].track == track && now[(std::size_t) i].start == start
  5898. && now[(std::size_t) i].channel == channel)
  5899. still.push_back (i);
  5900. if (! still.empty())
  5901. safe->engine.editSong ([&still] (Song& s) { trackmodes::followAudioTracks (s, still, true); });
  5902. }
  5903. safe->askToMakeClipsUnique (std::move (placed), std::move (channels));
  5904. });
  5905. }
  5906. // FL's Edit › "Create new clips with manual fades" (EECreateNewClipsWithManualFades, off by default): a new audio clip's
  5907. // fades start reset and flagged manual (FUN_010657a0, then FUN_01065830 / FUN_01065840 set bits 0 / 1 of its fade flags),
  5908. // so its edges use its own fade handles instead of the channel's declicker: with no fade they are sharp cuts (the clip
  5909. // voice skips the declicker on a manual side, round 189i).
  5910. static std::uint32_t newClipFadeFlags() noexcept
  5911. {
  5912. return EditorGlobals::get().manualFades ? 3u : 0u;
  5913. }
  5914. Clip PlaylistComponent::makeBrushClip (int track, std::int64_t start) const
  5915. {
  5916. // what is chosen in the Picker: the current pattern, an audio clip or an automation clip
  5917. const auto& song = engine.getSong();
  5918. // issue #175: a clip clicked with the Pencil / Brush paints as it is (FL), while it still is what the tools paint
  5919. if (brush.picked.has_value() && painttemplate::matches (*brush.picked, brush.kind, brush.index, song.currentPattern))
  5920. {
  5921. auto c = painttemplate::paint (*brush.picked, track, start);
  5922. if (c.kind == ClipKind::audio)
  5923. c.flFadeFlags = brush.picked->flFadeFlags;
  5924. return c;
  5925. }
  5926. return makeSourceClip (brush.kind, brush.kind == ClipKind::pattern ? song.currentPattern : brush.index, track, start);
  5927. }
  5928. Clip PlaylistComponent::makeSourceClip (ClipKind kind, int index, int track, std::int64_t start) const
  5929. {
  5930. // a pattern (an invalid one: the current pattern), an audio clip's channel or an automation clip, with its plain length
  5931. const auto& song = engine.getSong();
  5932. Clip c;
  5933. c.pattern = kind == ClipKind::pattern && index >= 0 && index < (int) song.patterns.size() ? index : song.currentPattern;
  5934. c.track = track;
  5935. c.start = juce::jmax<std::int64_t> (0, start);
  5936. c.length = (c.pattern == song.currentPattern || c.pattern < 0 || c.pattern >= (int) song.patterns.size()
  5937. ? song.activePattern()
  5938. : song.patterns[(std::size_t) c.pattern])
  5939. .effectiveLength (song.meter());
  5940. if (kind == ClipKind::audio && index >= 0 && index < (int) song.channels.size()
  5941. && song.channels[(std::size_t) index].instrument == InstrumentKind::audioClip)
  5942. {
  5943. c.kind = ClipKind::audio;
  5944. c.channel = index;
  5945. c.pattern = 0;
  5946. c.flFadeFlags = newClipFadeFlags();
  5947. // audio length in ticks at the current BPM
  5948. if (auto data = engine.getSampleLibrary().load (juce::String::fromUTF8 (song.channels[(std::size_t) index].samplePath.c_str())))
  5949. c.length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) ((double) data->frames() / data->sampleRate * song.bpm / 60.0 * ppq));
  5950. }
  5951. else if (kind == ClipKind::automation && index >= 0 && index < (int) song.automations.size())
  5952. {
  5953. c.kind = ClipKind::automation;
  5954. c.automation = index;
  5955. c.pattern = 0;
  5956. c.length = song.barTicks() * 4; // 4 bars
  5957. }
  5958. return c;
  5959. }
  5960. void PlaylistComponent::setTimeSelection (std::int64_t from, std::int64_t to)
  5961. {
  5962. engine.editSong ([from, to] (Song& s) {
  5963. s.loopStart = from;
  5964. s.loopEnd = to;
  5965. s.mode = PlayMode::song;
  5966. }, false);
  5967. setSelection (to > from ? noteedit::clipsInTime (engine.getSong().playlist, from, to) : std::vector<int> {});
  5968. }
  5969. void PlaylistComponent::setTimeSelectionForSnapshot (int fromBar, int toBar)
  5970. {
  5971. const auto bar = engine.getSong().barTicks();
  5972. setTimeSelection (fromBar * bar, toBar * bar);
  5973. }
  5974. void PlaylistComponent::setViewForSnapshot (double pixelsPerBar, int firstBar, int firstTrack)
  5975. {
  5976. const auto bar = (double) engine.getSong().barTicks();
  5977. pixelsPerTick = pixelsPerBar / bar;
  5978. scrollTicks = firstBar * bar;
  5979. scrollY = juce::jmax (0, firstTrack) * defaultRowHeight();
  5980. updateScrollBars();
  5981. repaint();
  5982. }
  5983. ui::Hint PlaylistComponent::hoverForSnapshot()
  5984. {
  5985. const auto& playlist = engine.getSong().playlist;
  5986. const auto grid = gridArea();
  5987. // the last clip fully in view (the floating Channel Rack tends to cover the first ones)
  5988. for (int i = (int) playlist.size() - 1; i >= 0; --i)
  5989. if (const auto r = clipBounds (i); grid.contains (r) && r.getWidth() >= 40 && playlist[(std::size_t) i].kind == ClipKind::pattern)
  5990. {
  5991. const auto at = juce::Point<int> (r.getRight() - 2, r.getCentreY() + 4);
  5992. updateHover (at, {});
  5993. return hintAt (at);
  5994. }
  5995. return {};
  5996. }
  5997. void PlaylistComponent::mouseDown (const juce::MouseEvent& e)
  5998. {
  5999. if (touchInput.mouseDown (e)) // round 190pm (P23): a finger in Touch mode is held back until it means something
  6000. return;
  6001. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::begin); // (round 190jv: one undo step per gesture)
  6002. // round 190rw: the press's own edits are done when it returns: from then on a song change is someone else's
  6003. dragAbandoned = false;
  6004. const struct ArmWatch
  6005. {
  6006. PlaylistComponent& p;
  6007. ~ArmWatch()
  6008. {
  6009. p.dragWatch.arm (p.engine);
  6010. p.noteDragIds();
  6011. }
  6012. } armWatch { *this };
  6013. followEditStamp = engine.getPublishCount(); // (round 190im, R15)
  6014. downMods = e.mods;
  6015. startedOnEmpty = erasedSomething = holdExpired = false;
  6016. dragCopies = false;
  6017. hover = {};
  6018. gliding = false;
  6019. pointerPress = placedByDoubleClick = false; // (round 190jq)
  6020. // round 190qe: a zoom glide lands; the press is kept in the song (a selection box's corner while the view runs);
  6021. // the selection before the press is what "Restore selection" brings back if this click replaces it
  6022. settleViewGlide();
  6023. edgeScroller.stop();
  6024. edgeDragEvent.reset();
  6025. dragDownTick = xToTick (e.x);
  6026. dragDownContentY = e.y + scrollY;
  6027. selectionAtPress = clipKeys (selection);
  6028. // FL's middle + right click (round 190mp, DE-62; FL manual Playlist §8, captured in the Piano roll 190mp A3.2): the
  6029. // second button opens the main menu at the mouse with the tools' "Mode" column on its left
  6030. if (e.mods.isMiddleButtonDown() && e.mods.isRightButtonDown() && e.x >= headerWidth)
  6031. {
  6032. drag = Drag::none;
  6033. setMouseCursor (juce::MouseCursor::NormalCursor);
  6034. toolModeMenu (tools, [this] (EditTool t) { tools.setTool (t); }, mainMenu != nullptr ? mainMenu() : juce::PopupMenu())
  6035. .showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  6036. return;
  6037. }
  6038. if (e.mods.isMiddleButtonDown() && e.x >= headerWidth) // middle-drag pans, in every tool
  6039. {
  6040. const auto onClips = gridArea().contains (e.getPosition());
  6041. const auto onRuler = e.y >= rulerTop && e.y < headerHeight;
  6042. if (onClips && flmods::ctrl (e.mods) && ! e.mods.isAltDown()) // FL: Ctrl+middle-drag = vertical zoom
  6043. {
  6044. drag = Drag::heightZoom;
  6045. const auto track = yToTrack (e.y);
  6046. heightZoomTrackY = trackToY (track); // the top of the track under the mouse stays where it is
  6047. heightZoomStartHeight = juce::jmax (1, heightOf (track));
  6048. trackZoomStart = trackZoom;
  6049. heightZoomDrag.begin (e.y);
  6050. e.source.enableUnboundedMouseMovement (true);
  6051. return;
  6052. }
  6053. if (onRuler || (onClips && e.mods.isAltDown())) // FL: middle-drag on the ruler / Alt+middle-drag = time zoom
  6054. {
  6055. drag = Drag::timeZoom;
  6056. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  6057. timeZoomDrag.begin (width / pixelsPerTick, scrollTicks + width * 0.5 / pixelsPerTick, e.x, e.y);
  6058. e.source.enableUnboundedMouseMovement (true);
  6059. return;
  6060. }
  6061. drag = Drag::pan;
  6062. panStartTicks = scrollTicks;
  6063. panStartY = scrollY;
  6064. setMouseCursor (editorCursor (gesture::Cursor::pan));
  6065. return;
  6066. }
  6067. // the vertical zoom handle: drag up = taller tracks
  6068. if (trackZoomHandle().contains (e.getPosition()) && e.mods.isLeftButtonDown())
  6069. {
  6070. drag = Drag::trackZoom;
  6071. trackZoomStart = trackZoom;
  6072. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  6073. return;
  6074. }
  6075. // round 190jq (issue #164, LYNX extra): the header column's right edge, while its switch is on: drag = wider headers,
  6076. // double click = FL's width (core/PlaylistViewOptions.h › headerwidth)
  6077. if (onHeaderGrip (e.getPosition()) && e.mods.isLeftButtonDown())
  6078. {
  6079. if (e.getNumberOfClicks() > 1)
  6080. {
  6081. headerwidth::extra = 0;
  6082. updateHeaderWidth();
  6083. if (onViewOptionChanged)
  6084. onViewOptionChanged();
  6085. ui::postHint ({ tr ("Track header width"), juce::String (headerWidth) + " px", false, false });
  6086. return;
  6087. }
  6088. drag = Drag::headerWidth;
  6089. headerWidthDragStart = headerwidth::clampExtra (headerwidth::extra);
  6090. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  6091. return;
  6092. }
  6093. // the header's side strips (live check 190gu B1, round 190gw; FL headers only): the left 10 px flip the row between its
  6094. // size and the smallest (FL's quick lock), the 9 px column at the right edge selects (click: the track alone,
  6095. // Shift+click / right-click: toggle it, no menu; a double click: the track alone <-> every track; a drag: a range)
  6096. if (! simpleHeaders && e.x >= 0 && e.x < headerWidth && e.y >= tracksTop() && e.y < gridArea().getBottom())
  6097. {
  6098. const auto track = yToTrack (e.y);
  6099. const auto zone = trackhdr::zoneAt (e.x, headerWidth);
  6100. const auto onRow = e.y - trackToY (track) < heightOf (track) && ! noteedit::isFoldedAway (engine.getSong(), track);
  6101. if (onRow && zone == trackhdr::HeaderZone::lockStrip && e.mods.isLeftButtonDown() && ! trackArrow (track).contains (e.getPosition()))
  6102. {
  6103. bandToggleLock (track);
  6104. return;
  6105. }
  6106. if (onRow && zone == trackhdr::HeaderZone::selectionStrip && (e.mods.isLeftButtonDown() || flmods::popup (e.mods)))
  6107. {
  6108. const auto action = trackhdr::stripPress (flmods::ctrl (e.mods), e.mods.isShiftDown(), flmods::popup (e.mods), e.getNumberOfClicks() > 1);
  6109. if (action != trackhdr::StripAction::ctrlPress) // (Ctrl: the header's own Ctrl press below)
  6110. {
  6111. auto sel = sortedTrackSelection();
  6112. if (action == trackhdr::StripAction::onlyOrAll)
  6113. trackhdr::applyOnlyOrAll (sel, track, numTracks());
  6114. else
  6115. trackhdr::applySelection (sel, track, action == trackhdr::StripAction::toggle ? trackhdr::SelMode::toggle : trackhdr::SelMode::only);
  6116. selectedTracks = sel;
  6117. const auto nowSelected = std::binary_search (sel.begin(), sel.end(), track);
  6118. currentTrack = selectedTracks.empty() ? -1 : track;
  6119. if (action == trackhdr::StripAction::only)
  6120. followLinkedTrack (track);
  6121. if (e.mods.isLeftButtonDown())
  6122. {
  6123. drag = Drag::headerSelect; // (FUN_012e8740: the drag adds, or removes, the tracks crossed)
  6124. headerDragAnchor = track;
  6125. headerDragAdding = nowSelected;
  6126. headerDragClips = false;
  6127. headerCtrlPending = false;
  6128. }
  6129. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  6130. return;
  6131. }
  6132. }
  6133. }
  6134. // issue #154 (round 190ht, LYNX extra): the linked header's insert effects column
  6135. if (! e.mods.isMiddleButtonDown() && insertsMouseDown (e))
  6136. return;
  6137. // issue #206 follow-up (round 190qb, LYNX extra): a middle-click on its "+ Add" opens the effect search for that
  6138. // insert's next free slot (as a middle-click on an empty Mixer slot)
  6139. if (e.mods.isMiddleButtonDown() && ! e.mods.isLeftButtonDown() && ! e.mods.isRightButtonDown() && insertsAddSearch (e.getPosition()))
  6140. return;
  6141. // the resize band at the bottom of a header (FL AUTracksPanelMouseDown, round 190ft): drag resizes the track (and
  6142. // every selected track when it is one of them; LYNX's Shift: every track); Alt+click or a middle click = 100 %
  6143. // and unlocked; a double click or a click on a locked row flips "Lock to this size"
  6144. if (const auto divider = dividerAt (e.getPosition()); divider >= 0 && (e.mods.isLeftButtonDown() || e.mods.isMiddleButtonDown()))
  6145. {
  6146. const auto press = e.mods.isMiddleButtonDown() ? trackhdr::BandPress::reset
  6147. : trackhdr::bandPress (pltracks::isSizeLocked (engine.getSong(), divider), e.getNumberOfClicks() > 1, e.mods.isAltDown());
  6148. if (press == trackhdr::BandPress::toggleLock)
  6149. {
  6150. bandToggleLock (divider);
  6151. return;
  6152. }
  6153. if (press == trackhdr::BandPress::reset)
  6154. {
  6155. bandReset (divider);
  6156. return;
  6157. }
  6158. drag = Drag::trackResize;
  6159. resizeTrack = divider;
  6160. resizeAll = e.mods.isShiftDown();
  6161. resizeStartHeight = heightOf (divider);
  6162. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  6163. return;
  6164. }
  6165. // round 190pa (P14, core/RangeEdit.h): Ctrl+Alt+drag (Pattern) or a plain drag on empty space (Clip-launch) draws a
  6166. // range on chosen tracks; a drag inside it moves its
  6167. // content, a right-click opens its menu; any other press clears it
  6168. if (rangeMouseDown (e))
  6169. return;
  6170. // issue #207 (round 190lw): the pen, a curve's rubber band and a selected points' move (LYNX extras)
  6171. if (pointMouseDown (e, -1))
  6172. return;
  6173. // round 190jr: the Simple automation view (its header menu; the first point on a row makes its lane)
  6174. if (simpleAutoMouseDown (e))
  6175. return;
  6176. // round 177b: automation lanes (their own gestures in every tool)
  6177. if (laneMouseDown (e))
  6178. return;
  6179. // track header: the LED mutes (Ctrl+click or right-click on it: solo), a group header's arrow folds the
  6180. // group, a click elsewhere selects the track; right-click elsewhere: track menu
  6181. if (e.x < headerWidth && e.y >= tracksTop() && e.y < gridArea().getBottom())
  6182. {
  6183. const auto track = yToTrack (e.y);
  6184. if (simpleHeaders) // round 190jc (SG-2): the round "+" adds a track; the rows under the real tracks are not there
  6185. {
  6186. if (track == dropLaneTrack())
  6187. {
  6188. if (! flmods::popup (e.mods) && simpleAddButton().contains (e.getPosition()) && onSimpleAddTrack)
  6189. onSimpleAddTrack();
  6190. return;
  6191. }
  6192. if (track >= paintedRows())
  6193. return;
  6194. // round 190rc (Discord 11-24, sidthenugget): a click on the track's instrument icon opens (or closes) the
  6195. // instrument's window, as BandLab's instrument icon opens its instrument
  6196. if (! flmods::popup (e.mods) && e.mods.isLeftButtonDown() && onToggleChannelWindow)
  6197. if (const auto it = simpleIconBoxes.find (track); it != simpleIconBoxes.end() && it->second.expanded (2).contains (e.getPosition()))
  6198. if (const auto channel = simpleInstrumentChannel (track); channel >= 0)
  6199. {
  6200. selectTrack (track);
  6201. onToggleChannelWindow (channel);
  6202. return;
  6203. }
  6204. }
  6205. if (! flmods::popup (e.mods)) // round 177b: the lanes' fold arrow and "+A"
  6206. {
  6207. if (trackLaneArrow (track).expanded (2).contains (e.getPosition()))
  6208. {
  6209. editTrack (track, [] (PlaylistTrack& t) { t.lanesFolded = ! t.lanesFolded; });
  6210. return;
  6211. }
  6212. if (trackAddLane (track).contains (e.getPosition()))
  6213. {
  6214. showAddLaneMenu (track);
  6215. return;
  6216. }
  6217. }
  6218. // round 190pe (P20): the version chip opens the track's versions
  6219. if (! flmods::popup (e.mods) && trackVersionChip (track).contains (e.getPosition()))
  6220. {
  6221. buildTrackVersionMenu (track).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  6222. return;
  6223. }
  6224. if (noteedit::isFoldedAway (engine.getSong(), track)) // a thin row of a folded group: only its menu
  6225. {
  6226. if (flmods::popup (e.mods))
  6227. showTrackMenu (track);
  6228. return;
  6229. }
  6230. const auto onLed = ! liveTakeLane (track) && trackLed (track).expanded (3).contains (e.getPosition()); // (round 190oo: none drawn there)
  6231. const auto onArrow = trackArrow (track).contains (e.getPosition());
  6232. if (trackAudition (track).expanded (2).contains (e.getPosition()))
  6233. {
  6234. if (! flmods::popup (e.mods)) // not an edit: no undo step, and nothing about it is saved
  6235. engine.editSong ([track] (Song& s) { comp::setAudition (s, s.auditionLane == track ? -1 : track); }, false);
  6236. repaint (0, headerHeight, headerWidth, getHeight() - headerHeight);
  6237. return;
  6238. }
  6239. // FL's Shift+click on the mute switch = lock its state (round 190ld, DE-129): a solo elsewhere leaves it alone
  6240. if (onLed && e.mods.isShiftDown() && ! e.mods.isAltDown() && ! flmods::ctrl (e.mods) && ! flmods::popup (e.mods))
  6241. {
  6242. editTrack (track, [] (PlaylistTrack& t) { t.soloLock = ! t.soloLock; });
  6243. return;
  6244. }
  6245. // FL's group mute / solo (manual › Playlist › Mute / Solo, round 190jf B17): Alt+click on the mute LED of any track
  6246. // of a group mutes / unmutes the whole group, Alt+right-click solos it (core/NoteEdit.h › muteGroup / soloGroup)
  6247. if (onLed && e.mods.isAltDown() && ! noteedit::groupMuteSet (engine.getSong(), track).empty())
  6248. {
  6249. if (flmods::popup (e.mods))
  6250. engine.editSong ([track, count = numTracks()] (Song& s) {
  6251. noteedit::soloGroup (s, track, count, &flsettings::trackSoloMemory(), flsettings::options().restoreStateAfterSolo.load());
  6252. });
  6253. else
  6254. {
  6255. // (rollup 0.1.30: on linked headers, round 190ib, the LED is the insert's mute too)
  6256. std::vector<int> inserts;
  6257. if (linkedHeaders() || simpleHeaders)
  6258. for (const auto t : noteedit::groupMuteSet (engine.getSong(), track))
  6259. {
  6260. inserts.resize ((std::size_t) juce::jmax ((int) inserts.size(), t + 1), -1);
  6261. inserts[(std::size_t) t] = simpleInsert (t);
  6262. }
  6263. engine.editSong ([track, inserts] (Song& s) { noteedit::muteGroup (s, track, inserts); });
  6264. }
  6265. return;
  6266. }
  6267. // the Simple headers (round 184a), and the linked ones (round 190gz): M, S, volume, pan and "+FX" act on the
  6268. // track's mixer insert. Round 190oo (CS-24): an FL track's Simple header acts on the insert its clips play through
  6269. // (core/SimpleHeaderTarget.h); its M stays the Playlist track's mute (the code after this block, with FL's Shift /
  6270. // Alt / Ctrl clicks), so muting it never silences the other tracks on that insert
  6271. const auto borrowedLed = simpleHeaders && onLed && ! headerTarget (track).own;
  6272. if (const auto insert = headerInsert (track);
  6273. insert > 0 && ! borrowedLed && ! flmods::popup (e.mods) && ! (! simpleHeaders && onLed && flmods::ctrl (e.mods)))
  6274. {
  6275. const auto p = e.getPosition();
  6276. if (onLed && ! simpleHeaders && engine.getSong().isTrackMuted (track))
  6277. {
  6278. // a linked header's M is lit by a muted Playlist track too (FL's LED): the first click unmutes the track
  6279. editTrack (track, [] (PlaylistTrack& t) { t.muted = false; });
  6280. return;
  6281. }
  6282. // issue #265 (round 190qj): clips on this track that play through other inserts (a pattern whose channels
  6283. // are routed elsewhere) would keep playing under a lit M: M then mutes the Playlist track too (FL's track
  6284. // mute, every clip on it), and unmutes both
  6285. if (onLed && ! simpleHeaders && ! autolink::otherInsertsOnTrack (engine.getSong(), track, insert).empty())
  6286. {
  6287. const auto mute = ! engine.getSong().mixer[(std::size_t) insert].muted;
  6288. engine.editSong ([insert, track, mute] (Song& s) {
  6289. s.mixer[(std::size_t) insert].muted = mute;
  6290. if (track < (int) s.playlistTracks.size())
  6291. s.playlistTracks[(std::size_t) track].muted = mute;
  6292. });
  6293. return;
  6294. }
  6295. if (onLed || trackSolo (track).contains (p))
  6296. {
  6297. const auto solo = ! onLed;
  6298. engine.editSong ([insert, solo] (Song& s) {
  6299. auto& m = s.mixer[(std::size_t) insert];
  6300. if (solo)
  6301. m.solo = ! m.solo;
  6302. else
  6303. m.muted = ! m.muted;
  6304. });
  6305. return;
  6306. }
  6307. if (trackVolume (track).expanded (0, 4).contains (p) || trackPan (track).expanded (2).contains (p))
  6308. {
  6309. levelDrag = trackPan (track).expanded (2).contains (p) ? 2 : 1;
  6310. levelInsert = insert;
  6311. levelWidth = trackVolume (track).getWidth();
  6312. const auto& m = engine.getSong().mixer[(std::size_t) insert];
  6313. levelStart = levelDrag == 2 ? m.pan : m.volume;
  6314. if (levelDrag == 1) // a click on the bar sets the level there
  6315. {
  6316. const auto bar = trackVolume (track);
  6317. const auto v = juce::jlimit (0.0f, 1.0f, (float) (p.x - bar.getX()) / (float) juce::jmax (1, bar.getWidth()));
  6318. levelStart = v;
  6319. engine.editLevels ([insert, v] (Song& s) { s.mixer[(std::size_t) insert].volume = v; });
  6320. }
  6321. return;
  6322. }
  6323. if (trackFx (track).contains (p))
  6324. {
  6325. if (onTrackEffects)
  6326. onTrackEffects (insert);
  6327. return;
  6328. }
  6329. }
  6330. // an audio track's buttons (FL 2026): [LMB] on the record button arms / disarms its mixer track, on the input
  6331. // button opens the input source menu; a right-click on them does nothing in FL (no track menu either)
  6332. const auto onArm = trackArm (track).expanded (2).contains (e.getPosition());
  6333. const auto onInput = trackInput (track).expanded (2).contains (e.getPosition());
  6334. if (onArm || onInput)
  6335. {
  6336. const auto insert = trackmodes::armableInsert (engine.getSong(), track);
  6337. if (! flmods::popup (e.mods) && insert > 0)
  6338. {
  6339. if (onArm)
  6340. mixerinput::toggleArm (engine, insert, this);
  6341. else
  6342. mixerinput::showMenu (engine, insert, this);
  6343. }
  6344. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  6345. return;
  6346. }
  6347. if (onLed && (flmods::popup (e.mods) || flmods::ctrl (e.mods)))
  6348. engine.editSong ([track, count = numTracks()] (Song& s) {
  6349. noteedit::soloTrack (s, track, count, &flsettings::trackSoloMemory(), flsettings::options().restoreStateAfterSolo.load());
  6350. });
  6351. else if (flmods::popup (e.mods))
  6352. {
  6353. // FL: a right-click on a track that is not selected selects it alone first
  6354. if (! isTrackSelected (track))
  6355. {
  6356. selectedTracks = { track };
  6357. currentTrack = track;
  6358. followLinkedTrack (track);
  6359. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  6360. }
  6361. showTrackMenu (track);
  6362. }
  6363. else if (onLed)
  6364. editTrack (track, [] (PlaylistTrack& t) { t.muted = ! t.muted; });
  6365. else if (onArrow)
  6366. engine.editSong ([track] (Song& s) {
  6367. const auto folded = track < (int) s.playlistTracks.size() && s.playlistTracks[(std::size_t) track].collapsed;
  6368. noteedit::setGroupCollapsed (s, track, ! folded);
  6369. });
  6370. else if (! noteedit::isFoldedAway (engine.getSong(), track))
  6371. {
  6372. // FL's header press (AUTracksPanelMouseDown, round 190ft, core/TrackHeaderGestures.h): a click selects the
  6373. // track alone; Ctrl+click selects it alone with every clip on it, Ctrl+drag adds the tracks crossed (and
  6374. // their clips); Ctrl+Shift+click adds / removes the track (and a drag adds / removes the tracks crossed).
  6375. // LYNX keeps its Shift+click: the tracks from the last clicked one (round 165m).
  6376. const auto plan = trackhdr::planPress (flmods::ctrl (e.mods), e.mods.isShiftDown(), e.mods.isAltDown());
  6377. // round 190jf (B17, LYNX): Alt+drag moves the track with its folder; the press selects it alone, as FL's Alt+click
  6378. const auto altMove = e.mods.isAltDown() && ! flmods::ctrl (e.mods) && ! e.mods.isShiftDown() && ! simpleHeaders;
  6379. if (plan.lynxShiftRange && currentTrack >= 0)
  6380. {
  6381. selectedTracks.clear();
  6382. for (int t = juce::jmin (currentTrack, track); t <= juce::jmax (currentTrack, track); ++t)
  6383. selectedTracks.push_back (t);
  6384. }
  6385. else if (plan.ctrlClickToggles)
  6386. {
  6387. // Ctrl alone: decided by what follows (mouseDrag: FL's Ctrl press + range; mouseUp: LYNX's toggle)
  6388. drag = Drag::headerSelect;
  6389. headerDragAnchor = track;
  6390. headerDragAdding = true;
  6391. headerDragClips = true;
  6392. headerCtrlPending = true;
  6393. return;
  6394. }
  6395. else
  6396. {
  6397. auto sel = sortedTrackSelection();
  6398. trackhdr::applySelection (sel, track, plan.mode);
  6399. selectedTracks = sel;
  6400. const auto nowSelected = std::binary_search (sel.begin(), sel.end(), track);
  6401. if (plan.clips != trackhdr::ClipPick::none)
  6402. {
  6403. headerClipBase = plan.clips == trackhdr::ClipPick::add ? selection : std::vector<int> {};
  6404. selectClipsOnTracks (track, track, plan.clips == trackhdr::ClipPick::add);
  6405. }
  6406. if (const auto range = trackhdr::dragAfter (plan, nowSelected); range != trackhdr::RangeDrag::none)
  6407. {
  6408. drag = Drag::headerSelect;
  6409. headerDragAnchor = track;
  6410. headerDragAdding = range == trackhdr::RangeDrag::select;
  6411. headerDragClips = plan.clips != trackhdr::ClipPick::none;
  6412. }
  6413. if (plan.mode == trackhdr::SelMode::only && ! simpleHeaders)
  6414. followLinkedTrack (track);
  6415. if (altMove)
  6416. {
  6417. drag = Drag::headerMove;
  6418. headerMoveTrack = track;
  6419. headerMoveStartX = e.x;
  6420. headerMoveBefore = -1;
  6421. }
  6422. }
  6423. currentTrack = selectedTracks.empty() ? -1 : track; // (the last track removed: nothing is selected)
  6424. if (simpleHeaders)
  6425. selectTrackChannel (track); // (the typing piano and the touch keyboard play the track)
  6426. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  6427. }
  6428. return;
  6429. }
  6430. // ruler, FL 2026's rules (core/RulerGestures.h, docs/analise/REA_rodada168t.md): click = position; Ctrl / Shift /
  6431. // double-click drag, the Select tool or a right-drag = time selection; Ctrl+right-drag or the Zoom tool = zoom to
  6432. // a range; Shift+drag moves the selection. On a Mac, FL's Ctrl is Cmd (or Control, which is not a right click here)
  6433. if (e.y >= rulerTop && e.y < headerHeight && e.x >= headerWidth)
  6434. {
  6435. const auto fl = flmods::of (e.mods);
  6436. const auto& song = engine.getSong();
  6437. const auto snapOn = ! e.mods.isAltDown();
  6438. const auto tick = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  6439. const auto markerHit = markerTagAt (e.x, e.y);
  6440. // round 190hq (B11): a tempo marker's tag: drag it along the ruler, double-click it to type its tempo (the right
  6441. // button opens the ruler menu with its items)
  6442. if (const auto tempoHit = markerHit < 0 && ! fl.right && ! fl.ctrl && ! e.mods.isShiftDown() ? tempoTagAt (e.x, e.y) : -1; tempoHit >= 0)
  6443. {
  6444. if (e.getNumberOfClicks() >= 2)
  6445. {
  6446. editTempoMarker (0, tempoHit);
  6447. return;
  6448. }
  6449. drag = Drag::tempoMarker;
  6450. tempoDragMarker = tempoHit;
  6451. tempoDragTick = tempomarkers::list (song)[(std::size_t) tempoHit].tick;
  6452. return;
  6453. }
  6454. ruler::Press press;
  6455. press.mods = fl;
  6456. press.clicks = e.getNumberOfClicks();
  6457. press.tool = tools.getTool();
  6458. press.anyToolSeeks = ruler::seekWithAnyTool(); // #227 (round 190nq, LYNX extra)
  6459. press.onMarkerTag = markerHit >= 0;
  6460. press.hasSelection = song.hasLoop();
  6461. press.insideSelection = song.hasLoop() && xToTick (e.x) >= (double) song.loopStart && xToTick (e.x) < (double) song.loopEnd;
  6462. loopAnchor = tick;
  6463. rulerDoubleDrag = false;
  6464. rulerMenuOnClick = false;
  6465. switch (ruler::press (press))
  6466. {
  6467. case ruler::Action::markerMenu:
  6468. showRulerMenu (e.x, e.y);
  6469. return;
  6470. case ruler::Action::zoomRange:
  6471. drag = Drag::zoomRange;
  6472. rubberBand = {};
  6473. return;
  6474. case ruler::Action::adjust:
  6475. drag = Drag::loop;
  6476. loopAnchor = ruler::adjustAnchor (song.loopStart, song.loopEnd, tick);
  6477. setTimeSelection (juce::jmin (loopAnchor, tick), juce::jmax (loopAnchor, tick));
  6478. return;
  6479. case ruler::Action::select:
  6480. drag = Drag::loop;
  6481. // FL 2026 [SHOT round 166e]: a double click held and dragged draws a time selection, with the song
  6482. // position at its start; released in place it clears it (as a Ctrl+click does)
  6483. rulerDoubleDrag = press.clicks >= 2 && ! fl.right;
  6484. // LYNX: a right click released in place with no selection opens the ruler menu (FL: does nothing)
  6485. rulerMenuOnClick = fl.right;
  6486. return;
  6487. case ruler::Action::markerSpan:
  6488. {
  6489. const auto from = song.markers()[(std::size_t) markerHit].tick;
  6490. auto to = juce::jmax (from, song.songLength());
  6491. for (const auto& m : song.markers())
  6492. if (m.tick > from)
  6493. to = juce::jmin (to, m.tick);
  6494. if (to > from)
  6495. setTimeSelection (from, to);
  6496. return;
  6497. }
  6498. case ruler::Action::moveSelection:
  6499. drag = Drag::timeShift;
  6500. timeMoveFrom = song.loopStart;
  6501. timeMoveTo = song.loopEnd;
  6502. timeMoveAnchor = tick;
  6503. return;
  6504. case ruler::Action::moveWithClips:
  6505. drag = Drag::timeMove;
  6506. timeMoveOriginals = song.playlist;
  6507. timeMoveFrom = song.loopStart;
  6508. timeMoveTo = song.loopEnd;
  6509. timeMoveAnchor = tick;
  6510. timeMoveCopy = false;
  6511. return;
  6512. case ruler::Action::marker:
  6513. // FL's manual: "Left-click, hold & drag a marker to reposition it" (round 190ri). Released without a drag:
  6514. // LYNX goes to the marker (FL does nothing), on the release
  6515. drag = Drag::marker;
  6516. markerDragIndex = markerHit;
  6517. markerDragTick = song.markers()[(std::size_t) markerHit].tick;
  6518. markerDragMoved = false;
  6519. return;
  6520. case ruler::Action::seek:
  6521. break;
  6522. }
  6523. drag = Drag::seek;
  6524. rulerMark = tick; // (issue #211: FL's paste anchor, kept until the ruler's double click clears it)
  6525. seekTo (e.x, snapOn); // (it remembers the position for Stop: "Remember seek time")
  6526. return;
  6527. }
  6528. if (! gridArea().contains (e.getPosition()))
  6529. return;
  6530. bool rightEdge = false, leftEdge = false;
  6531. const auto hit = clipAt (e.x, e.y, rightEdge, leftEdge);
  6532. const auto tool = tools.getTool();
  6533. // hotfix 0.1.31.1: the Clip-launch Arrangement (Live) — a click on a clip or on a lane selects that track (the Device
  6534. // View follows; the hook is the main window's, which acts only while a Device View exists)
  6535. if (onArrangementTrackChosen && ! flmods::ctrl (e.mods))
  6536. chooseArrangementTrack (hit >= 0 ? engine.getSong().playlist[(std::size_t) hit].track : yToTrack (e.y));
  6537. // Performance mode (round 165m): while the song plays, a click on a clip of the performance zone launches it (the
  6538. // button's release is the release of the Hold modes) and a right-click stops its track; Ctrl / Alt edit as usual
  6539. if (const auto& song = engine.getSong(); hit >= 0 && song.mode == PlayMode::song && song.inPerformanceZone (song.playlist[(std::size_t) hit])
  6540. && engine.getTransport().playing.load() && ! flmods::ctrl (e.mods) && ! e.mods.isAltDown())
  6541. {
  6542. const auto& clip = song.playlist[(std::size_t) hit];
  6543. perf::Command c;
  6544. c.track = clip.track;
  6545. c.clipStart = clip.start;
  6546. c.type = flmods::popup (e.mods) ? perf::Command::Type::stopTrack : perf::Command::Type::press;
  6547. engine.performanceCommand (c);
  6548. if (c.type == perf::Command::Type::press)
  6549. {
  6550. drag = Drag::perfLaunch;
  6551. perfTrack = clip.track;
  6552. perfClip = clip.start;
  6553. }
  6554. return;
  6555. }
  6556. // Ctrl+right-click on empty space: zoom to show everything; again: back to the previous view
  6557. if (e.mods.isRightButtonDown() && flmods::ctrl (e.mods) && hit < 0)
  6558. {
  6559. if (zoomBeforeAll > 0.0)
  6560. {
  6561. pixelsPerTick = zoomBeforeAll;
  6562. scrollTicks = scrollBeforeAll;
  6563. zoomBeforeAll = 0.0;
  6564. updateScrollBars();
  6565. repaint();
  6566. }
  6567. else
  6568. {
  6569. zoomBeforeAll = pixelsPerTick;
  6570. scrollBeforeAll = scrollTicks;
  6571. zoomAll();
  6572. }
  6573. return;
  6574. }
  6575. // the menu button in a clip's title strip
  6576. if (hit >= 0 && e.mods.isLeftButtonDown() && ! flmods::ctrl (e.mods) && clipMenuButton (hit).contains (e.getPosition()))
  6577. {
  6578. showClipMenu (hit);
  6579. return;
  6580. }
  6581. // Zoom tool: right-click zooms out around the point (a click zooms in, a drag zooms to the range)
  6582. if (tool == EditTool::zoom && e.mods.isRightButtonDown() && ! e.mods.isAltDown())
  6583. {
  6584. zoomOut (e.x);
  6585. return;
  6586. }
  6587. // Alt+right-click on a clip: hear it while the button is held
  6588. if (e.mods.isRightButtonDown() && e.mods.isAltDown() && hit >= 0)
  6589. {
  6590. startPreview (hit, e.x);
  6591. return;
  6592. }
  6593. if (e.mods.isRightButtonDown() && hit >= 0 && gainHandle (hit).expanded (2.0f).contains (e.position))
  6594. {
  6595. showGainMenu (hit);
  6596. return;
  6597. }
  6598. // FL's fade handle menu (PLFadeHandleMenu, round 189i)
  6599. if (e.mods.isRightButtonDown() && hit >= 0)
  6600. if (const auto fade = fadeHandleAt (hit, e.getPosition()); fade != 0)
  6601. {
  6602. showFadeHandleMenu (hit, fade - 1);
  6603. return;
  6604. }
  6605. // FL 2026's tension handle menu (round 190jz)
  6606. if (e.mods.isRightButtonDown() && hit >= 0)
  6607. if (const auto side = fadeTensionAt (hit, e.getPosition()); side != 0)
  6608. {
  6609. fadeTensionMenu (hit, side - 1).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  6610. return;
  6611. }
  6612. if (e.mods.isRightButtonDown())
  6613. {
  6614. // round 165, FL's in-Playlist automation editing: right-click on a point = its menu, on a tension handle =
  6615. // straight segment, anywhere else in the curve's area = a new point there, dragged while the button is held
  6616. // (Shift: on the curve, keeping the level); the title strip (or a clip too small to edit) still deletes
  6617. if (const auto point = automationPointAt (hit, e.getPosition()); point >= 0)
  6618. {
  6619. showAutomationPointMenu (hit, point);
  6620. return;
  6621. }
  6622. if (const auto handle = automationHandleAt (hit, e.getPosition()); handle >= 0)
  6623. {
  6624. automationPointMemory().tension = 0.0f; // FL's "default tension" also clears the editor's memory
  6625. editCurve (hit, [handle] (std::vector<AutomationPoint>& points) { setAutomationSegmentTension (points, handle, 0.0f); });
  6626. return;
  6627. }
  6628. if (automationEditable (hit) && automationBody (engine.getSong().playlist[(std::size_t) hit]).contains (e.position))
  6629. {
  6630. const auto& c = engine.getSong().playlist[(std::size_t) hit];
  6631. AutomationPoint p;
  6632. p.tick = juce::jlimit<std::int64_t> (c.offset, c.offset + c.length, snap (xToTick (e.x), ! e.mods.isAltDown()) - c.start + c.offset);
  6633. const auto body = automationBody (c);
  6634. p.value = e.mods.isShiftDown() ? curveValueAt (hit, (double) p.tick)
  6635. : juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight()));
  6636. int added = -1;
  6637. // FL: the new point takes the mode and tension last used (round 190bw)
  6638. editCurve (hit, [p, &added, m = automationPointMemory()] (std::vector<AutomationPoint>& points) {
  6639. added = insertAutomationPoint (points, p, m.mode, m.tension);
  6640. });
  6641. setSelection ({});
  6642. drag = Drag::autoPoint;
  6643. autoClip = hit;
  6644. autoPoint = added;
  6645. return;
  6646. }
  6647. // on the clip menu icon (top left): the clip menu; anywhere else on a clip: delete, as in FL
  6648. // (press and hold on empty space: Knife). Round 190rw (Q1): in the Clip-launch layout (Live 12: a right-click on
  6649. // an Arrangement clip opens its context menu) and the Simple layout (BandLab: a region's context menu) the whole
  6650. // clip opens its menu (Delete is in it); FL's right-click delete stays in the Pattern layout
  6651. if (hit >= 0 && (clipMenuButton (hit).contains (e.getPosition()) || layoutstyle::current() != layoutstyle::Style::pattern))
  6652. {
  6653. showClipMenu (hit);
  6654. return;
  6655. }
  6656. // FL 2026 [SHOT, round 165z-b]: a double right-click is the Mute tool while the button stays down. The first
  6657. // click already deleted the clip under it and FL leaves it deleted; the sweep then mutes / unmutes every clip
  6658. // it crosses, the first one deciding which (issue #11)
  6659. const auto now = juce::Time::getMillisecondCounter();
  6660. const auto doubleRight = gesture::isDoubleClick (lastRightClickTime, now, lastRightClickPos.getDistanceFrom (e.getPosition()));
  6661. lastRightClickTime = doubleRight ? 0 : now;
  6662. lastRightClickPos = e.getPosition();
  6663. if (doubleRight)
  6664. {
  6665. drag = Drag::muting;
  6666. touchedClips.clear();
  6667. muteSweep = {};
  6668. bool r = false, l = false;
  6669. if (const auto clip = clipAt (e.x, e.y, r, l); clip >= 0)
  6670. {
  6671. touchedClips.push_back (clip);
  6672. const auto m = muteSweep.touch (engine.getSong().playlist[(std::size_t) clip].muted);
  6673. engine.editSong ([clip, m] (Song& s) { s.playlist[(std::size_t) clip].muted = m; });
  6674. }
  6675. return;
  6676. }
  6677. drag = Drag::erase;
  6678. startedOnEmpty = hit < 0;
  6679. setSelection ({}); // indices change while deleting
  6680. if (hit >= 0)
  6681. {
  6682. erasedSomething = true;
  6683. fadeOut ({ hit }); // (issue #250)
  6684. engine.editSong ([hit] (Song& s) { s.playlist.erase (s.playlist.begin() + hit); });
  6685. }
  6686. return;
  6687. }
  6688. // every tool: Ctrl+click on a clip adds/removes it from the selection; Ctrl+drag selects (Shift adds)
  6689. if (hit >= 0 && flmods::ctrl (e.mods))
  6690. {
  6691. auto s = selection;
  6692. if (isSelected (hit))
  6693. s.erase (std::find (s.begin(), s.end(), hit));
  6694. else
  6695. s.push_back (hit);
  6696. setSelection (s);
  6697. return;
  6698. }
  6699. if ((hit < 0 && flmods::ctrl (e.mods)) || tool == EditTool::lasso
  6700. || (hit < 0 && e.mods.isShiftDown() && tool != EditTool::brush))
  6701. {
  6702. drag = Drag::select;
  6703. dragClip = hit; // a Lasso click without dragging selects this clip
  6704. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  6705. rubberBand = {};
  6706. setSelection (selectionBefore);
  6707. return;
  6708. }
  6709. const auto snapOn = ! e.mods.isAltDown();
  6710. auto grabClips = [&] (Drag kind) {
  6711. if (! isSelected (hit))
  6712. setSelection ({});
  6713. const auto& playlist = engine.getSong().playlist;
  6714. dragClip = hit;
  6715. dragIndices = selection.empty() ? std::vector<int> { hit } : selection;
  6716. dragOriginals.clear();
  6717. for (auto i : dragIndices)
  6718. dragOriginals.push_back (playlist[(std::size_t) i]);
  6719. drag = kind;
  6720. grabOffset = playlist[(std::size_t) hit].start - snap (xToTick (e.x), snapOn);
  6721. };
  6722. switch (tool)
  6723. {
  6724. case EditTool::eraser:
  6725. drag = Drag::erase;
  6726. setSelection ({});
  6727. if (hit >= 0)
  6728. {
  6729. fadeOut ({ hit }); // (issue #250)
  6730. engine.editSong ([hit] (Song& s) { s.playlist.erase (s.playlist.begin() + hit); });
  6731. }
  6732. return;
  6733. case EditTool::mute:
  6734. drag = Drag::muting;
  6735. touchedClips.clear();
  6736. muteSweep = {};
  6737. if (hit >= 0)
  6738. {
  6739. touchedClips.push_back (hit);
  6740. const auto m = muteSweep.touch (engine.getSong().playlist[(std::size_t) hit].muted);
  6741. engine.editSong ([hit, m] (Song& s) { s.playlist[(std::size_t) hit].muted = m; });
  6742. }
  6743. else
  6744. {
  6745. muteSweep.touch (false); // the Mute tool started on empty space mutes
  6746. }
  6747. return;
  6748. case EditTool::knife:
  6749. drag = Drag::knife;
  6750. knifeFrom = knifeTo = e.getPosition();
  6751. repaint();
  6752. return;
  6753. case EditTool::zoom:
  6754. drag = Drag::zoomRange;
  6755. rubberBand = {};
  6756. return;
  6757. case EditTool::listen:
  6758. drag = Drag::listen;
  6759. seekTo (e.x, ! e.mods.isAltDown());
  6760. engine.play();
  6761. return;
  6762. case EditTool::slip:
  6763. if (hit >= 0)
  6764. grabClips (Drag::slip);
  6765. return;
  6766. case EditTool::pencil:
  6767. case EditTool::brush:
  6768. case EditTool::drumPaint:
  6769. case EditTool::lasso:
  6770. break;
  6771. }
  6772. // automation clip: drag a point, or click on the curve to add one (Pencil and Brush); round 165 (FL): Alt+click
  6773. // deletes a point, the hollow handle between two points bends the segment
  6774. if (hit >= 0 && ! e.mods.isShiftDown() && (tool == EditTool::pencil || tool == EditTool::brush))
  6775. {
  6776. auto point = automationPointAt (hit, e.getPosition());
  6777. if (const auto handle = point < 0 ? automationHandleAt (hit, e.getPosition()) : -1; handle >= 0)
  6778. {
  6779. const auto& points = *curveOf (hit).points;
  6780. setSelection ({});
  6781. drag = Drag::autoTension;
  6782. autoClip = hit;
  6783. autoPoint = handle;
  6784. automationPointMemory() = { points[(std::size_t) handle].mode < flcurve::modeCount ? (int) points[(std::size_t) handle].mode : 0,
  6785. points[(std::size_t) handle].tension };
  6786. tensionStart = points[(std::size_t) handle].tension;
  6787. // a positive tension lowers a rising segment's middle and raises a falling one's: the handle follows the mouse
  6788. tensionSign = points[(std::size_t) handle + 1].value >= points[(std::size_t) handle].value ? -1.0f : 1.0f;
  6789. return;
  6790. }
  6791. if (point < 0 && isOnAutomationCurve (hit, e.getPosition()))
  6792. {
  6793. const auto& c = engine.getSong().playlist[(std::size_t) hit];
  6794. AutomationPoint p;
  6795. p.tick = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) - c.start + c.offset);
  6796. const auto body = automationBody (c);
  6797. p.value = juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight()));
  6798. editCurve (hit, [p, m = automationPointMemory()] (std::vector<AutomationPoint>& points) { insertAutomationPoint (points, p, m.mode, m.tension); });
  6799. point = automationPointAt (hit, e.getPosition());
  6800. }
  6801. if (point >= 0)
  6802. {
  6803. setSelection ({});
  6804. drag = Drag::autoPoint;
  6805. autoClip = hit;
  6806. autoPoint = point;
  6807. return;
  6808. }
  6809. }
  6810. // warp marker flags (round 175a): drag a marker sideways; the change is applied on release. Round 190gi: Alt + drag
  6811. // near a marker's line anywhere on the clip's body does the same (FL's plain clip drag is unchanged)
  6812. if (hit >= 0)
  6813. if (const auto marker = e.mods.isAltDown() && e.mods.isLeftButtonDown() ? warpMarkerNear (hit, e.getPosition()) : warpMarkerAt (hit, e.getPosition()); marker > 0)
  6814. {
  6815. setSelection ({});
  6816. warpClip = hit;
  6817. warpIndex = marker;
  6818. warpBeat = clipWarpMarkers (hit)[(std::size_t) marker].beats;
  6819. drag = Drag::warpMarker;
  6820. return;
  6821. }
  6822. // round 190jr (BUILD-LIST 13): the Simple layout's loop handle: a drag right repeats the region
  6823. if (hit >= 0 && ! flmods::popup (e.mods) && regionLoopHandle (hit).expanded (2.0f).contains (e.position))
  6824. {
  6825. const auto run = regionloop::runOf (engine.getSong(), hit);
  6826. if (! run.empty())
  6827. {
  6828. setSelection ({});
  6829. const auto& region = engine.getSong().playlist[(std::size_t) run.clips.front()];
  6830. loopTrack = region.track;
  6831. loopStart = region.start;
  6832. loopLike = region;
  6833. drag = Drag::regionLoop;
  6834. postDragHint();
  6835. return;
  6836. }
  6837. }
  6838. // audio clip fade handles (drawn at the top corners of the body); FL's manual: Alt+click resets one (round 190jz)
  6839. if (hit >= 0)
  6840. if (const auto fade = fadeHandleAt (hit, e.getPosition()); fade != 0)
  6841. {
  6842. if (e.mods.isAltDown())
  6843. {
  6844. engine.editSong ([hit, side = fade - 1] (Song& s) {
  6845. auto& c = s.playlist[(std::size_t) hit];
  6846. (side == 0 ? c.fadeIn : c.fadeOut) = 0;
  6847. (side == 0 ? c.fadeInTension : c.fadeOutTension) = 0.0f;
  6848. });
  6849. repaint();
  6850. return;
  6851. }
  6852. setSelection ({});
  6853. dragClip = hit;
  6854. dragIndices = { hit };
  6855. drag = fade == 1 ? Drag::fadeIn : Drag::fadeOut;
  6856. crossPair = -1; // (round 190mr, DL-68: no crossfade drag-over yet)
  6857. postDragHint();
  6858. return;
  6859. }
  6860. // round 190jz (issue #194): a fade's tension handle, dragged up / down (FL 2026: up raises the curve's middle); Alt+click
  6861. // resets it, as FL's manual says
  6862. if (hit >= 0)
  6863. if (const auto side = fadeTensionAt (hit, e.getPosition()); side != 0)
  6864. {
  6865. const auto& c = engine.getSong().playlist[(std::size_t) hit];
  6866. if (e.mods.isAltDown())
  6867. {
  6868. engine.editSong ([hit, in = side == 1] (Song& s) { (in ? s.playlist[(std::size_t) hit].fadeInTension : s.playlist[(std::size_t) hit].fadeOutTension) = 0.0f; });
  6869. repaint();
  6870. return;
  6871. }
  6872. setSelection ({});
  6873. dragClip = hit;
  6874. dragIndices = { hit };
  6875. fadeSide = side - 1;
  6876. fadeTensionStart = clipops::fadeTensionHandle (side == 1 ? c.fadeInTension : c.fadeOutTension);
  6877. fadeTensionStartY = e.y;
  6878. drag = Drag::fadeTension;
  6879. postDragHint();
  6880. return;
  6881. }
  6882. // FL 2026's gain handle (round 166e): drag up / down; on a selected clip, every selected audio clip follows
  6883. if (hit >= 0 && gainHandle (hit).expanded (2.0f).contains (e.position))
  6884. {
  6885. const auto& song = engine.getSong();
  6886. dragClip = hit;
  6887. dragIndices.clear();
  6888. gainStartDb.clear();
  6889. for (auto i : isSelected (hit) ? selection : std::vector<int> { hit })
  6890. if (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio)
  6891. {
  6892. dragIndices.push_back (i);
  6893. gainStartDb.push_back (clipops::clipGainToDb (song.playlist[(std::size_t) i].gain));
  6894. }
  6895. gainStartY = e.y;
  6896. drag = Drag::clipGain;
  6897. postDragHint();
  6898. return;
  6899. }
  6900. // Alt+Shift+drag inside a clip: slip its content
  6901. if (hit >= 0 && e.mods.isAltDown() && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  6902. {
  6903. grabClips (Drag::slip);
  6904. return;
  6905. }
  6906. // Shift+drag on a clip body drags a copy (on an edge, Shift trims like a plain edge drag)
  6907. if (hit >= 0 && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  6908. {
  6909. const auto sources = isSelected (hit) ? selection : std::vector<int> { hit };
  6910. const auto grabbedAt = (std::size_t) (std::find (sources.begin(), sources.end(), hit) - sources.begin());
  6911. std::vector<Clip> copies;
  6912. std::vector<int> added;
  6913. for (auto i : sources)
  6914. copies.push_back (engine.getSong().playlist[(std::size_t) i]);
  6915. // Shift+V held: the copies get their own pattern / automation (FL's "make unique" while cloning)
  6916. const auto unique = juce::KeyPress::isKeyCurrentlyDown ('V') || juce::KeyPress::isKeyCurrentlyDown ('v');
  6917. // round 190ne (core/TrackClips.h): a copy of a track clip is unique by default; Shift+L+drag makes a linked one
  6918. const auto linked = juce::KeyPress::isKeyCurrentlyDown ('L') || juce::KeyPress::isKeyCurrentlyDown ('l');
  6919. engine.editSong ([&] (Song& s) {
  6920. for (const auto& c : copies)
  6921. {
  6922. added.push_back ((int) s.playlist.size());
  6923. s.playlist.push_back (c);
  6924. }
  6925. if (unique)
  6926. polish::makeClipsUnique (s, added);
  6927. else if (! linked)
  6928. trackclips::makeCopiesUnique (s, added);
  6929. });
  6930. for (std::size_t j = 0; j < added.size(); ++j) // (the copies' own patterns, when they got some)
  6931. copies[j] = engine.getSong().playlist[(std::size_t) added[j]];
  6932. setSelection (added);
  6933. dragIndices = added;
  6934. dragOriginals = copies;
  6935. dragCopies = true;
  6936. dragClip = added[grabbedAt];
  6937. drag = Drag::move;
  6938. grabOffset = copies[grabbedAt].start - snap (xToTick (e.x), snapOn);
  6939. return;
  6940. }
  6941. // a take lane's clip (round 177c): a drag on its body swipes that range to the comp, Logic's Quick Swipe with the normal
  6942. // tool; its title still moves it and its edges still resize. Never on an ordinary group: only lanes of a comp track.
  6943. // (comp::swipeStyle: which tools swipe on a drag)
  6944. if (hit >= 0 && ! rightEdge && ! leftEdge && ! flmods::ctrl (e.mods) && comp::dragSwipes (comp::swipeStyle, tool == EditTool::brush))
  6945. {
  6946. const auto& song = engine.getSong();
  6947. const auto& c = song.playlist[(std::size_t) hit];
  6948. const auto clipTop = (float) trackToY (c.track);
  6949. const auto title = clipHeaderHeight (juce::Rectangle<float> (0.0f, clipTop, 1.0f, (float) heightOf (c.track)));
  6950. if (c.kind == ClipKind::audio && comp::isComp (song, comp::groupOf (song, c.track).comp) && comp::groupOf (song, c.track).isLane (c.track)
  6951. && (float) e.y >= clipTop + title)
  6952. {
  6953. setSelection ({});
  6954. drag = Drag::swipe;
  6955. swipeLane = c.track;
  6956. swipeAnchor = swipeEnd = snap (xToTick (e.x) + (snapOn ? gridTicks() / 2.0 : 0.0), snapOn);
  6957. postDragHint();
  6958. return;
  6959. }
  6960. }
  6961. if (hit >= 0)
  6962. {
  6963. grabClips (rightEdge ? Drag::resize : leftEdge ? Drag::trimLeft : Drag::move);
  6964. stretchOriginals.clear();
  6965. if (EditorGlobals::get().stretchOnResize && (rightEdge || leftEdge))
  6966. stretchOriginals = engine.getSong().playlist;
  6967. if (drag == Drag::resize && ripple)
  6968. {
  6969. setSelection ({}); // a ripple resize works on the grabbed clip only
  6970. dragIndices = { hit };
  6971. dragOriginals = { engine.getSong().playlist[(std::size_t) hit] };
  6972. rippleOriginals = engine.getSong().playlist;
  6973. }
  6974. const auto& c = engine.getSong().playlist[(std::size_t) hit];
  6975. // issue #175 (FL): the Pencil and the Brush paint the clicked clip from now on, as it is (trimmed, stretched...)
  6976. if (tool == EditTool::pencil || tool == EditTool::brush)
  6977. brush = { c.kind, c.kind == ClipKind::audio ? c.channel : c.kind == ClipKind::automation ? c.automation : -1,
  6978. painttemplate::fromClicked (c) };
  6979. if (c.kind == ClipKind::pattern && c.pattern != engine.getSong().currentPattern)
  6980. engine.editSong ([p = c.pattern] (Song& s) { s.currentPattern = p; }, false);
  6981. if (onClipClicked) // (round 190qu: the Clip-launch Clip View shows it)
  6982. onClipClicked (hit);
  6983. return;
  6984. }
  6985. // round 190jq: the pointer-click switch (issue #191, LYNX extra; FL's Select tool on empty space: a click deselects, a
  6986. // drag draws a box; the release of a click moves the song position, as a click in Live's Arrangement), and an
  6987. // automation clip lane (#191.3), where nothing is placed (its own clips only)
  6988. if ((pointerclick::onEmpty (pointerclick::on, tool, e.getNumberOfClicks()) == pointerclick::EmptyPress::pointer && ! e.mods.isShiftDown())
  6989. || projection.isChild (yToTrack (e.y)))
  6990. {
  6991. drag = Drag::select;
  6992. dragClip = -1;
  6993. selectionBefore = {};
  6994. rubberBand = {};
  6995. setSelection ({});
  6996. pointerPress = true;
  6997. return;
  6998. }
  6999. placedByDoubleClick = e.getNumberOfClicks() > 1 && pointerclick::on;
  7000. // paints what is chosen in the Picker (the current pattern, an audio clip or an automation clip)
  7001. setSelection ({});
  7002. // round 190ne (core/TrackClips.h): on a track whose clips own their notes the pencil and the brush draw a NEW empty
  7003. // clip of the track (Live / Bitwig), one bar long or as long as the last one drawn or resized there
  7004. // (round 190qu, Discord 11-24: an instrument track in Track-only mode or the Simple layout too, whatever the brush holds)
  7005. if (const auto track = yToTrack (e.y); (brush.kind == ClipKind::pattern && trackclips::owns (engine.getSong(), track))
  7006. || trackclips::pencilMakesNewClip (engine.getSong(), track))
  7007. {
  7008. const auto at = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  7009. const auto length = lastTrackClipLength > 0 ? lastTrackClipLength : engine.getSong().barTicks();
  7010. Clip c;
  7011. engine.editSong ([&c, track, at, length] (Song& s) {
  7012. c.kind = ClipKind::pattern;
  7013. c.pattern = trackclips::newClip (s, track, length);
  7014. c.track = track;
  7015. c.start = at;
  7016. c.length = length;
  7017. s.playlist.push_back (c);
  7018. s.currentPattern = c.pattern;
  7019. s.mode = PlayMode::song; // someone arranging wants to hear the song
  7020. });
  7021. engine.setSelectedChannel (engine.getSong().playlistTracks[(std::size_t) track].channel); // its piano roll is the channel's
  7022. brush.index = -1;
  7023. brush.picked.reset();
  7024. dragClip = (int) engine.getSong().playlist.size() - 1;
  7025. dragIndices = { dragClip };
  7026. dragOriginals = { c };
  7027. grabOffset = 0;
  7028. if (tool == EditTool::brush)
  7029. {
  7030. drag = Drag::paint;
  7031. paintClip = c;
  7032. nextPaintTick = c.end();
  7033. return;
  7034. }
  7035. drag = Drag::move;
  7036. return;
  7037. }
  7038. // an instrument track places its own pattern (FL: named after the channel, made on the first click; round 151)
  7039. if (const auto track = yToTrack (e.y); brush.kind == ClipKind::pattern && track >= 0 && track < (int) engine.getSong().playlistTracks.size()
  7040. && engine.getSong().playlistTracks[(std::size_t) track].mode == PlaylistTrackMode::instrument)
  7041. {
  7042. engine.editSong ([track] (Song& s) {
  7043. if (const auto p = trackmodes::instrumentTrackPattern (s, track); p >= 0)
  7044. s.currentPattern = p;
  7045. });
  7046. engine.setSelectedChannel (engine.getSong().playlistTracks[(std::size_t) track].channel); // its piano roll is the channel's
  7047. }
  7048. auto c = makeBrushClip (yToTrack (e.y), snap (xToTick (e.x), snapOn));
  7049. if (c.kind == ClipKind::pattern) // (the current pattern; a clicked pattern clip stays the template, issue #175)
  7050. {
  7051. brush.kind = ClipKind::pattern;
  7052. brush.index = -1;
  7053. }
  7054. // a track locked to content places its own content (FL: the paint loop of FUN_00e5cd20 → FUN_01220fe0, round 168f)
  7055. pltracks::applyLockToContent (engine.getSong(), c);
  7056. engine.editSong ([c] (Song& s) {
  7057. s.playlist.push_back (c);
  7058. s.mode = PlayMode::song; // someone arranging wants to hear the song
  7059. });
  7060. dragClip = (int) engine.getSong().playlist.size() - 1;
  7061. dragIndices = { dragClip };
  7062. dragOriginals = { c };
  7063. grabOffset = 0;
  7064. if (tool == EditTool::brush)
  7065. {
  7066. drag = Drag::paint;
  7067. paintClip = c;
  7068. nextPaintTick = c.end();
  7069. return;
  7070. }
  7071. drag = Drag::move;
  7072. }
  7073. // round 190rw (Q1, ui/DragSongWatch.h) ------------------------------------------------------------------------------
  7074. void PlaylistComponent::noteDragIds()
  7075. {
  7076. const auto& playlist = engine.getSong().playlist;
  7077. const auto uidAt = [&playlist] (int i) { return i >= 0 && i < (int) playlist.size() ? playlist[(std::size_t) i].uid : std::uint64_t {}; };
  7078. dragUids.clear();
  7079. for (const auto i : dragIndices)
  7080. dragUids.push_back (uidAt (i));
  7081. dragUids.push_back (uidAt (dragClip));
  7082. dragUids.push_back (uidAt (crossPair));
  7083. }
  7084. bool PlaylistComponent::keepDragAfterSongSwap()
  7085. {
  7086. switch (drag)
  7087. {
  7088. // nothing of the song held: the view, a box, the song position
  7089. case Drag::none: case Drag::seek: case Drag::select: case Drag::zoomRange: case Drag::listen: case Drag::pan:
  7090. case Drag::trackZoom: case Drag::heightZoom: case Drag::timeZoom: case Drag::headerWidth: case Drag::preview:
  7091. case Drag::perfLaunch: case Drag::headerSelect:
  7092. return true;
  7093. // clips held by index: found again by uid (the indices follow a re-sorted playlist)
  7094. case Drag::move: case Drag::resize: case Drag::trimLeft: case Drag::slip: case Drag::fadeIn: case Drag::fadeOut:
  7095. case Drag::fadeTension: case Drag::clipGain: case Drag::paint: case Drag::erase: case Drag::muting: case Drag::knife:
  7096. break;
  7097. // tracks, markers, points, lanes, ranges held by index: ended
  7098. default:
  7099. return false;
  7100. }
  7101. if (dragUids.size() != dragIndices.size() + 2)
  7102. return false;
  7103. const auto& playlist = engine.getSong().playlist;
  7104. const auto find = [&playlist] (std::uint64_t uid) {
  7105. if (uid == 0)
  7106. return -1;
  7107. for (std::size_t i = 0; i < playlist.size(); ++i)
  7108. if (playlist[i].uid == uid)
  7109. return (int) i;
  7110. return -2; // gone
  7111. };
  7112. std::vector<int> indices;
  7113. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7114. {
  7115. const auto i = find (dragUids[j]);
  7116. if (i < 0)
  7117. return false; // a dragged clip was deleted (or had no id)
  7118. indices.push_back (i);
  7119. }
  7120. const auto clip = find (dragUids[dragIndices.size()]), pair = find (dragUids[dragIndices.size() + 1]);
  7121. if ((dragClip >= 0 && clip < 0) || (crossPair >= 0 && pair < 0))
  7122. return false;
  7123. dragIndices = std::move (indices);
  7124. if (dragClip >= 0)
  7125. dragClip = clip;
  7126. if (crossPair >= 0)
  7127. crossPair = pair;
  7128. std::vector<int> kept; // the selection: what is still there (it is drawn and copied by index)
  7129. for (const auto i : selection)
  7130. if (i >= 0 && i < (int) playlist.size())
  7131. kept.push_back (i);
  7132. if (kept.size() != selection.size())
  7133. setSelection (kept);
  7134. return true;
  7135. }
  7136. void PlaylistComponent::abandonDrag()
  7137. {
  7138. drag = Drag::none;
  7139. dragIndices.clear();
  7140. dragOriginals.clear();
  7141. dragUids.clear();
  7142. dragClip = -1;
  7143. crossPair = -1;
  7144. dragCopies = false;
  7145. rubberBand = {};
  7146. edgeScroller.stop();
  7147. edgeDragEvent.reset();
  7148. dragWatch.disarm();
  7149. dragAbandoned = true;
  7150. const auto& playlist = engine.getSong().playlist;
  7151. std::vector<int> kept;
  7152. for (const auto i : selection)
  7153. if (i >= 0 && i < (int) playlist.size())
  7154. kept.push_back (i);
  7155. setSelection (kept);
  7156. repaint();
  7157. }
  7158. bool PlaylistComponent::dragSurvivesSwap()
  7159. {
  7160. if (! dragWatch.foreign (engine))
  7161. return true;
  7162. if (keepDragAfterSongSwap())
  7163. {
  7164. dragWatch.mark (engine);
  7165. noteDragIds();
  7166. return true;
  7167. }
  7168. abandonDrag();
  7169. return false;
  7170. }
  7171. void PlaylistComponent::mouseDrag (const juce::MouseEvent& e)
  7172. {
  7173. if (touchInput.mouseDrag (e)) // round 190pm (P23)
  7174. return;
  7175. // round 190rw: the song changed under the drag (not by it): go on only with the same clips
  7176. if (dragAbandoned || ! dragSurvivesSwap())
  7177. return;
  7178. const struct MarkWatch
  7179. {
  7180. PlaylistComponent& p;
  7181. ~MarkWatch()
  7182. {
  7183. if (! p.dragAbandoned)
  7184. {
  7185. p.dragWatch.mark (p.engine);
  7186. p.noteDragIds();
  7187. }
  7188. }
  7189. } markWatch { *this };
  7190. if (insertsMouseDrag (e)) // issue #154: an effect dragged from a linked header's list
  7191. return;
  7192. // round 190qe (D2-PL1): past the arrangement's edge the view runs (feelFrame); the moved or resized clip and the brush
  7193. // stay at the edge meanwhile, as FL keeps them (round 190qc)
  7194. if (! edgeLayout && (edgeScrollsX() || edgeScrollsY()))
  7195. {
  7196. if (drag == Drag::move && dragOutToClipGrid (e)) // round 190ef: out over the Clip-launch grid (before the edge holds it)
  7197. return;
  7198. edgeDragEvent.emplace (e); // (the real pointer: the speed comes from how far past the edge it is)
  7199. frames.wake();
  7200. if (drag != Drag::select)
  7201. {
  7202. const auto grid = gridArea();
  7203. const auto x = edgeScrollsX() ? (float) edgescroll::clampInto (e.position.x, grid.getX(), grid.getRight()) : e.position.x;
  7204. const auto y = edgeScrollsY() ? (float) edgescroll::clampInto (e.position.y, grid.getY(), grid.getBottom()) : e.position.y;
  7205. if (x != e.position.x || y != e.position.y)
  7206. {
  7207. const juce::ScopedValueSetter<bool> layout (edgeLayout, true);
  7208. mouseDrag (e.withNewPosition (juce::Point<float> (x, y)));
  7209. return;
  7210. }
  7211. }
  7212. }
  7213. if (drag == Drag::range || drag == Drag::rangeMove) // round 190pa (P14)
  7214. {
  7215. rangeMouseDrag (e);
  7216. return;
  7217. }
  7218. if (drag == Drag::pen || drag == Drag::pointBand || drag == Drag::pointsMove) // issue #207 (round 190lw)
  7219. {
  7220. pointMouseDrag (e);
  7221. postDragHint();
  7222. return;
  7223. }
  7224. if (levelDrag != 0 && levelInsert > 0 && levelInsert < (int) engine.getSong().mixer.size())
  7225. {
  7226. // a Simple header's volume (along the bar) or pan (up / down, as a knob); Shift: fine
  7227. const auto fine = e.mods.isShiftDown() ? 0.2f : 1.0f;
  7228. const auto insert = levelInsert;
  7229. if (levelDrag == 1)
  7230. {
  7231. const auto v = juce::jlimit (0.0f, 1.0f, levelStart + fine * (float) e.getDistanceFromDragStartX() / (float) juce::jmax (40, levelWidth));
  7232. engine.editLevels ([insert, v] (Song& s) { s.mixer[(std::size_t) insert].volume = v; });
  7233. }
  7234. else
  7235. {
  7236. const auto v = juce::jlimit (-1.0f, 1.0f, levelStart - fine * (float) e.getDistanceFromDragStartY() / 80.0f);
  7237. engine.editLevels ([insert, v] (Song& s) { s.mixer[(std::size_t) insert].pan = v; });
  7238. }
  7239. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  7240. return;
  7241. }
  7242. if (drag == Drag::perfLaunch)
  7243. return; // (a launch: nothing moves)
  7244. if (drag == Drag::swipe)
  7245. {
  7246. const auto snapOn = ! e.mods.isAltDown();
  7247. swipeEnd = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? gridTicks() / 2.0 : 0.0), snapOn));
  7248. postDragHint();
  7249. repaint (0, trackToY (swipeLane), getWidth(), heightOf (swipeLane));
  7250. return;
  7251. }
  7252. if (drag == Drag::trackZoom)
  7253. {
  7254. setTrackZoom (trackZoomStart * std::pow (2.0, -e.getDistanceFromDragStartY() / 80.0), tracksTop());
  7255. return;
  7256. }
  7257. if (drag == Drag::heightZoom)
  7258. {
  7259. heightZoomDrag.move (e.y, flmods::ctrl (e.mods));
  7260. const auto height = heightZoomDrag.height (heightZoomStartHeight, 8, 640);
  7261. setTrackZoom (trackZoomStart * (double) height / (double) heightZoomStartHeight, heightZoomTrackY);
  7262. return;
  7263. }
  7264. if (drag == Drag::timeZoom)
  7265. {
  7266. const auto width = (double) juce::jmax (1, gridArea().getWidth());
  7267. timeZoomDrag.move (e.x, e.y, flmods::ctrl (e.mods));
  7268. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, width / timeZoomDrag.span);
  7269. scrollTicks = juce::jmax (0.0, timeZoomDrag.centre - width * 0.5 / pixelsPerTick);
  7270. zoomBeforeAll = 0.0;
  7271. updateScrollBars();
  7272. repaint();
  7273. ui::postHint ({ tr ("Zooming: drag up = closer, sideways = scroll [Ctrl] zoom only"), {}, false, false });
  7274. return;
  7275. }
  7276. if (drag == Drag::trackResize)
  7277. {
  7278. if (resizeTrack < 0)
  7279. return; // (ended by the group gesture: FL ignores the rest of the drag)
  7280. // the size shown, kept at 100% zoom (the vertical zoom scales every track); FL (AUTracksPanelMouseMove,
  7281. // round 190ft): a selected track resizes every selected track to the same height (FUN_012eda20)
  7282. auto height = trackhdr::draggedHeight ((int) std::lround (resizeStartHeight / trackZoom),
  7283. (int) std::lround (e.getDistanceFromDragStartY() / trackZoom));
  7284. std::vector<int> tracks;
  7285. auto rowTop = trackToY (resizeTrack);
  7286. const auto sel = sortedTrackSelection();
  7287. if (resizeAll)
  7288. for (int t = 0; t < numTracks(); ++t)
  7289. tracks.push_back (t);
  7290. else if (sel.size() > 1 && std::binary_search (sel.begin(), sel.end(), resizeTrack))
  7291. {
  7292. rowTop = trackToY (sel.front());
  7293. const auto shared = trackhdr::selectedHeight (sel, resizeTrack, rowTop, e.y);
  7294. tracks = sel;
  7295. if (shared > 0)
  7296. height = polish::evenTrackHeight ((int) std::lround (shared / trackZoom));
  7297. else
  7298. tracks.clear(); // (FL leaves the sizes alone below the smallest row)
  7299. }
  7300. else
  7301. tracks.push_back (resizeTrack);
  7302. // past the top of a row at its smallest: "Group with above track" flips, the size goes back to 100 % (FL)
  7303. if (! resizeAll && ! liveStyle && resizeTrack > 0 && trackhdr::groupGesture (height, e.y, rowTop))
  7304. {
  7305. auto targets = sel.size() > 1 && std::binary_search (sel.begin(), sel.end(), resizeTrack) ? sel : std::vector<int> { resizeTrack };
  7306. if (targets.size() == 1)
  7307. {
  7308. selectedTracks = targets;
  7309. currentTrack = resizeTrack;
  7310. }
  7311. const auto group = ! (resizeTrack < (int) engine.getSong().playlistTracks.size() && engine.getSong().playlistTracks[(std::size_t) resizeTrack].grouped);
  7312. engine.editSong ([targets, group] (Song& s) {
  7313. for (auto t : targets)
  7314. {
  7315. if (t <= 0)
  7316. continue;
  7317. if ((int) s.playlistTracks.size() <= t)
  7318. s.playlistTracks.resize ((std::size_t) t + 1);
  7319. s.playlistTracks[(std::size_t) t].height = 0;
  7320. if (group)
  7321. noteedit::groupWithAbove (s, t);
  7322. else
  7323. noteedit::ungroupTrack (s, t);
  7324. }
  7325. });
  7326. resizeTrack = -1;
  7327. refreshTrackLayout();
  7328. updateScrollBars();
  7329. repaint();
  7330. ui::postHint ({ group ? tr ("Group with above track") : tr ("Ungroup"), {}, false, false });
  7331. return;
  7332. }
  7333. if (! tracks.empty() && heightOf (resizeTrack) != scaledHeight (height))
  7334. setTrackHeights (tracks, height);
  7335. // FL's hint: the size in % of the default row
  7336. const auto percent = juce::roundToInt (polish::flSizeForHeight (height, baseRowHeight()) * 100.0f);
  7337. ui::postHint ({ resizeAll ? tr ("Resizing every track") : tr ("Resizing the track"),
  7338. juce::String (scaledHeight (height)) + " px (" + juce::String (percent) + "%)", false, false });
  7339. return;
  7340. }
  7341. if (drag == Drag::headerWidth) // round 190jq (issue #164)
  7342. {
  7343. const auto extra = headerwidth::dragged (headerWidthDragStart, e.getDistanceFromDragStartX(), headerBaseWidth, getWidth());
  7344. if (extra != headerwidth::extra)
  7345. {
  7346. headerwidth::extra = extra;
  7347. updateHeaderWidth();
  7348. }
  7349. ui::postHint ({ tr ("Track header width: [LMB] drag [2xLMB] FL's width"), juce::String (headerWidth) + " px", false, false });
  7350. return;
  7351. }
  7352. if (drag == Drag::headerMove) // round 190jf (B17)
  7353. {
  7354. const auto& song = engine.getSong();
  7355. auto row = yToTrack (e.y);
  7356. if (const auto owner = projection.ownerOf (row); owner >= 0) // (round 190jq: a lane moves with its owner)
  7357. row = owner;
  7358. const auto lower = e.y - trackToY (row) >= heightOf (row) / 2;
  7359. const auto drop = folderdrag::dropAt (song, headerMoveTrack, row, lower, e.x - headerMoveStartX, numTracks());
  7360. const auto moved = std::abs (e.getDistanceFromDragStartY()) > 3 || std::abs (e.getDistanceFromDragStartX()) >= folderdrag::stepPx;
  7361. const auto before = moved && folderdrag::changes (song, headerMoveTrack, drop) ? drop.before : -1;
  7362. if (before != headerMoveBefore || drop.depth != headerMoveDepth)
  7363. {
  7364. headerMoveBefore = before;
  7365. headerMoveDepth = drop.depth;
  7366. repaint();
  7367. }
  7368. ui::postHint ({ tr ("Moving the track with its group [Alt] drag right / left: deeper / out of a group"),
  7369. before < 0 ? juce::String() : (drop.depth > 0 ? tr ("In a group, level {0}", { juce::String (drop.depth) }) : tr ("Not in a group")),
  7370. false, false });
  7371. return;
  7372. }
  7373. if (drag == Drag::headerSelect)
  7374. {
  7375. // FL FUN_012e8740 on every move: the tracks from the press to the mouse are added (or removed); the range only grows
  7376. const auto track = yToTrack (e.y);
  7377. if (headerCtrlPending)
  7378. {
  7379. if (track == headerDragAnchor)
  7380. return; // (still a click: LYNX's toggle on release)
  7381. // the drag left the track: FL's Ctrl press now (the track alone with its clips), then FL's range
  7382. headerCtrlPending = false;
  7383. selectedTracks = { headerDragAnchor };
  7384. currentTrack = headerDragAnchor;
  7385. headerClipBase.clear();
  7386. selectClipsOnTracks (headerDragAnchor, headerDragAnchor, false);
  7387. followLinkedTrack (headerDragAnchor);
  7388. }
  7389. auto sel = sortedTrackSelection();
  7390. trackhdr::applyRange (sel, headerDragAnchor, track, headerDragAdding);
  7391. selectedTracks = sel;
  7392. if (selectedTracks.empty())
  7393. currentTrack = -1;
  7394. if (headerDragClips) // (the clip box from the header spans the song: the clips of the tracks crossed)
  7395. selectClipsOnTracks (headerDragAnchor, track, ! headerClipBase.empty());
  7396. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  7397. return;
  7398. }
  7399. if (drag == Drag::preview)
  7400. return;
  7401. const auto snapOn = ! e.mods.isAltDown();
  7402. // after the step below, the hint bar says what the gesture is doing
  7403. const struct PostAfter
  7404. {
  7405. PlaylistComponent& list;
  7406. ~PostAfter() { list.postDragHint(); }
  7407. } postAfter { *this };
  7408. switch (drag)
  7409. {
  7410. case Drag::none:
  7411. case Drag::trackResize:
  7412. case Drag::headerSelect:
  7413. case Drag::headerMove:
  7414. case Drag::headerWidth:
  7415. case Drag::trackZoom:
  7416. case Drag::heightZoom:
  7417. case Drag::timeZoom:
  7418. case Drag::preview:
  7419. return;
  7420. case Drag::pan:
  7421. scrollTicks = juce::jmax (0.0, panStartTicks - e.getDistanceFromDragStartX() / pixelsPerTick);
  7422. scrollY = juce::jmax (0, panStartY - e.getDistanceFromDragStartY());
  7423. updateScrollBars();
  7424. repaint();
  7425. return;
  7426. case Drag::laneDraw:
  7427. laneDrawTo (e);
  7428. return;
  7429. case Drag::lanePoint:
  7430. {
  7431. const auto a = laneAutomation (laneTrack, laneIndex);
  7432. if (a < 0)
  7433. return;
  7434. const auto& points = engine.getSong().automations[(std::size_t) a].points;
  7435. if (autoPoint < 0 || autoPoint >= (int) points.size())
  7436. return;
  7437. // between its neighbours; Shift pressed after the click keeps the time, Ctrl the value (as in clips)
  7438. auto tick = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  7439. const auto lo = autoPoint > 0 ? points[(std::size_t) autoPoint - 1].tick : 0;
  7440. const auto hi = autoPoint + 1 < (int) points.size() ? points[(std::size_t) autoPoint + 1].tick : std::numeric_limits<std::int64_t>::max();
  7441. tick = juce::jlimit (lo, hi, tick);
  7442. const auto body = laneBody (laneTrack, laneIndex);
  7443. auto value = laneValueOf (a, juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight())));
  7444. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  7445. tick = points[(std::size_t) autoPoint].tick;
  7446. if (flmods::ctrl (e.mods) && ! flmods::ctrl (downMods))
  7447. value = points[(std::size_t) autoPoint].value;
  7448. engine.editSong ([a, i = autoPoint, tick, value] (Song& s) {
  7449. auto& p = s.automations[(std::size_t) a].points[(std::size_t) i];
  7450. p.tick = tick;
  7451. p.value = value;
  7452. });
  7453. return;
  7454. }
  7455. case Drag::laneTension:
  7456. {
  7457. const auto a = laneAutomation (laneTrack, laneIndex);
  7458. if (a < 0 || autoPoint < 0 || autoPoint + 1 >= (int) engine.getSong().automations[(std::size_t) a].points.size())
  7459. return;
  7460. const auto range = juce::jmax (30.0f, laneBody (laneTrack, laneIndex).getHeight()) * (flmods::ctrl (e.mods) ? 4.0f : 1.0f);
  7461. const auto up = -(float) e.getDistanceFromDragStartY() / range;
  7462. const auto tension = juce::jlimit (-1.0f, 1.0f, tensionStart + tensionSign * up);
  7463. engine.editSong ([a, i = autoPoint, tension] (Song& s) { setAutomationSegmentTension (s.automations[(std::size_t) a].points, i, tension); });
  7464. return;
  7465. }
  7466. case Drag::autoPoint:
  7467. {
  7468. const auto& song = engine.getSong();
  7469. if (autoClip < 0 || autoClip >= (int) song.playlist.size())
  7470. return;
  7471. const auto& c = song.playlist[(std::size_t) autoClip];
  7472. const auto curve = curveOf (autoClip);
  7473. if (curve.points == nullptr)
  7474. return;
  7475. const auto& points = *curve.points;
  7476. if (autoPoint < 0 || autoPoint >= (int) points.size())
  7477. return;
  7478. // the point stays between its neighbours; Shift pressed after the click keeps the time, Ctrl the value
  7479. auto tick = snap (xToTick (e.x), snapOn) - c.start + c.offset;
  7480. const auto lo = autoPoint > 0 ? points[(std::size_t) autoPoint - 1].tick : 0;
  7481. const auto hi = autoPoint + 1 < (int) points.size() ? points[(std::size_t) autoPoint + 1].tick : std::numeric_limits<std::int64_t>::max();
  7482. tick = juce::jlimit (lo, hi, tick);
  7483. const auto body = automationBody (c);
  7484. auto value = juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight()));
  7485. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  7486. tick = points[(std::size_t) autoPoint].tick;
  7487. if (flmods::ctrl (e.mods) && ! flmods::ctrl (downMods))
  7488. value = points[(std::size_t) autoPoint].value;
  7489. editCurve (autoClip, [i = autoPoint, tick, value] (std::vector<AutomationPoint>& list) {
  7490. if (i < (int) list.size())
  7491. {
  7492. list[(std::size_t) i].tick = tick;
  7493. list[(std::size_t) i].value = value;
  7494. }
  7495. });
  7496. return;
  7497. }
  7498. case Drag::autoTension:
  7499. {
  7500. const auto& song = engine.getSong();
  7501. if (autoClip < 0 || autoClip >= (int) song.playlist.size())
  7502. return;
  7503. const auto curve = curveOf (autoClip);
  7504. if (curve.points == nullptr || autoPoint < 0 || autoPoint + 1 >= (int) curve.points->size())
  7505. return;
  7506. // the handle follows the mouse: a drag over the curve's height bends the segment fully (Ctrl: 4× finer)
  7507. const auto range = juce::jmax (30.0f, automationBody (song.playlist[(std::size_t) autoClip]).getHeight()) * (flmods::ctrl (e.mods) ? 4.0f : 1.0f);
  7508. const auto up = -(float) e.getDistanceFromDragStartY() / range;
  7509. const auto tension = juce::jlimit (-1.0f, 1.0f, tensionStart + tensionSign * up);
  7510. automationPointMemory().tension = tension; // (FL's editor memory: the next new point takes it)
  7511. editCurve (autoClip, [i = autoPoint, tension] (std::vector<AutomationPoint>& list) { setAutomationSegmentTension (list, i, tension); });
  7512. return;
  7513. }
  7514. case Drag::timeMove:
  7515. {
  7516. const auto here = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  7517. const auto delta = juce::jmax (-timeMoveFrom, here - timeMoveAnchor);
  7518. std::vector<int> moved;
  7519. engine.editSong ([&] (Song& s) {
  7520. s.playlist = timeMoveOriginals;
  7521. moved = noteedit::moveTimeRange (s.playlist, timeMoveFrom, timeMoveTo, delta, timeMoveCopy);
  7522. s.loopStart = timeMoveFrom + delta;
  7523. s.loopEnd = timeMoveTo + delta;
  7524. });
  7525. setSelection (moved);
  7526. return;
  7527. }
  7528. case Drag::timeShift: // FL: Shift+drag on the ruler moves the time selection (its length kept)
  7529. {
  7530. const auto here = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  7531. const auto r = ruler::moved (timeMoveFrom, timeMoveTo, here - timeMoveAnchor);
  7532. setTimeSelection (r.from, r.to);
  7533. return;
  7534. }
  7535. case Drag::seek:
  7536. case Drag::listen:
  7537. seekTo (e.x, snapOn);
  7538. if (drag == Drag::seek)
  7539. rulerMark = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  7540. return;
  7541. case Drag::marker: // (round 190ri: the tag follows the mouse once it has moved 3 px; the marker moves on release)
  7542. if (! markerDragMoved && std::abs (e.getDistanceFromDragStartX()) < 3)
  7543. return;
  7544. markerDragMoved = true;
  7545. markerDragTick = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  7546. repaint (0, rulerTop, getWidth(), timelineHeight);
  7547. return;
  7548. case Drag::tempoMarker: // (round 190hq: the tag follows the mouse; the marker moves on release)
  7549. tempoDragTick = juce::jmax<std::int64_t> (1, snap (xToTick (e.x), snapOn));
  7550. repaint (0, rulerTop, getWidth(), timelineHeight);
  7551. return;
  7552. case Drag::loop:
  7553. {
  7554. const auto here = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? gridTicks() / 2.0 : 0.0), snapOn));
  7555. setTimeSelection (juce::jmin (loopAnchor, here), juce::jmax (loopAnchor, here));
  7556. return;
  7557. }
  7558. case Drag::regionLoop:
  7559. regionLoopDragTo (e.x);
  7560. return;
  7561. case Drag::clipGain:
  7562. {
  7563. const auto delta = (gainStartY - e.y) * clipops::clipGainDbPerPixel;
  7564. std::vector<std::pair<int, float>> gains;
  7565. for (std::size_t k = 0; k < dragIndices.size(); ++k)
  7566. gains.push_back ({ dragIndices[k], clipops::clipGainFromDb (gainStartDb[k] + delta) });
  7567. engine.editSong ([gains] (Song& s) {
  7568. for (auto [i, g] : gains)
  7569. if (i < (int) s.playlist.size())
  7570. s.playlist[(std::size_t) i].gain = g;
  7571. });
  7572. postDragHint();
  7573. repaint();
  7574. return;
  7575. }
  7576. case Drag::warpMarker:
  7577. {
  7578. const auto markers = clipWarpMarkers (warpClip);
  7579. if (warpIndex <= 0 || warpIndex >= (int) markers.size())
  7580. return;
  7581. const auto& clip = engine.getSong().playlist[(std::size_t) warpClip];
  7582. const auto tick = snapOn ? (double) snap (xToTick (e.x) + gridTicks() / 2.0, true) : xToTick (e.x);
  7583. const auto beats = (tick - warpedit::clipTickOfBeat (clip, 0.0)) / (ppq * std::clamp (clip.stretch, 0.01, 100.0));
  7584. const auto lo = markers[(std::size_t) warpIndex - 1].beats + warpedit::minBeatGap;
  7585. const auto hi = warpIndex + 1 < (int) markers.size() ? markers[(std::size_t) warpIndex + 1].beats - warpedit::minBeatGap : 1.0e6;
  7586. warpBeat = juce::jlimit (lo, juce::jmax (lo, hi), beats);
  7587. postDragHint();
  7588. repaint();
  7589. return;
  7590. }
  7591. case Drag::fadeIn:
  7592. case Drag::fadeOut:
  7593. {
  7594. const auto& clip = engine.getSong().playlist[(std::size_t) dragClip];
  7595. // FL's Edit › "Snap fade handles" (off by default, EESnapFadeHandles): off, the handles move freely and Alt snaps
  7596. // them (FL 2026's hint "Hold Alt to snap", round 190jz); on, Alt lets them move freely
  7597. const auto snapFade = snapOn && (EditorGlobals::get().snapFadeHandles != e.mods.isAltDown());
  7598. const auto tick = snapFade ? snap (xToTick (e.x) + gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  7599. if (crossfadeDragOver (tick)) // round 190mr (DL-68): Live's crossfade by dragging over the neighbour's edge
  7600. {
  7601. postDragHint();
  7602. repaint();
  7603. return;
  7604. }
  7605. auto length = drag == Drag::fadeIn ? tick - clip.start : clip.end() - tick;
  7606. length = juce::jlimit<std::int64_t> (0, clip.length, length);
  7607. const auto in = drag == Drag::fadeIn;
  7608. if ((in ? clip.fadeIn : clip.fadeOut) == std::min (length, clip.length - (in ? clip.fadeOut : clip.fadeIn))
  7609. && clipops::manualFade (clip, in ? 0 : 1))
  7610. return;
  7611. // FL 2026 sets the side's manual bit when its handle is dragged (fade flags 0x1 in the saved file, round 190jz)
  7612. engine.editSong ([i = dragClip, length, in] (Song& s) {
  7613. auto& c = s.playlist[(std::size_t) i];
  7614. (in ? c.fadeIn : c.fadeOut) = std::min (length, c.length - (in ? c.fadeOut : c.fadeIn));
  7615. clipops::setManualFade (c, in ? 0 : 1, true);
  7616. });
  7617. postDragHint();
  7618. repaint();
  7619. return;
  7620. }
  7621. case Drag::fadeTension:
  7622. {
  7623. const auto v = juce::jlimit (-1.0, 1.0, fadeTensionStart + (fadeTensionStartY - e.y) * clipops::fadeTensionPerPixel);
  7624. const auto raw = clipops::fadeTensionFromHandle (v);
  7625. engine.editSong ([i = dragClip, in = fadeSide == 0, raw] (Song& s) {
  7626. if (i < (int) s.playlist.size())
  7627. (in ? s.playlist[(std::size_t) i].fadeInTension : s.playlist[(std::size_t) i].fadeOutTension) = raw;
  7628. });
  7629. postDragHint();
  7630. repaint();
  7631. return;
  7632. }
  7633. case Drag::select:
  7634. case Drag::zoomRange:
  7635. {
  7636. if (e.getDistanceFromDragStart() < 3 && rubberBand.isEmpty())
  7637. return;
  7638. const auto area = gridArea();
  7639. if (drag == Drag::zoomRange) // a time range over the whole height (also when dragged on the ruler)
  7640. {
  7641. const auto x0 = juce::jlimit (area.getX(), area.getRight(), juce::jmin (e.getMouseDownX(), e.x));
  7642. const auto x1 = juce::jlimit (area.getX(), area.getRight(), juce::jmax (e.getMouseDownX(), e.x));
  7643. rubberBand = juce::Rectangle<int>::leftTopRightBottom (x0, area.getY(), x1, area.getBottom());
  7644. repaint();
  7645. return;
  7646. }
  7647. // (round 190qe: the box's corner stays where it was pressed in the song while the view runs at an edge; the
  7648. // clips between it and the pointer are selected, also the ones scrolled out of view)
  7649. const juce::Point<int> corner ((int) juce::jlimit (-1.0e6, 1.0e6, std::round (tickToX (dragDownTick))), dragDownContentY - scrollY);
  7650. const auto box = juce::Rectangle<int> (corner, e.getPosition());
  7651. rubberBand = box.getIntersection (area);
  7652. const auto t0 = juce::jmin (dragDownTick, xToTick (e.x)), t1 = juce::jmax (dragDownTick, xToTick (e.x));
  7653. // (round 190jq: by drawn rows; the same as the tracks' order unless automation clips are drawn as lanes)
  7654. const auto tr0 = projection.row (yToTrack (box.getY())), tr1 = projection.row (yToTrack (box.getBottom()));
  7655. const auto& playlist = engine.getSong().playlist;
  7656. auto s = selectionBefore;
  7657. for (int i = 0; i < (int) playlist.size(); ++i)
  7658. {
  7659. const auto& c = playlist[(std::size_t) i];
  7660. if ((double) c.end() > t0 && (double) c.start < t1 && projection.row (c.track) >= tr0 && projection.row (c.track) <= tr1)
  7661. s.push_back (i);
  7662. }
  7663. setSelection (s);
  7664. return;
  7665. }
  7666. case Drag::erase:
  7667. {
  7668. // right press-and-hold on empty space, then drag: a temporary Knife
  7669. if (e.mods.isRightButtonDown() && startedOnEmpty && ! erasedSomething && ! holdExpired)
  7670. {
  7671. if (e.getLengthOfMousePress() >= 350)
  7672. {
  7673. drag = Drag::knife;
  7674. knifeFrom = e.getMouseDownPosition();
  7675. knifeTo = e.getPosition();
  7676. repaint();
  7677. return;
  7678. }
  7679. if (e.getDistanceFromDragStart() > 3)
  7680. holdExpired = true;
  7681. }
  7682. bool edge = false;
  7683. const auto hit = clipAt (e.x, e.y, edge);
  7684. if (hit >= 0)
  7685. {
  7686. erasedSomething = true;
  7687. fadeOut ({ hit }); // (issue #250)
  7688. engine.editSong ([hit] (Song& s) { s.playlist.erase (s.playlist.begin() + hit); });
  7689. }
  7690. return;
  7691. }
  7692. case Drag::muting:
  7693. {
  7694. bool edge = false;
  7695. const auto hit = clipAt (e.x, e.y, edge);
  7696. if (hit >= 0 && std::find (touchedClips.begin(), touchedClips.end(), hit) == touchedClips.end())
  7697. {
  7698. touchedClips.push_back (hit); // a double right-click started on empty space: the first clip decides
  7699. const auto m = muteSweep.touch (engine.getSong().playlist[(std::size_t) hit].muted);
  7700. engine.editSong ([hit, m] (Song& s) { s.playlist[(std::size_t) hit].muted = m; });
  7701. }
  7702. return;
  7703. }
  7704. case Drag::knife:
  7705. knifeTo = e.getPosition();
  7706. repaint();
  7707. return;
  7708. case Drag::paint:
  7709. {
  7710. // copies of the painted clip, end to end, on the track under the mouse
  7711. const auto tick = snap (xToTick (e.x), snapOn);
  7712. const auto length = juce::jmax<std::int64_t> (1, paintClip.length);
  7713. for (int guard = 0; tick >= nextPaintTick && guard < 64; ++guard)
  7714. {
  7715. auto c = paintClip;
  7716. c.start = nextPaintTick;
  7717. c.track = yToTrack (e.y);
  7718. nextPaintTick += length;
  7719. if (projection.isChild (c.track)) // (round 190jq: an automation clip lane takes no painted copies)
  7720. continue;
  7721. if (noteedit::paintWouldStack (engine.getSong().playlist, c))
  7722. continue; // (FL: no copy over a clip of the same source, round 169d)
  7723. engine.editSong ([c] (Song& s) {
  7724. s.playlist.push_back (c);
  7725. trackclips::makeCopiesUnique (s, std::vector<int> { (int) s.playlist.size() - 1 }); // (round 190ne: a track clip's copy is its own)
  7726. });
  7727. }
  7728. return;
  7729. }
  7730. case Drag::slip:
  7731. {
  7732. // the content moves by the (snapped) mouse movement; the clips stay put
  7733. const auto delta = snap (xToTick (e.x), snapOn) - snap (xToTick (e.getMouseDownX()), snapOn);
  7734. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  7735. auto probe = dragOriginals[grabbedAt];
  7736. noteedit::slip (probe, delta);
  7737. if (engine.getSong().playlist[(std::size_t) dragClip].offset == probe.offset)
  7738. return;
  7739. engine.editSong ([this, delta] (Song& s) {
  7740. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7741. {
  7742. auto c = dragOriginals[j];
  7743. noteedit::slip (c, delta);
  7744. s.playlist[(std::size_t) dragIndices[j]].offset = c.offset;
  7745. }
  7746. });
  7747. return;
  7748. }
  7749. case Drag::move:
  7750. {
  7751. if (dragOutToClipGrid (e)) // round 190ef
  7752. return;
  7753. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  7754. const auto& grabbed = dragOriginals[grabbedAt];
  7755. auto deltaTicks = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset) - grabbed.start;
  7756. auto deltaTracks = yToTrack (e.y) - grabbed.track;
  7757. // the group keeps its shape: clamp by the leftmost / topmost clip
  7758. for (const auto& c : dragOriginals)
  7759. {
  7760. deltaTicks = juce::jmax (deltaTicks, -c.start);
  7761. deltaTracks = juce::jlimit (-c.track, 499 - c.track, deltaTracks);
  7762. }
  7763. // round 190jq (#191.3): with automation clips drawn as lanes, a vertical move counts drawn rows; a lane's clips
  7764. // stay in their lane and no other clip lands in a lane (else the move keeps the tracks it had)
  7765. std::vector<int> movedTracks;
  7766. if (projection.any())
  7767. {
  7768. const auto rows = projection.row (yToTrack (e.y)) - projection.row (grabbed.track);
  7769. for (const auto& c : dragOriginals)
  7770. {
  7771. const auto to = cliplanes::movedTrack (projection, c.track, rows, numTracks());
  7772. if (to < 0 || to > 499)
  7773. {
  7774. movedTracks.clear();
  7775. break;
  7776. }
  7777. movedTracks.push_back (to);
  7778. }
  7779. if (movedTracks.empty())
  7780. for (const auto& c : dragOriginals)
  7781. movedTracks.push_back (c.track);
  7782. }
  7783. const auto trackOf = [&] (std::size_t j) { return movedTracks.empty() ? dragOriginals[j].track + deltaTracks : movedTracks[j]; };
  7784. const auto& current = engine.getSong().playlist[(std::size_t) dragClip];
  7785. if (current.start == grabbed.start + deltaTicks && current.track == trackOf (grabbedAt))
  7786. return;
  7787. engine.editSong ([this, deltaTicks, &trackOf] (Song& s) {
  7788. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7789. {
  7790. auto& c = s.playlist[(std::size_t) dragIndices[j]];
  7791. c.start = dragOriginals[j].start + deltaTicks;
  7792. c.track = trackOf (j);
  7793. }
  7794. });
  7795. return;
  7796. }
  7797. case Drag::resize:
  7798. {
  7799. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  7800. const auto& grabbed = dragOriginals[grabbedAt];
  7801. const auto minimum = snapOn ? juce::jmax<std::int64_t> (10, gridTicks()) : (std::int64_t) 10;
  7802. const auto end = snapOn ? snap (xToTick (e.x) + gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  7803. const auto delta = juce::jmax (minimum, end - grabbed.start) - grabbed.length;
  7804. if (engine.getSong().playlist[(std::size_t) dragClip].length == grabbed.length + delta)
  7805. return;
  7806. // the STRETCH switch (FL's ClipStretchBtn, round 168f): an audio clip's audio stretches with its edge
  7807. if (EditorGlobals::get().stretchOnResize && grabbed.kind == ClipKind::audio && ! stretchOriginals.empty())
  7808. {
  7809. engine.editSong ([this, delta, minimum] (Song& s) {
  7810. s.playlist = stretchOriginals;
  7811. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7812. if (const auto& o = dragOriginals[j]; o.kind == ClipKind::audio)
  7813. pltracks::stretchAudioClip (s, stretchOriginals, dragIndices[j], o.start, juce::jmax (minimum, o.length + delta),
  7814. EditorGlobals::get().createVariants);
  7815. });
  7816. return;
  7817. }
  7818. if (ripple && ! rippleOriginals.empty()) // the later clips on the track follow the end
  7819. {
  7820. engine.editSong ([this, length = juce::jmax (minimum, grabbed.length + delta)] (Song& s) {
  7821. s.playlist = rippleOriginals;
  7822. noteedit::rippleResize (s.playlist, dragClip, length);
  7823. });
  7824. return;
  7825. }
  7826. engine.editSong ([this, delta, minimum] (Song& s) {
  7827. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7828. {
  7829. auto& c = s.playlist[(std::size_t) dragIndices[j]];
  7830. c.length = juce::jmax (minimum, dragOriginals[j].length + delta);
  7831. c.fadeIn = juce::jmin (c.fadeIn, c.length);
  7832. c.fadeOut = juce::jmin (c.fadeOut, c.length - c.fadeIn);
  7833. }
  7834. });
  7835. return;
  7836. }
  7837. case Drag::trimLeft:
  7838. {
  7839. // the start moves, the content stays where it is (the offset follows)
  7840. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  7841. const auto& grabbed = dragOriginals[grabbedAt];
  7842. const auto minimum = snapOn ? juce::jmax<std::int64_t> (10, gridTicks()) : (std::int64_t) 10;
  7843. const auto start = snapOn ? snap (xToTick (e.x) + gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  7844. const auto delta = start - grabbed.start;
  7845. auto probe = grabbed;
  7846. noteedit::trimStart (probe, grabbed.start + delta, minimum);
  7847. if (engine.getSong().playlist[(std::size_t) dragClip].start == probe.start)
  7848. return;
  7849. if (EditorGlobals::get().stretchOnResize && grabbed.kind == ClipKind::audio && ! stretchOriginals.empty())
  7850. {
  7851. // stretching from the start: the end stays (round 168f)
  7852. engine.editSong ([this, delta, minimum] (Song& s) {
  7853. s.playlist = stretchOriginals;
  7854. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7855. if (const auto& o = dragOriginals[j]; o.kind == ClipKind::audio)
  7856. {
  7857. const auto newStart = juce::jlimit<std::int64_t> (0, o.end() - minimum, o.start + delta);
  7858. pltracks::stretchAudioClip (s, stretchOriginals, dragIndices[j], newStart, o.end() - newStart,
  7859. EditorGlobals::get().createVariants);
  7860. }
  7861. });
  7862. return;
  7863. }
  7864. engine.editSong ([this, delta, minimum] (Song& s) {
  7865. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  7866. {
  7867. auto c = dragOriginals[j];
  7868. noteedit::trimStart (c, c.start + delta, minimum);
  7869. s.playlist[(std::size_t) dragIndices[j]] = c;
  7870. }
  7871. });
  7872. return;
  7873. }
  7874. }
  7875. }
  7876. bool PlaylistComponent::makeDragHint (ui::Hint& hint)
  7877. {
  7878. if (makePointDragHint (hint)) // issue #207 (round 190lw)
  7879. return true;
  7880. const auto& song = engine.getSong();
  7881. const auto count = juce::String ((int) std::max<std::size_t> (1, dragIndices.size()));
  7882. auto position = [&song] (std::int64_t tick) {
  7883. const auto bar = song.barAt (juce::jmax<std::int64_t> (0, tick));
  7884. const auto beat = (tick - bar.tick) / ppq + 1;
  7885. return juce::String (bar.number) + ":" + juce::String (beat);
  7886. };
  7887. const auto clip = dragClip >= 0 && dragClip < (int) song.playlist.size() ? &song.playlist[(std::size_t) dragClip] : nullptr;
  7888. switch (drag)
  7889. {
  7890. case Drag::move:
  7891. if (clip == nullptr)
  7892. return false;
  7893. hint.text = tr ("Moving {0} clip(s) [Alt] no snap", { count });
  7894. hint.value = position (clip->start) + " " + tr ("Track {0}", { juce::String (clip->track + 1) });
  7895. break;
  7896. case Drag::resize:
  7897. case Drag::trimLeft:
  7898. if (clip == nullptr)
  7899. return false;
  7900. hint.text = tr ("Resizing {0} clip(s) [Alt] no snap", { count });
  7901. hint.value = position (drag == Drag::resize ? clip->end() : clip->start);
  7902. break;
  7903. case Drag::regionLoop: // round 190jr
  7904. if (const auto region = regionloop::regionAt (song, loopTrack, loopStart, loopLike); region >= 0)
  7905. {
  7906. const auto run = regionloop::runOf (song, region);
  7907. hint.text = tr ("Looping the region: drag right to repeat it [Alt] no snap");
  7908. hint.value = tr ("{0} passes", { juce::String ((double) (run.end - run.start) / (double) juce::jmax<std::int64_t> (1, run.pass), 2) })
  7909. + " " + position (run.end);
  7910. }
  7911. break;
  7912. case Drag::slip: hint.text = tr ("Sliding the content inside the clip [Alt] no snap"); break;
  7913. case Drag::swipe: hint.text = tr ("Swiping this range to the comp [Alt] no snap"); break;
  7914. case Drag::clipGain:
  7915. if (clip == nullptr)
  7916. return false;
  7917. hint.text = tr ("Clip gain: drag up / down ({0} clip(s))", { count });
  7918. hint.value = tr ("Gain: {0}", { gainText (clip->gain) });
  7919. break;
  7920. case Drag::fadeIn:
  7921. case Drag::fadeOut: // round 190jz: FL 2026's hint while a fade handle moves ("Fade out: 0'00.112'' Hold Alt to snap")
  7922. if (clip == nullptr)
  7923. return false;
  7924. hint.text = (drag == Drag::fadeIn ? tr ("Fade in: {0}", { fadeLengthText (clip->effectiveFadeIn()) })
  7925. : tr ("Fade out: {0}", { fadeLengthText (clip->effectiveFadeOut()) }))
  7926. + " " + (EditorGlobals::get().snapFadeHandles ? tr ("Hold Alt for no snap") : tr ("Hold Alt to snap"));
  7927. break;
  7928. case Drag::fadeTension: // FL 2026: "Tension: 15%"
  7929. if (clip == nullptr)
  7930. return false;
  7931. hint.text = tr ("Tension: {0}%", { juce::String (juce::roundToInt (clipops::fadeTensionHandle (fadeSide == 0 ? clip->fadeInTension : clip->fadeOutTension) * 100.0)) });
  7932. break;
  7933. case Drag::warpMarker: hint.text = tr ("Moving the warp marker: the audio around it stretches [Alt] no snap"); break;
  7934. case Drag::marker:
  7935. if (! markerDragMoved)
  7936. break;
  7937. hint.text = tr ("Moving the marker [Alt] no snap");
  7938. hint.value = position (markerDragTick);
  7939. break;
  7940. case Drag::tempoMarker:
  7941. hint.text = tr ("Moving the tempo change [Alt] no snap");
  7942. hint.value = position (tempoDragTick);
  7943. break;
  7944. case Drag::autoPoint:
  7945. hint.text = tr ("Moving the point: then [Shift] keeps time [Ctrl] keeps value");
  7946. // round 190im (DE-117): an automation clip's point too (its curve has no envelope lane: lane 0), as FL's manual
  7947. // says ("Control point and tension handle values appear in the hint bar when they are moved"); with its
  7948. // place in the song, as the automation lanes show it
  7949. if (const auto curve = curveOf (autoClip); curve.points != nullptr && autoPoint >= 0 && autoPoint < (int) curve.points->size())
  7950. {
  7951. const auto& owner = song.playlist[(std::size_t) autoClip]; // (curveOf: a valid clip)
  7952. const auto& point = (*curve.points)[(std::size_t) autoPoint];
  7953. hint.value = curveValueText (autoClip, point.value) + " " + position (owner.start + point.tick - owner.offset);
  7954. }
  7955. break;
  7956. case Drag::autoTension:
  7957. hint.text = tr ("Bending the segment: drag up / down [Ctrl] fine");
  7958. if (const auto curve = curveOf (autoClip); curve.points != nullptr && autoPoint >= 0 && autoPoint + 1 < (int) curve.points->size())
  7959. hint.value = tensionText ((*curve.points)[(std::size_t) autoPoint].tension); // (DE-118)
  7960. break;
  7961. case Drag::laneDraw:
  7962. hint.text = drawFreehand ? tr ("Draw Mode: drawing freehand") : tr ("Draw Mode: drawing steps at the grid width [Alt] freehand");
  7963. break;
  7964. case Drag::lanePoint:
  7965. case Drag::laneTension:
  7966. {
  7967. const auto a = laneAutomation (laneTrack, laneIndex);
  7968. if (a < 0 || autoPoint < 0 || autoPoint >= (int) song.automations[(std::size_t) a].points.size())
  7969. return false;
  7970. const auto& automation = song.automations[(std::size_t) a];
  7971. hint.text = drag == Drag::lanePoint ? tr ("Moving the point: then [Shift] keeps time [Ctrl] keeps value")
  7972. : tr ("Bending the segment: drag up / down [Ctrl] fine");
  7973. if (drag == Drag::laneTension && autoPoint + 1 < (int) automation.points.size()) // (round 190im, DE-118: the segment's tension)
  7974. hint.value = tensionText (automation.points[(std::size_t) autoPoint].tension);
  7975. else
  7976. hint.value = automationPointValueText (automation.target, automation.points[(std::size_t) autoPoint].value) + " "
  7977. + position (automation.points[(std::size_t) autoPoint].tick);
  7978. break;
  7979. }
  7980. case Drag::select:
  7981. hint.text = tr ("Selecting [Shift] adds to the selection");
  7982. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  7983. break;
  7984. case Drag::loop:
  7985. hint.text = tr ("Time selection [Alt] no snap");
  7986. hint.value = position (song.loopStart) + " - " + position (song.loopEnd);
  7987. break;
  7988. case Drag::erase: hint.text = tr ("Deleting what the mouse crosses"); break;
  7989. case Drag::muting: hint.text = tr ("Muting / unmuting what the mouse crosses"); break;
  7990. case Drag::knife: hint.text = tr ("Cutting along the line [Alt] no snap"); break;
  7991. case Drag::paint: hint.text = tr ("Painting clips [Alt] no snap"); break;
  7992. case Drag::timeMove: hint.text = tr ("Moving the time selection with its clips [Alt] no snap"); break;
  7993. case Drag::timeShift:
  7994. hint.text = tr ("Moving the time selection [Alt] no snap");
  7995. hint.value = position (song.loopStart) + " - " + position (song.loopEnd);
  7996. break;
  7997. case Drag::seek:
  7998. hint.text = tr ("Song position [Alt] no snap");
  7999. hint.value = position ((std::int64_t) playheadTick);
  8000. break;
  8001. case Drag::listen:
  8002. case Drag::pan:
  8003. case Drag::zoomRange:
  8004. case Drag::trackResize:
  8005. case Drag::headerSelect:
  8006. case Drag::headerMove:
  8007. case Drag::headerWidth:
  8008. case Drag::trackZoom:
  8009. case Drag::heightZoom:
  8010. case Drag::timeZoom:
  8011. case Drag::preview:
  8012. case Drag::none: return false;
  8013. }
  8014. return true;
  8015. }
  8016. void PlaylistComponent::postDragHint()
  8017. {
  8018. if (ui::Hint hint; makeDragHint (hint))
  8019. ui::postHint (hint);
  8020. }
  8021. ui::Hint PlaylistComponent::dragHintForSnapshot (int clip, int point, bool tension)
  8022. {
  8023. const auto was = drag;
  8024. drag = tension ? Drag::autoTension : Drag::autoPoint;
  8025. autoClip = clip;
  8026. autoPoint = point;
  8027. ui::Hint hint;
  8028. makeDragHint (hint);
  8029. drag = was;
  8030. return hint;
  8031. }
  8032. void PlaylistComponent::hoverFadeForSnapshot (int index, int target)
  8033. {
  8034. // (--issueshot190jz) the clip hovered as the mouse would hover it, `target` drawn as hovered (-1: nothing hovered)
  8035. hover = {};
  8036. if (index >= 0 && index < (int) engine.getSong().playlist.size())
  8037. {
  8038. hover.clip = index;
  8039. hover.track = engine.getSong().playlist[(std::size_t) index].track;
  8040. hover.target = target == 1 || target == 2 ? gesture::Target::fadeHandle : target >= 3 ? gesture::Target::fadeTension : gesture::Target::item;
  8041. hover.fade = juce::jmax (0, target);
  8042. }
  8043. repaint();
  8044. }
  8045. ui::Hint PlaylistComponent::fadeDragHintForSnapshot (int index, int target)
  8046. {
  8047. const auto was = drag;
  8048. const auto wasClip = dragClip;
  8049. drag = target == 1 ? Drag::fadeIn : target == 2 ? Drag::fadeOut : Drag::fadeTension;
  8050. dragClip = index;
  8051. fadeSide = target == 4 ? 1 : 0;
  8052. ui::Hint hint;
  8053. makeDragHint (hint);
  8054. drag = was;
  8055. dragClip = wasClip;
  8056. return hint;
  8057. }
  8058. void PlaylistComponent::mouseUp (const juce::MouseEvent& e)
  8059. {
  8060. if (touchInput.mouseUp (e)) // round 190pm (P23)
  8061. return;
  8062. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::end); // (closes when mouseUp returns)
  8063. // round 190rw: a drag the song changed under (see mouseDrag) ends here with no write
  8064. if (dragAbandoned || ! dragSurvivesSwap())
  8065. {
  8066. dragAbandoned = false;
  8067. dragWatch.disarm();
  8068. return;
  8069. }
  8070. dragWatch.disarm();
  8071. // round 190qe: the release ends the edge scroll; a click that replaced or cleared the selection leaves the old one
  8072. // for "Restore selection" (D2-PL9), once the release is done
  8073. edgeScroller.stop();
  8074. edgeDragEvent.reset();
  8075. struct RememberSelection
  8076. {
  8077. PlaylistComponent& p;
  8078. ~RememberSelection()
  8079. {
  8080. if (p.engine.getPublishCount() == p.followEditStamp) // (a click that only selected: an edit keeps its selection)
  8081. p.selectionHistory.changed (p.selectionAtPress, p.clipKeys (p.selection));
  8082. }
  8083. } const rememberSelection { *this };
  8084. // round 190im (R15): a gesture that changed the song is an edit by hand: Follow pauses (when that option is on)
  8085. EditorGlobals::get().pauseFollowIfEdited (EditorGlobals::FollowView::playlist, followEditStamp, engine.getPublishCount());
  8086. if (insertsMouseUp (e)) // issue #154: a click or a drag in a linked header's effects list
  8087. {
  8088. drag = Drag::none;
  8089. return;
  8090. }
  8091. if (drag == Drag::range || drag == Drag::rangeMove) // round 190pa (P14)
  8092. {
  8093. rangeMouseUp (e);
  8094. drag = Drag::none;
  8095. return;
  8096. }
  8097. if (drag == Drag::pen || drag == Drag::pointBand || drag == Drag::pointsMove) // issue #207 (round 190lw)
  8098. {
  8099. pointMouseUp (e);
  8100. ui::clearPostedHint();
  8101. updateHover (e.getPosition(), e.mods);
  8102. return;
  8103. }
  8104. if (drag == Drag::headerWidth) // round 190jq (issue #164): the width is a preference (ui-options.txt), saved now
  8105. {
  8106. drag = Drag::none;
  8107. if (onViewOptionChanged)
  8108. onViewOptionChanged();
  8109. updateCursor (e.mods);
  8110. return;
  8111. }
  8112. // round 190jq (issue #191): a pointer click that was not dragged moves the song position (FL's Select tool clears the
  8113. // selection on the press; Live's Arrangement moves the position)
  8114. if (drag == Drag::select && pointerPress && e.getDistanceFromDragStart() < 3)
  8115. {
  8116. seekTo (e.getMouseDownX(), ! e.mods.isAltDown());
  8117. // round 190mk (DL-70): Live's insert marker on the clicked lane
  8118. if (liveArrangeLook())
  8119. setInsertMark (yToTrack (e.getMouseDownY()), (std::int64_t) std::llround (juce::jmax (0.0, ! e.mods.isAltDown() ? (double) snapLine (xToTick (e.getMouseDownX())) : xToTick (e.getMouseDownX()))));
  8120. }
  8121. // round 190mk (DL-70): Live's Arrangement — a click (no drag) of the Select tool on an empty spot of a lane sets the
  8122. // insert marker there, and the song position with it (Live: playback starts at the insert marker)
  8123. else if (drag == Drag::select && ! pointerPress && dragClip < 0 && selectionBefore.empty() && liveArrangeLook()
  8124. && e.getDistanceFromDragStart() < 3 && ! e.mods.isShiftDown() && ! flmods::ctrl (e.mods) && tools.getTool() == EditTool::lasso
  8125. && gridArea().contains (e.getMouseDownPosition()) && ! projection.isChild (yToTrack (e.getMouseDownY())))
  8126. {
  8127. seekTo (e.getMouseDownX(), ! e.mods.isAltDown());
  8128. setInsertMark (yToTrack (e.getMouseDownY()), (std::int64_t) std::llround (juce::jmax (0.0, ! e.mods.isAltDown() ? (double) snapLine (xToTick (e.getMouseDownX())) : xToTick (e.getMouseDownX()))));
  8129. }
  8130. pointerPress = false;
  8131. if (drag == Drag::headerSelect && headerCtrlPending)
  8132. {
  8133. // LYNX extra (issue #163; FL has no Ctrl+click toggle): Ctrl+click adds / removes the track, its clips follow
  8134. headerCtrlPending = false;
  8135. drag = Drag::none;
  8136. const auto track = headerDragAnchor;
  8137. auto sel = sortedTrackSelection();
  8138. trackhdr::applySelection (sel, track, trackhdr::SelMode::toggle);
  8139. selectedTracks = sel;
  8140. const auto nowSelected = std::binary_search (sel.begin(), sel.end(), track);
  8141. currentTrack = sel.empty() ? -1 : (nowSelected ? track : sel.back());
  8142. std::vector<int> clipTracks;
  8143. for (const auto& c : engine.getSong().playlist)
  8144. clipTracks.push_back (c.gridSlot >= 0 ? -1 : c.track);
  8145. auto clips = selection;
  8146. trackhdr::toggleTrackClips (clips, clipTracks, track, nowSelected);
  8147. setSelection (clips);
  8148. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  8149. return;
  8150. }
  8151. headerCtrlPending = false;
  8152. if (drag == Drag::headerMove) // round 190jf (B17): the move, one undo step
  8153. {
  8154. drag = Drag::none;
  8155. const auto track = headerMoveTrack, before = headerMoveBefore, depth = headerMoveDepth;
  8156. headerMoveTrack = headerMoveBefore = -1;
  8157. if (before >= 0)
  8158. {
  8159. int at = -1;
  8160. engine.editSong ([track, before, depth, &at] (Song& s) { at = noteedit::moveFolder (s, track, before, depth); });
  8161. if (at >= 0)
  8162. {
  8163. selectedTracks = { at };
  8164. currentTrack = at;
  8165. }
  8166. refreshTrackLayout();
  8167. updateScrollBars();
  8168. }
  8169. repaint();
  8170. return;
  8171. }
  8172. if (drag == Drag::swipe)
  8173. {
  8174. drag = Drag::none;
  8175. if (const auto from = juce::jmin (swipeAnchor, swipeEnd), to = juce::jmax (swipeAnchor, swipeEnd); to > from)
  8176. {
  8177. engine.editSong ([lane = swipeLane, from, to] (Song& s) { comp::swipe (s, lane, from, to); });
  8178. sortClips();
  8179. }
  8180. swipeLane = -1;
  8181. repaint();
  8182. return;
  8183. }
  8184. ui::clearPostedHint();
  8185. if (levelDrag != 0)
  8186. {
  8187. levelDrag = 0;
  8188. levelInsert = -1;
  8189. return;
  8190. }
  8191. if (drag == Drag::perfLaunch)
  8192. {
  8193. perf::Command c;
  8194. c.type = perf::Command::Type::release;
  8195. c.track = perfTrack;
  8196. c.clipStart = perfClip;
  8197. engine.performanceCommand (c);
  8198. drag = Drag::none;
  8199. perfTrack = -1;
  8200. return;
  8201. }
  8202. if (drag == Drag::marker)
  8203. {
  8204. drag = Drag::none;
  8205. const auto& song = engine.getSong();
  8206. if (markerDragIndex >= 0 && markerDragIndex < (int) song.markers().size())
  8207. {
  8208. if (markerDragMoved)
  8209. {
  8210. if (song.markers()[(std::size_t) markerDragIndex].tick != markerDragTick)
  8211. engine.editSong ([i = markerDragIndex, t = markerDragTick] (Song& s) {
  8212. if (i >= (int) s.markers().size())
  8213. return;
  8214. auto m = s.markers()[(std::size_t) i];
  8215. s.markers().erase (s.markers().begin() + i);
  8216. m.tick = t;
  8217. s.addMarker (m);
  8218. });
  8219. }
  8220. else
  8221. {
  8222. // a click on a marker's tag goes to the marker (LYNX), quantized while playing like any song jump
  8223. const auto markerTick = song.markers()[(std::size_t) markerDragIndex].tick;
  8224. const auto waits = engine.getTransport().playing.load() && engine.quantizeSongJumps.load() > 0;
  8225. engine.jumpToMarker (markerDragIndex);
  8226. if (! waits)
  8227. playheadTick = (double) markerTick;
  8228. }
  8229. }
  8230. markerDragIndex = -1;
  8231. repaint();
  8232. return;
  8233. }
  8234. if (drag == Drag::tempoMarker)
  8235. {
  8236. drag = Drag::none;
  8237. const auto marks = tempomarkers::list (engine.getSong());
  8238. if (tempoDragMarker >= 0 && tempoDragMarker < (int) marks.size() && marks[(std::size_t) tempoDragMarker].tick != tempoDragTick)
  8239. engine.editSong ([m = tempoDragMarker, t = tempoDragTick] (Song& s) { tempomarkers::move (s, m, t); });
  8240. tempoDragMarker = -1;
  8241. repaint();
  8242. return;
  8243. }
  8244. if (drag == Drag::warpMarker)
  8245. {
  8246. // one undoable edit: the clip gets its own copy of the channel if others share it (warpedit), then the marker
  8247. // moves (in the beats the channel plays, so the markers are rewritten as played first)
  8248. const auto seconds = clipFileSeconds (warpClip);
  8249. const auto markers = clipWarpMarkers (warpClip);
  8250. if (seconds > 0.0 && warpIndex > 0 && warpIndex < (int) markers.size() && std::abs (markers[(std::size_t) warpIndex].beats - warpBeat) > 1.0e-9)
  8251. engine.editSong ([clip = warpClip, index = warpIndex, beats = warpBeat, seconds] (Song& s) {
  8252. const auto channel = warpedit::channelForClipEdit (s, clip);
  8253. if (channel < 0)
  8254. return;
  8255. auto& sampler = s.channels[(std::size_t) channel].sampler;
  8256. sampler.warp = warpedit::editableMarkers (sampler, seconds);
  8257. warpedit::moveMarker (sampler, index, beats, seconds);
  8258. });
  8259. drag = Drag::none;
  8260. warpClip = warpIndex = -1;
  8261. repaint();
  8262. return;
  8263. }
  8264. if (drag == Drag::knife)
  8265. cutWithKnife (knifeFrom, knifeTo, ! e.mods.isAltDown());
  8266. if (drag == Drag::zoomRange)
  8267. {
  8268. if (rubberBand.getWidth() > 4)
  8269. zoomToTicks (xToTick (rubberBand.getX()), xToTick (rubberBand.getRight()));
  8270. else
  8271. zoomIn (e.x); // a click zooms in around the point (right-click zooms out)
  8272. }
  8273. if (drag == Drag::select && rubberBand.isEmpty() && dragClip >= 0)
  8274. {
  8275. auto s = selectionBefore;
  8276. if (auto it = std::find (s.begin(), s.end(), dragClip); it != s.end())
  8277. s.erase (it);
  8278. else
  8279. s.push_back (dragClip);
  8280. setSelection (s);
  8281. }
  8282. // Ctrl+click on the ruler without dragging clears the time selection (and so does a double click); a right click
  8283. // in place keeps what it did (FL: moved the nearer edge) and, with no selection, opens LYNX's ruler menu
  8284. // (FL 2026, round 190mq: the double click also deselects the clips and drops the paste anchor, issue #213)
  8285. if (drag == Drag::loop && e.getDistanceFromDragStart() < 3 && ! flmods::of (downMods).right)
  8286. {
  8287. setTimeSelection (0, 0);
  8288. rulerMark = -1;
  8289. if (! flmods::of (downMods).shift)
  8290. setSelection ({});
  8291. }
  8292. else if (drag == Drag::loop && rulerMenuOnClick && ruler::isClick (e.getDistanceFromDragStartX(), e.getDistanceFromDragStartY()))
  8293. {
  8294. rulerMenuOnClick = false;
  8295. showRulerMenu (e.getMouseDownX(), e.getMouseDownY());
  8296. }
  8297. else if (drag == Drag::loop && rulerDoubleDrag && engine.getSong().hasLoop())
  8298. {
  8299. const auto start = (double) engine.getSong().loopStart;
  8300. const auto waits = engine.getTransport().playing.load() && engine.quantizeSongJumps.load() > 0;
  8301. engine.jumpTo (start);
  8302. if (! waits)
  8303. playheadTick = start;
  8304. }
  8305. rulerDoubleDrag = false;
  8306. rulerMenuOnClick = false;
  8307. if (drag == Drag::listen)
  8308. engine.stop();
  8309. if (drag == Drag::preview)
  8310. stopPreview();
  8311. resizeTrack = -1;
  8312. if (drag == Drag::move)
  8313. {
  8314. // FL reroutes only the clips that landed on another track: sliding a clip
  8315. // along its own audio track leaves its channel's insert alone
  8316. std::vector<int> moved;
  8317. const auto& playlist = engine.getSong().playlist;
  8318. for (std::size_t j = 0; j < dragIndices.size() && j < dragOriginals.size(); ++j)
  8319. {
  8320. const auto i = dragIndices[j];
  8321. if (i >= 0 && i < (int) playlist.size() && playlist[(std::size_t) i].track != dragOriginals[j].track)
  8322. moved.push_back (i);
  8323. }
  8324. // round 190cg: the lane automation under a clip goes along its track with it (same-track moves and copies)
  8325. if (automationFollows())
  8326. {
  8327. struct Carry
  8328. {
  8329. int track;
  8330. std::int64_t from, to, delta;
  8331. };
  8332. std::vector<Carry> carries;
  8333. for (std::size_t j = 0; j < dragIndices.size() && j < dragOriginals.size(); ++j)
  8334. {
  8335. const auto i = dragIndices[j];
  8336. const auto& o = dragOriginals[j];
  8337. if (i >= 0 && i < (int) playlist.size() && playlist[(std::size_t) i].track == o.track && playlist[(std::size_t) i].start != o.start
  8338. && o.kind != ClipKind::automation)
  8339. carries.push_back ({ o.track, o.start, o.end(), playlist[(std::size_t) i].start - o.start });
  8340. }
  8341. if (! carries.empty() && ! arrange::laneAutomations (engine.getSong()).empty())
  8342. engine.editSong ([carries, copy = dragCopies] (Song& s) {
  8343. for (const auto& c : carries)
  8344. arrange::carryLaneAutomation (s, c.track, c.from, c.to, c.delta, copy);
  8345. });
  8346. }
  8347. sortClips (moved, true);
  8348. dragCopies = false;
  8349. }
  8350. else if (drag == Drag::paint)
  8351. {
  8352. std::vector<int> painted; // the first painted clip and the copies appended after it
  8353. for (auto i = dragClip; i >= 0 && i < (int) engine.getSong().playlist.size(); ++i)
  8354. painted.push_back (i);
  8355. sortClips (painted);
  8356. }
  8357. else if (drag == Drag::resize || drag == Drag::trimLeft || drag == Drag::timeMove || drag == Drag::regionLoop)
  8358. {
  8359. // round 190ne: the pencil draws the next clip of an own-clips track as long as the one resized there last
  8360. if (const auto& song = engine.getSong(); drag == Drag::resize && dragClip >= 0 && dragClip < (int) song.playlist.size())
  8361. if (const auto& c = song.playlist[(std::size_t) dragClip]; c.kind == ClipKind::pattern && trackclips::pencilMakesNewClip (song, c.track) && c.length > 0)
  8362. lastTrackClipLength = c.length;
  8363. sortClips();
  8364. }
  8365. rippleOriginals.clear();
  8366. timeMoveOriginals.clear();
  8367. autoClip = autoPoint = -1;
  8368. laneTrack = laneIndex = -1;
  8369. drag = Drag::none;
  8370. dragClip = -1;
  8371. dragIndices.clear();
  8372. dragOriginals.clear();
  8373. touchedClips.clear();
  8374. rubberBand = {};
  8375. knownClipCount = engine.getSong().playlist.size();
  8376. hover = {};
  8377. updateHover (e.getPosition(), e.mods); // the cursor of what is under the mouse now
  8378. repaint();
  8379. }
  8380. // Round 190im (R12): Live's Split (Ctrl+E, its manual 6.6: "split a clip at the insert marker or at the boundaries of a
  8381. // selection"): every selected clip is cut at the time selection's start and end that fall inside it, or at the playhead
  8382. // when there is no time selection. One undo step; the pieces stay selected.
  8383. void PlaylistComponent::splitSelectionForLive()
  8384. {
  8385. const auto& song = engine.getSong();
  8386. std::vector<std::int64_t> at;
  8387. if (song.loopEnd > song.loopStart && song.loopStart >= 0)
  8388. at = { song.loopStart, song.loopEnd };
  8389. else
  8390. at = { (std::int64_t) std::llround (juce::jmax (0.0, playheadTick >= 0.0 ? playheadTick : engine.getTransport().positionTicks.load())) };
  8391. const auto targets = selection;
  8392. std::vector<int> pieces;
  8393. engine.editSong ([&targets, &at, &pieces] (Song& s) {
  8394. for (const auto index : targets)
  8395. {
  8396. if (index < 0 || index >= (int) s.playlist.size())
  8397. continue;
  8398. pieces.push_back (index);
  8399. auto part = index;
  8400. for (const auto tick : at)
  8401. if (tick > s.playlist[(std::size_t) part].start && tick < s.playlist[(std::size_t) part].end())
  8402. {
  8403. s.playlist.push_back (splitClip (s.playlist[(std::size_t) part], tick)); // (the piece after the cut)
  8404. part = (int) s.playlist.size() - 1;
  8405. pieces.push_back (part);
  8406. }
  8407. }
  8408. });
  8409. setSelection ({});
  8410. setSelection (pieces);
  8411. sortClips();
  8412. }
  8413. int PlaylistComponent::splitAtPlayhead()
  8414. {
  8415. const auto& song = engine.getSong();
  8416. const auto tick = (std::int64_t) std::llround (juce::jmax (0.0, playheadTick >= 0.0 ? playheadTick : engine.getTransport().positionTicks.load()));
  8417. const auto targets = splitat::clipsAt (song.playlist, selection, tick);
  8418. if (targets.empty())
  8419. return 0;
  8420. std::vector<int> pieces;
  8421. engine.editSong ([&targets, &pieces, tick] (Song& s) { pieces = splitat::split (s.playlist, targets, tick); });
  8422. setSelection ({});
  8423. setSelection (pieces);
  8424. sortClips();
  8425. return (int) targets.size();
  8426. }
  8427. void PlaylistComponent::cutWithKnife (juce::Point<int> from, juce::Point<int> to, bool snapOn)
  8428. {
  8429. const auto& playlist = engine.getSong().playlist;
  8430. std::vector<std::pair<int, std::int64_t>> cuts;
  8431. const auto round = snapOn ? gridTicks() / 2.0 : 0.0;
  8432. if (from.getDistanceFrom (to) < 3)
  8433. {
  8434. bool edge = false;
  8435. // (round 190rw: only inside the clip, as the line cut below: a click whose snap lands on the clip's edge cut a
  8436. // 1-tick sliver off it, or a 0-length piece off a 1-tick clip)
  8437. if (const auto hit = clipAt (from.x, from.y, edge); hit >= 0)
  8438. if (const auto tick = snap (xToTick (from.x) + round, snapOn);
  8439. tick > playlist[(std::size_t) hit].start && tick < playlist[(std::size_t) hit].end())
  8440. cuts.push_back ({ hit, tick });
  8441. }
  8442. else
  8443. {
  8444. // every track the line crosses is cut where the line passes its middle
  8445. const auto top = juce::jmin (from.y, to.y), bottom = juce::jmax (from.y, to.y);
  8446. for (int i = 0; i < (int) playlist.size(); ++i)
  8447. {
  8448. const auto& c = playlist[(std::size_t) i];
  8449. const auto trackHeight = heightOf (c.track);
  8450. const auto rowY = trackToY (c.track) + trackHeight / 2;
  8451. if (rowY < top - trackHeight / 2 || rowY > bottom + trackHeight / 2)
  8452. continue;
  8453. const auto y = juce::jlimit (top, bottom, rowY);
  8454. 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);
  8455. const auto tick = snap (xToTick ((int) std::round (x)) + round, snapOn);
  8456. if (tick > c.start && tick < c.end())
  8457. cuts.push_back ({ i, tick });
  8458. }
  8459. }
  8460. if (cuts.empty())
  8461. return;
  8462. setSelection ({});
  8463. engine.editSong ([&cuts] (Song& s) {
  8464. for (auto [index, tick] : cuts)
  8465. {
  8466. auto rest = splitClip (s.playlist[(std::size_t) index], tick);
  8467. s.playlist.push_back (rest);
  8468. }
  8469. });
  8470. sortClips();
  8471. }
  8472. void PlaylistComponent::zoomToTicks (double from, double to)
  8473. {
  8474. if (to - from < 1.0)
  8475. return;
  8476. // (round 190qe, UX-A3: glides with Animations on)
  8477. settleViewGlide();
  8478. auto target = currentView();
  8479. target.pixelsPerUnit = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, gridArea().getWidth() / (to - from));
  8480. target.scroll = juce::jmax (0.0, from);
  8481. showView (clampedView (target));
  8482. }
  8483. void PlaylistComponent::zoomIn (int anchorX)
  8484. {
  8485. const auto anchor = xToTick (anchorX);
  8486. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick * 2.0);
  8487. scrollTicks = juce::jmax (0.0, anchor - (anchorX - headerWidth) / pixelsPerTick);
  8488. updateScrollBars();
  8489. repaint();
  8490. }
  8491. void PlaylistComponent::zoomOut (int anchorX)
  8492. {
  8493. const auto anchor = xToTick (anchorX);
  8494. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick / 2.0);
  8495. scrollTicks = juce::jmax (0.0, anchor - (anchorX - headerWidth) / pixelsPerTick);
  8496. updateScrollBars();
  8497. repaint();
  8498. }
  8499. void PlaylistComponent::insertTimeSelection()
  8500. {
  8501. const auto& song = engine.getSong();
  8502. if (! song.hasLoop())
  8503. return;
  8504. setSelection ({});
  8505. engine.editSong ([from = song.loopStart, to = song.loopEnd] (Song& s) { noteedit::insertTime (s.playlist, s.markers(), from, to - from);
  8506. sections::insertTime (s.sections(), from, to - from);
  8507. chordlane::insertTime (s.chords(), from, to - from); }); // (round 190ol, 190pf)
  8508. sortClips();
  8509. }
  8510. void PlaylistComponent::deleteTimeSelection()
  8511. {
  8512. const auto& song = engine.getSong();
  8513. if (! song.hasLoop())
  8514. return;
  8515. setSelection ({});
  8516. engine.editSong ([from = song.loopStart, to = song.loopEnd] (Song& s) { noteedit::deleteTime (s.playlist, s.markers(), from, to);
  8517. sections::deleteTime (s.sections(), from, to);
  8518. chordlane::deleteTime (s.chords(), from, to); }); // (round 190ol, 190pf)
  8519. sortClips();
  8520. }
  8521. // --- round 190cg (core/ArrangeOps.h) ---------------------------------------------------------------------------------
  8522. void PlaylistComponent::setLiveStyle (bool on)
  8523. {
  8524. if (on == liveStyle)
  8525. return;
  8526. liveStyle = on;
  8527. foldLanesAfterOpen(); // round 190oo (CS O-3: a project opened in another layout folds when the arrangement first shows it)
  8528. refreshTrackLayout(); // (round 190gw: the Clip-launch layout keeps LYNX's 38 px default row; round 190jn: Live's 19 px in its look)
  8529. updateHeaderWidth(); // (round 190jn: Live's header row is wider)
  8530. sectionsLaneChanged(); // (round 190ol: no Sections lane in the Clip-launch layout)
  8531. chordLaneChanged(); // (round 190pf: the Chord lane's look follows the layout)
  8532. updateScrollBars();
  8533. repaint();
  8534. }
  8535. // --- round 190jn: Live's Arrangement look (design190ia CL-17, CL-18) -------------------------------------------------------
  8536. bool& playlistTallLiveLanes() { return tallLiveLanes; }
  8537. bool PlaylistComponent::liveArrangeLook() const noexcept
  8538. {
  8539. return liveStyle && theme::livelook::active();
  8540. }
  8541. // --- round 190mk (DL-70): Live's insert marker ----------------------------------------------------------------------------
  8542. void PlaylistComponent::setInsertMark (int track, std::int64_t tick)
  8543. {
  8544. insertMarkTrack = track >= 0 && track < numTracks() ? track : -1;
  8545. insertMarkTick = tick;
  8546. insertMarkLine.restart();
  8547. updateInsertMarkLine();
  8548. }
  8549. void PlaylistComponent::updateInsertMarkLine()
  8550. {
  8551. juce::Rectangle<int> line;
  8552. if (insertMarkTrack >= 0 && insertMarkTrack < numTracks() && insertMarkTick >= 0 && liveArrangeLook() && selection.empty())
  8553. {
  8554. const auto height = heightOf (insertMarkTrack) - 2; // (Live: over the lane's 17 px, its 2 px separator below stays)
  8555. if (height > 0)
  8556. line = juce::Rectangle<int> ((int) std::floor (tickToX ((double) insertMarkTick)), trackToY (insertMarkTrack), 1, height).getIntersection (gridArea());
  8557. }
  8558. if (line.isEmpty())
  8559. {
  8560. if (insertMarkLine.isVisible())
  8561. insertMarkLine.setVisible (false);
  8562. return;
  8563. }
  8564. if (insertMarkLine.getBounds() != line)
  8565. insertMarkLine.setBounds (line);
  8566. if (! insertMarkLine.isVisible())
  8567. insertMarkLine.setVisible (true);
  8568. }
  8569. // Live's status bar: "Insert Mark 63.1.1 (Time: 1:29:102)"
  8570. juce::String PlaylistComponent::insertMarkText() const
  8571. {
  8572. const auto& song = engine.getSong();
  8573. const auto bar = song.barAt (insertMarkTick);
  8574. const auto sig = markers::signatureAt (song, insertMarkTick);
  8575. const auto beat = (std::int64_t) ppq * 4 / juce::jmax (1, sig.second);
  8576. const auto position = insertmark::positionText (bar.number, insertMarkTick - bar.tick, beat, ticksPerStep);
  8577. return tr ("Insert Mark {0} (Time: {1})", { juce::String (position), juce::String (insertmark::timeText (song.secondsForTicks (insertMarkTick))) });
  8578. }
  8579. bool PlaylistComponent::insertMarkForSnapshot (int track, std::int64_t tick, juce::Rectangle<int>& line, juce::String& hint)
  8580. {
  8581. setSelection ({});
  8582. setInsertMark (track, tick);
  8583. insertMarkLine.setPhaseForSnapshot (0.0);
  8584. updateInsertMarkLine();
  8585. line = insertMarkLine.isVisible() ? insertMarkLine.getBounds() : juce::Rectangle<int>();
  8586. hint = insertMarkTrack >= 0 ? insertMarkText() : juce::String();
  8587. return ! line.isEmpty();
  8588. }
  8589. bool PlaylistComponent::liveHeaders() const
  8590. {
  8591. return liveArrangeLook() && ! simpleHeaders && ! linkedHeaders();
  8592. }
  8593. void PlaylistComponent::liveLanesChanged()
  8594. {
  8595. refreshTrackLayout();
  8596. updateHeaderWidth();
  8597. updateScrollBars();
  8598. repaint();
  8599. }
  8600. juce::Colour PlaylistComponent::liveClipColour (const Clip& c) const
  8601. {
  8602. // Live: a clip's own colour (an imported set's clip colour, Live's table: round 190ig CL-6), else its track's
  8603. const auto& song = engine.getSong();
  8604. std::uint32_t own = 0;
  8605. if (c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  8606. own = song.channels[(std::size_t) c.channel].colour;
  8607. else if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size())
  8608. own = song.automations[(std::size_t) c.automation].colour;
  8609. else if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  8610. own = song.patterns[(std::size_t) c.pattern].colour;
  8611. if (own == 0 && c.track >= 0 && c.track < (int) song.playlistTracks.size())
  8612. own = song.playlistTracks[(std::size_t) c.track].colour;
  8613. if (own != 0)
  8614. return juce::Colour (own).withAlpha (1.0f);
  8615. return c.kind == ClipKind::pattern ? patternColour (song, c.pattern) : c.kind == ClipKind::audio ? theme::colour::audioClip : theme::colour::automation;
  8616. }
  8617. theme::ClipLook PlaylistComponent::liveClipLook (const Clip& c) const
  8618. {
  8619. const auto colour = liveClipColour (c);
  8620. return theme::clipBody (colour, colour, c.kind, theme::ClipStyle::livePastel);
  8621. }
  8622. template <typename Line>
  8623. void PlaylistComponent::forEachLiveGridLine (double x0, double x1, Line&& line) const
  8624. {
  8625. const auto& song = engine.getSong();
  8626. const auto barPx = (double) song.barTicks() * pixelsPerTick;
  8627. if (barPx <= 0.0)
  8628. return;
  8629. int group = 1; // bars a shading group spans
  8630. while ((double) group * barPx < 80.0 && group < (1 << 16))
  8631. group *= 2;
  8632. int every = 1; // bars between two lines
  8633. while ((double) every * barPx < 8.0 && every < (1 << 16))
  8634. every *= 2;
  8635. const auto beats = ppq * pixelsPerTick >= 6.0 && every == 1;
  8636. const auto from = juce::jmax ((std::int64_t) 0, (std::int64_t) xToTick ((int) std::floor (x0)) - song.barTicks());
  8637. const auto to = (std::int64_t) xToTick ((int) std::ceil (x1)) + 1;
  8638. for (const auto& b : song.barsBetween (from, to))
  8639. {
  8640. const auto index = b.number - 1;
  8641. const auto odd = ((index / group) & 1) != 0;
  8642. if (index % every == 0)
  8643. line (tickToX ((double) b.tick), every > 1 || index % group == 0 ? 0 : 1, odd, b);
  8644. if (beats)
  8645. for (auto tick = b.tick + ppq; tick < b.tick + b.length; tick += ppq)
  8646. line (tickToX ((double) tick), 2, odd, b);
  8647. }
  8648. }
  8649. void PlaylistComponent::paintLiveGrid (juce::Graphics& g, juce::Rectangle<int> grid) const
  8650. {
  8651. const auto visible = grid.getIntersection (g.getClipBounds());
  8652. if (visible.isEmpty())
  8653. return;
  8654. static const juce::Colour shade[2] = { juce::Colour (0xff323232), juce::Colour (0xff363636) };
  8655. static const juce::Colour lines[2][3] = { { juce::Colour (0xff232323), juce::Colour (0xff282828), juce::Colour (0xff2c2c2c) },
  8656. { juce::Colour (0xff262626), juce::Colour (0xff2b2b2b), juce::Colour (0xff303030) } };
  8657. // the groups' shading, one rectangle per group (each bar's start: a group starts at its first bar)
  8658. g.setColour (shade[0]);
  8659. g.fillRect (visible);
  8660. const auto& song = engine.getSong();
  8661. const auto barPx = (double) song.barTicks() * pixelsPerTick;
  8662. int group = 1;
  8663. while (barPx > 0.0 && (double) group * barPx < 80.0 && group < (1 << 16))
  8664. group *= 2;
  8665. {
  8666. double runStart = -1.0;
  8667. const auto from = juce::jmax ((std::int64_t) 0, (std::int64_t) xToTick (visible.getX()) - song.barTicks());
  8668. const auto to = (std::int64_t) xToTick (visible.getRight()) + 1;
  8669. const auto fillRun = [&] (double end) {
  8670. if (runStart >= 0.0 && end > runStart)
  8671. g.fillRect (juce::Rectangle<double> (runStart, (double) visible.getY(), end - runStart, (double) visible.getHeight()).toFloat()
  8672. .getIntersection (visible.toFloat()));
  8673. };
  8674. g.setColour (shade[1]);
  8675. for (const auto& b : song.barsBetween (from, to))
  8676. {
  8677. const auto odd = (((b.number - 1) / group) & 1) != 0;
  8678. const auto x = (double) (int) tickToX ((double) b.tick);
  8679. if (odd && runStart < 0.0)
  8680. runStart = x;
  8681. else if (! odd && runStart >= 0.0)
  8682. {
  8683. fillRun (x);
  8684. runStart = -1.0;
  8685. }
  8686. }
  8687. fillRun ((double) visible.getRight());
  8688. }
  8689. forEachLiveGridLine ((double) visible.getX(), (double) visible.getRight(), [&] (double x, int level, bool odd, const Bar&) {
  8690. g.setColour (lines[odd ? 1 : 0][level]);
  8691. g.fillRect ((int) x, visible.getY(), 1, visible.getHeight());
  8692. });
  8693. }
  8694. bool PlaylistComponent::paintLiveLanesCached (juce::Graphics& g, juce::Rectangle<int> grid, int rows)
  8695. {
  8696. // (measured on Thief, Windows: the 19 px Arrangement's whole frame 15.6 -> 11.6 ms once the collapsed lanes' empty fade
  8697. // paths were gone; the frame's pixels match the lanes drawn straight but for 15 px of one glyph's edge over them.
  8698. // LYNX_LIVEGRID_CACHE=0 draws them straight, for checks)
  8699. static const bool enabled = juce::SystemStats::getEnvironmentVariable ("LYNX_LIVEGRID_CACHE", "1") != "0";
  8700. if (! enabled || grid.isEmpty())
  8701. return false;
  8702. // whole physical pixels only (1x, 2x): the image then maps 1:1 onto the screen's pixels, the same pixels as drawn straight
  8703. const auto physical = g.getInternalContext().getPhysicalPixelScaleFactor();
  8704. const auto scale = std::round (physical);
  8705. if (scale < 1.0f || scale > 2.0f || std::abs (physical - scale) > 1.0e-4f)
  8706. return false;
  8707. const auto mix = [] (std::uint64_t h, std::uint64_t v) { return (h ^ v) * 0x100000001b3ull; };
  8708. const auto bits = [] (double v) {
  8709. std::uint64_t u = 0;
  8710. std::memcpy (&u, &v, sizeof u);
  8711. return u;
  8712. };
  8713. auto key = mix (mix (mix (mix (0xcbf29ce484222325ull, (std::uint64_t) grid.getX()), (std::uint64_t) grid.getY()), (std::uint64_t) grid.getWidth()),
  8714. (std::uint64_t) grid.getHeight());
  8715. key = mix (mix (mix (key, (std::uint64_t) scale), bits (tickToX (0.0))), bits (tickToX ((double) ppq * 4096.0)));
  8716. const auto& song = engine.getSong();
  8717. const auto from = juce::jmax ((std::int64_t) 0, (std::int64_t) xToTick (grid.getX()) - song.barTicks());
  8718. const auto to = (std::int64_t) xToTick (grid.getRight()) + 1;
  8719. for (const auto& b : song.barsBetween (from, to)) // (the bars' places and lengths: a time signature change moves the grid)
  8720. key = mix (mix (key, (std::uint64_t) b.tick), (std::uint64_t) b.length);
  8721. for (int t = 0; t < rows; ++t)
  8722. if (const auto y = trackToY (t), h = heightOf (t); y <= grid.getBottom() && y + h >= grid.getY())
  8723. key = mix (mix (key, (std::uint64_t) (std::int64_t) y), (std::uint64_t) h);
  8724. const auto w = (int) scale * grid.getWidth(), h = (int) scale * grid.getHeight();
  8725. if (key != liveLaneKey || liveLaneImage.getWidth() != w || liveLaneImage.getHeight() != h)
  8726. {
  8727. // (round 190pb: an opaque RGB picture: the grid's shading covers all of it with opaque colours, so it is the same
  8728. // pixels as ARGB, and the software renderer copies an RGB row (a 4-byte store a pixel into an ARGB target, JUCE fix
  8729. // 45; memcpy into an RGB one) where it blended every ARGB pixel: the Patience set's Clip-launch arrangement -14 M
  8730. // instructions a frame)
  8731. if (liveLaneImage.getWidth() != w || liveLaneImage.getHeight() != h || liveLaneImage.getFormat() != juce::Image::RGB)
  8732. liveLaneImage = juce::Image (juce::Image::RGB, w, h, false, juce::NativeImageType());
  8733. juce::Graphics ig (liveLaneImage);
  8734. ig.addTransform (juce::AffineTransform::translation ((float) -grid.getX(), (float) -grid.getY()).scaled (scale));
  8735. paintLiveGrid (ig, grid);
  8736. ig.setColour (liveLaneSeparator);
  8737. for (int t = 0; t < rows; ++t)
  8738. if (const auto y = trackToY (t), th = heightOf (t); y <= grid.getBottom() && y + th >= grid.getY())
  8739. ig.fillRect (grid.getX(), y + th - 2, grid.getWidth(), 2);
  8740. liveLaneKey = key;
  8741. }
  8742. if (scale == 1.0f)
  8743. g.drawImageAt (liveLaneImage, grid.getX(), grid.getY());
  8744. else
  8745. g.drawImage (liveLaneImage, grid.toFloat(), juce::RectanglePlacement::stretchToFit);
  8746. return true;
  8747. }
  8748. juce::Rectangle<float> PlaylistComponent::paintLiveClipFrame (juce::Graphics& g, juce::Rectangle<float> r, const theme::ClipLook& look,
  8749. const juce::String& name) const
  8750. {
  8751. const uitrace::Part tally (uitrace::part::frame);
  8752. const auto rim = theme::liveShade (look.body, 0.53f);
  8753. const auto strip = (float) liveStripHeight;
  8754. // (the rim colour under the whole clip, the body over the strip's inside and over the rest right of the left rim: two
  8755. // rectangles on a collapsed lane, three on a taller one, instead of four)
  8756. const auto stripRect = r.withHeight (juce::jmin (strip, r.getHeight()));
  8757. g.setColour (rim);
  8758. g.fillRect (r);
  8759. g.setColour (look.body);
  8760. g.fillRect (stripRect.withTrimmedLeft (1.0f).withTrimmedTop (1.0f).withTrimmedBottom (1.0f));
  8761. if (r.getHeight() > strip)
  8762. g.fillRect (r.withTrimmedTop (strip).withTrimmedLeft (1.0f));
  8763. juce::Rectangle<float> body;
  8764. if (r.getHeight() >= strip + 4.0f)
  8765. {
  8766. body = r.withTrimmedTop (strip).withTrimmedLeft (1.0f);
  8767. // the grid inside the body (Live: beats x 0.88, bars x 0.79, a group's first bar x 0.68)
  8768. const auto inner = body.getIntersection (g.getClipBounds().toFloat());
  8769. if (! inner.isEmpty())
  8770. {
  8771. const juce::Colour lines[3] = { theme::liveShade (look.body, 0.68f), theme::liveShade (look.body, 0.79f), theme::liveShade (look.body, 0.88f) };
  8772. forEachLiveGridLine ((double) inner.getX(), (double) inner.getRight(), [&] (double x, int level, bool, const Bar&) {
  8773. if (x < (double) inner.getX() || x >= (double) inner.getRight())
  8774. return;
  8775. g.setColour (lines[level]);
  8776. g.fillRect (juce::Rectangle<float> ((float) (int) x, body.getY(), 1.0f, body.getHeight()));
  8777. });
  8778. }
  8779. }
  8780. if (! (r.getX() < heldTitleLeft && r.getRight() > heldTitleLeft) || ! heldEveryClip()) // (round 190qe: else the held pass draws it)
  8781. paintLiveClipTitle (g, r, look, name);
  8782. return body;
  8783. }
  8784. // paintLiveClipFrame's name in the strip (round 190qe: also a title held at the view's left edge)
  8785. void PlaylistComponent::paintLiveClipTitle (juce::Graphics& g, juce::Rectangle<float> r, const theme::ClipLook& look, const juce::String& name) const
  8786. {
  8787. if (r.getWidth() > 12.0f && name.isNotEmpty())
  8788. {
  8789. const auto strip = (float) liveStripHeight;
  8790. const uitrace::Part tallyTitle (uitrace::part::title);
  8791. g.setColour (look.ink);
  8792. g.setFont (theme::font (theme::type::small));
  8793. const auto text = juce::Rectangle<float> (r.getX() + 4.0f, r.getY() + 1.0f, r.getWidth() - 6.0f, juce::jmin (strip, r.getHeight()) - 2.0f);
  8794. textcache::drawText (g, name, text.toNearestInt(), juce::Justification::centredLeft, false);
  8795. }
  8796. }
  8797. bool PlaylistComponent::automationFollows() const noexcept
  8798. {
  8799. const auto set = EditorGlobals::get().automationFollowsClips;
  8800. return set < 0 ? liveStyle : set > 0;
  8801. }
  8802. void PlaylistComponent::setLoopSwitch (bool plays)
  8803. {
  8804. if (engine.getSong().hasLoop())
  8805. engine.editSong ([plays] (Song& s) { s.loopOff = ! plays; }, false);
  8806. repaint();
  8807. }
  8808. void PlaylistComponent::timeCommand (int which)
  8809. {
  8810. const auto& song = engine.getSong();
  8811. const auto time = song.hasLoop();
  8812. const auto from = song.loopStart, to = song.loopEnd;
  8813. if (which == 3)
  8814. {
  8815. if (timeClipboard.length <= 0)
  8816. return;
  8817. setSelection ({});
  8818. engine.editSong ([at = time ? from : snap ((double) songPositionTick(), true), clip = timeClipboard, carried = timePatterns] (Song& s) mutable {
  8819. trackclips::materialize (s, clip.clips, carried); // (round 190ne: pasted track clips are unique copies)
  8820. arrange::pasteTime (s, at, clip);
  8821. });
  8822. }
  8823. else if (! time)
  8824. return;
  8825. else if (which == 2)
  8826. {
  8827. timeClipboard = arrange::copyTime (song, from, to);
  8828. timePatterns = trackclips::carry (song, timeClipboard.clips);
  8829. }
  8830. else if (which == 4)
  8831. engine.editSong ([from, to, clips = selection] (Song& s) { arrange::cropClips (s, clips, from, to); });
  8832. else
  8833. {
  8834. setSelection ({});
  8835. if (which == 1)
  8836. {
  8837. timeClipboard = arrange::copyTime (song, from, to);
  8838. timePatterns = trackclips::carry (song, timeClipboard.clips);
  8839. }
  8840. engine.editSong ([from, to, which] (Song& s) {
  8841. if (which == 0)
  8842. {
  8843. const auto before = s.playlist.size();
  8844. arrange::duplicateTime (s, from, to);
  8845. std::vector<int> copies; // (round 190ne: the copies of track clips are unique)
  8846. for (auto i = before; i < s.playlist.size(); ++i)
  8847. copies.push_back ((int) i);
  8848. trackclips::makeCopiesUnique (s, copies);
  8849. }
  8850. else
  8851. {
  8852. arrange::deleteTime (s, from, to);
  8853. s.loopEnd = s.loopStart; // the range is gone
  8854. }
  8855. });
  8856. }
  8857. sortClips();
  8858. repaint();
  8859. }
  8860. void PlaylistComponent::askTempoRange()
  8861. {
  8862. const auto& song = engine.getSong();
  8863. const auto set = song.tempoViewHigh > song.tempoViewLow;
  8864. auto* box = new juce::AlertWindow (tr ("Tempo range shown"), tr ("Lowest and highest tempo of the tempo lane (BPM)"), juce::MessageBoxIconType::NoIcon, this);
  8865. box->addTextEditor ("low", juce::String (set ? song.tempoViewLow : 60.0), tr ("Lowest"));
  8866. box->addTextEditor ("high", juce::String (set ? song.tempoViewHigh : 200.0), tr ("Highest"));
  8867. box->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8868. box->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8869. box->enterModalState (true, juce::ModalCallbackFunction::create ([this, box] (int result) {
  8870. const auto low = juce::jlimit (minTempo, maxTempo, box->getTextEditorContents ("low").replaceCharacter (',', '.').getDoubleValue());
  8871. const auto high = juce::jlimit (minTempo, maxTempo, box->getTextEditorContents ("high").replaceCharacter (',', '.').getDoubleValue());
  8872. if (result == 1 && high > low + 1.0)
  8873. engine.editSong ([low, high] (Song& s) { s.tempoViewLow = low; s.tempoViewHigh = high; });
  8874. repaint();
  8875. }), true);
  8876. }
  8877. void PlaylistComponent::sliceInsertTimeSelection()
  8878. {
  8879. const auto& song = engine.getSong();
  8880. if (! song.hasLoop())
  8881. return;
  8882. setSelection ({});
  8883. engine.editSong ([from = song.loopStart, to = song.loopEnd] (Song& s) { noteedit::sliceInsertTime (s.playlist, s.markers(), from, to - from);
  8884. sections::insertTime (s.sections(), from, to - from);
  8885. chordlane::insertTime (s.chords(), from, to - from); }); // (round 190ol, 190pf)
  8886. sortClips();
  8887. }
  8888. void PlaylistComponent::trimTimeSelection()
  8889. {
  8890. const auto& song = engine.getSong();
  8891. if (! song.hasLoop())
  8892. return;
  8893. setSelection ({});
  8894. engine.editSong ([from = song.loopStart, to = song.loopEnd] (Song& s) {
  8895. noteedit::trimTime (s.playlist, s.markers(), from, to);
  8896. sections::deleteTime (s.sections(), to, std::numeric_limits<std::int64_t>::max() / 4); // (round 190ol)
  8897. sections::deleteTime (s.sections(), 0, from);
  8898. chordlane::deleteTime (s.chords(), to, std::numeric_limits<std::int64_t>::max() / 4); // (round 190pf)
  8899. chordlane::deleteTime (s.chords(), 0, from);
  8900. s.loopStart = s.loopEnd = 0; // (FL clears the time selection after a trim, FUN_00eb35f0)
  8901. });
  8902. sortClips();
  8903. }
  8904. void PlaylistComponent::selectAllWithTime()
  8905. {
  8906. // FL's EESelAllAction (FUN_00eb1960): in the Playlist the time selection also covers the whole song, from 0 to the
  8907. // end of the last clip rounded up to a whole bar (FUN_00e43d30), then every clip is selected (FUN_00e5a850)
  8908. const auto& song = engine.getSong();
  8909. std::vector<int> all ((std::size_t) song.playlist.size());
  8910. std::int64_t end = 0;
  8911. for (std::size_t i = 0; i < all.size(); ++i)
  8912. {
  8913. all[i] = (int) i;
  8914. end = std::max (end, song.playlist[i].start + std::max<std::int64_t> (1, song.playlist[i].length));
  8915. }
  8916. if (end > 0)
  8917. {
  8918. const auto bar = song.barAt (end - 1);
  8919. engine.editSong ([to = bar.tick + bar.length] (Song& s) {
  8920. s.loopStart = 0;
  8921. s.loopEnd = to;
  8922. s.mode = PlayMode::song;
  8923. }, false);
  8924. }
  8925. setSelection (all);
  8926. }
  8927. void PlaylistComponent::shiftSelectedClips (int steps, int tracks, bool fine)
  8928. {
  8929. // the selected clips, else all of them (FL's menu offers these with nothing selected: FL's usual "selected, else all",
  8930. // as Mute does, FUN_01061e80; the manual: "If no selection is made then all the Clips will be moved")
  8931. auto chosen = selection;
  8932. if (chosen.empty())
  8933. for (int i = 0; i < (int) engine.getSong().playlist.size(); ++i)
  8934. chosen.push_back (i);
  8935. // FL (FUN_00e51730, round 190ag): one snap step, or with Alt held one pixel's worth of ticks at this zoom
  8936. const auto step = fine ? clipops::pixelStepTicks (pixelsPerTick) : juce::jmax<std::int64_t> (1, gridTicks());
  8937. moveClips (std::move (chosen), (std::int64_t) steps * step, tracks, true, true);
  8938. }
  8939. void PlaylistComponent::moveClips (std::vector<int> chosen, std::int64_t delta, int tracks, bool newUndoStep, bool keepInView)
  8940. {
  8941. // the one move behind Shift+arrows, Alt+arrows and the Shift+Alt+wheel nudge (issue #147): the clips move together and
  8942. // stop together at the song start and at the first / last track; nothing is recorded when they cannot move
  8943. {
  8944. auto probe = engine.getSong().playlist;
  8945. const auto time = delta != 0 ? clipops::shiftClipsInTime (probe, chosen, delta) : 0;
  8946. const auto rows = tracks != 0 ? clipops::shiftClipsTrack (probe, chosen, tracks) : 0;
  8947. if (chosen.empty() || (time == 0 && rows == 0))
  8948. return;
  8949. }
  8950. auto edge = delta < 0 ? std::numeric_limits<std::int64_t>::max() : std::numeric_limits<std::int64_t>::min();
  8951. auto rows = 0; // (what the move came to: 0 at the first / last track)
  8952. engine.editSong ([&chosen, &edge, &rows, delta, tracks] (Song& s) {
  8953. if (delta != 0)
  8954. clipops::shiftClipsInTime (s.playlist, chosen, delta);
  8955. if (tracks != 0)
  8956. rows = clipops::shiftClipsTrack (s.playlist, chosen, tracks);
  8957. for (auto i : chosen)
  8958. if (i >= 0 && i < (int) s.playlist.size())
  8959. edge = delta < 0 ? std::min (edge, s.playlist[(std::size_t) i].start) : std::max (edge, s.playlist[(std::size_t) i].end());
  8960. }, newUndoStep);
  8961. // (only a change of track can put an audio clip on another audio track: a move in time asks nothing)
  8962. sortClips (tracks != 0 ? std::move (chosen) : std::vector<int> {}, rows != 0);
  8963. if (keepInView && delta != 0) // FL scrolls to keep the leading edge of the moved clips in view (FUN_00e7e290)
  8964. if (const auto to = clipops::scrollToShowEdge (scrollTicks, (double) gridArea().getWidth(), pixelsPerTick, edge, delta > 0);
  8965. ! juce::approximatelyEqual (to, scrollTicks))
  8966. {
  8967. gliding = false;
  8968. scrollTicks = to;
  8969. updateScrollBars();
  8970. repaint();
  8971. }
  8972. }
  8973. void PlaylistComponent::selectBySelectedSource()
  8974. {
  8975. const auto found = clipops::clipsOfSource (engine.getSong(), makeBrushClip (0, 0));
  8976. if (found.empty())
  8977. {
  8978. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("No clips selected"),
  8979. tr ("There are no clips associated with the currently selected source clip."));
  8980. return;
  8981. }
  8982. setSelection (found);
  8983. }
  8984. std::unique_ptr<juce::AlertWindow> PlaylistComponent::makeHeaderDropDialog()
  8985. {
  8986. // FL's "Dropped sample(s)" box (FUN_00e71430: the three choices and Cancel, in FL's order)
  8987. auto box = std::make_unique<juce::AlertWindow> (tr ("Dropped sample(s)"), tr ("Do you want to create audio clip(s), audio track(s) or instrument track(s)?"),
  8988. juce::MessageBoxIconType::QuestionIcon);
  8989. box->addButton (tr ("Audio clip(s)"), 1);
  8990. box->addButton (tr ("Audio track(s)"), 2);
  8991. box->addButton (tr ("Instrument track(s)"), 3);
  8992. box->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8993. return box;
  8994. }
  8995. void PlaylistComponent::dropOnTrackHeader (const juce::StringArray& files, int track)
  8996. {
  8997. juce::StringArray samples;
  8998. for (const auto& f : files)
  8999. if (SampleLibrary::isSampleFile (juce::File (f)))
  9000. samples.add (f);
  9001. if (samples.isEmpty())
  9002. return;
  9003. const auto mode = trackmodes::headerDropOptions().mode;
  9004. if (mode != trackmodes::HeaderDrop::ask)
  9005. {
  9006. dropOnTrackHeaderAs (samples, track, mode);
  9007. return;
  9008. }
  9009. // FL's question (FUN_00e71430, asked once for all the dropped files)
  9010. auto* box = makeHeaderDropDialog().release();
  9011. box->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<PlaylistComponent> (this), samples, track] (int result) {
  9012. if (safe == nullptr || result < 1 || result > 3)
  9013. return;
  9014. const auto how = result == 1 ? trackmodes::HeaderDrop::audioClips
  9015. : result == 2 ? trackmodes::HeaderDrop::audioTracks
  9016. : trackmodes::HeaderDrop::instrumentTracks;
  9017. safe->dropOnTrackHeaderAs (samples, track, how);
  9018. }), true);
  9019. }
  9020. void PlaylistComponent::dropOnTrackHeaderAs (const juce::StringArray& files, int track, trackmodes::HeaderDrop how)
  9021. {
  9022. const auto lock = trackmodes::headerDropOptions().lockToContent;
  9023. std::vector<int> tracks;
  9024. auto failed = false;
  9025. for (const auto& f : files)
  9026. {
  9027. const juce::File file (f);
  9028. const auto data = engine.getSampleLibrary().load (file.getFullPathName());
  9029. if (data == nullptr)
  9030. continue;
  9031. const auto seconds = (double) data->frames() / data->sampleRate;
  9032. const auto length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * engine.getSong().bpm / 60.0 * ppq));
  9033. const auto path = file.getFullPathName().toStdString();
  9034. const auto name = file.getFileNameWithoutExtension().toStdString();
  9035. auto done = false;
  9036. engine.editSong ([&] (Song& s) {
  9037. const auto before = s.playlist.size();
  9038. done = trackmodes::dropOnHeader (s, track, path, name, length, how, lock);
  9039. for (auto i = before; done && i < s.playlist.size(); ++i)
  9040. if (s.playlist[i].kind == ClipKind::audio)
  9041. s.playlist[i].flFadeFlags |= newClipFadeFlags();
  9042. });
  9043. if (done)
  9044. tracks.push_back (track);
  9045. else if (how != trackmodes::HeaderDrop::audioClips)
  9046. failed = true;
  9047. ++track; // (FL: each further file on the next track)
  9048. }
  9049. sortClips();
  9050. if (! tracks.empty() && trackmodes::headerDropOptions().selectTracks)
  9051. {
  9052. currentTrack = tracks.front();
  9053. selectedTracks = tracks;
  9054. repaint();
  9055. }
  9056. if (failed)
  9057. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't create instrument/audio track"),
  9058. tr ("No available mixer track was found."));
  9059. }
  9060. juce::PopupMenu PlaylistComponent::editMenu()
  9061. {
  9062. auto key = [] (const char* id) { return shortcutText != nullptr ? shortcutText (id) : juce::String(); };
  9063. const auto& song = engine.getSong();
  9064. const auto any = ! selection.empty(), time = song.hasLoop();
  9065. const auto allAudio = any && std::all_of (selection.begin(), selection.end(), [&song] (int i) {
  9066. return i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio;
  9067. });
  9068. juce::PopupMenu m;
  9069. m.addItem (tr ("Cut") + key ("playlist.cut"), any, false, [this] { copySelection(); deleteSelection(); });
  9070. m.addItem (tr ("Copy") + key ("playlist.copy"), any, false, [this] { copySelection(); });
  9071. m.addItem (tr ("Paste") + key ("playlist.paste"), canPasteClips(), false, [this] { pasteClips(); });
  9072. m.addItem (tr ("Duplicate") + "\tCtrl+B", any || time, false, [this] { duplicateSelection(); });
  9073. // round 190ne (core/TrackClips.h): copies that keep sharing the clip's notes (only track clips differ from Duplicate)
  9074. m.addItem (tr ("Duplicate as linked copies") + key ("playlist.duplicateLinked"), any || time, false, [this] { duplicateSelection (true); });
  9075. m.addItem (tr ("Delete") + "\tDel", any, false, [this] { if (ripple) rippleDeleteSelection(); else deleteSelection(); });
  9076. m.addSeparator();
  9077. m.addItem (tr ("Shift left") + key ("playlist.shiftLeft"), [this] { runAction ("playlist.shiftLeft"); });
  9078. m.addItem (tr ("Shift right") + key ("playlist.shiftRight"), [this] { runAction ("playlist.shiftRight"); });
  9079. m.addItem (tr ("Shift up") + key ("playlist.shiftUp"), [this] { runAction ("playlist.shiftUp"); });
  9080. m.addItem (tr ("Shift down") + key ("playlist.shiftDown"), [this] { runAction ("playlist.shiftDown"); });
  9081. m.addItem (tr ("Make unique") + key ("playlist.makeUnique"), any, false, [this] { runAction ("playlist.makeUnique"); });
  9082. // (FL 2026: on with audio clips selected, off when the selection also holds other clips)
  9083. m.addItem (tr ("Make unique as sample") + key ("playlist.makeUniqueAsSample"), allAudio, false, [this] { runAction ("playlist.makeUniqueAsSample"); });
  9084. m.addSeparator();
  9085. {
  9086. auto& g = EditorGlobals::get();
  9087. m.addItem (tr ("Allow resizing from left") + key ("playlist.leftResizing"), true, g.leftResizing, [this] { runAction ("playlist.leftResizing"); });
  9088. m.addItem (tr ("Nudge clips with mouse wheel") + key ("playlist.wheelNudging"), true, g.wheelNudging, [this] { runAction ("playlist.wheelNudging"); });
  9089. }
  9090. {
  9091. auto& o = trackmodes::headerDropOptions();
  9092. m.addItem (tr ("Dropping on track header locks to content"), true, o.lockToContent, [this] {
  9093. trackmodes::headerDropOptions().lockToContent = ! trackmodes::headerDropOptions().lockToContent;
  9094. if (EditorGlobals::get().onOptionsChanged)
  9095. EditorGlobals::get().onOptionsChanged();
  9096. });
  9097. juce::PopupMenu drop;
  9098. using trackmodes::HeaderDrop;
  9099. for (auto [how, text] : { std::pair { HeaderDrop::audioClips, TR_NOOP ("As audio clips") }, { HeaderDrop::audioTracks, TR_NOOP ("As audio tracks") },
  9100. { HeaderDrop::instrumentTracks, TR_NOOP ("As instrument tracks") }, { HeaderDrop::ask, TR_NOOP ("Always ask") } })
  9101. {
  9102. juce::PopupMenu::Item item (tr (text));
  9103. item.setTicked (o.mode == how).setAction ([this, how = how] {
  9104. trackmodes::headerDropOptions().mode = how;
  9105. if (EditorGlobals::get().onOptionsChanged)
  9106. EditorGlobals::get().onOptionsChanged();
  9107. });
  9108. item.isEnabled = true;
  9109. drop.addItem (item);
  9110. }
  9111. m.addSubMenu (tr ("Drop audio on track headers"), drop);
  9112. }
  9113. m.addSeparator();
  9114. m.addItem (tr ("Mute") + key ("playlist.muteClips"), [this] { runAction ("playlist.muteClips"); });
  9115. m.addItem (tr ("Unmute") + key ("playlist.unmuteClips"), [this] { runAction ("playlist.unmuteClips"); });
  9116. // issue #249 (round 190oq, LYNX extra): Alt+M switches both ways (FL's only mutes)
  9117. m.addItem (tr ("Alt+M toggles: pressed again, it unmutes (LYNX)"), true, mutekeys::toggles(),
  9118. [] { workflowextras::setExtra ("editing.muteKeyToggles", ! mutekeys::toggles()); });
  9119. m.addSeparator();
  9120. m.addItem (tr ("Insert space") + "\tCtrl+Ins", time, false, [this] { insertTimeSelection(); });
  9121. m.addItem (tr ("Slice & insert space") + "\tCtrl+Alt+Ins", time, false, [this] { runAction ("playlist.sliceInsertSpace"); });
  9122. m.addItem (tr ("Delete space") + "\tCtrl+Del", time, false, [this] { deleteTimeSelection(); });
  9123. m.addItem (tr ("Trim selection") + key ("playlist.trimSpace"), time, false, [this] { runAction ("playlist.trimSpace"); });
  9124. // issue #285 (round 190rc, LYNX extra): the Slice tool's cut at the song position, in one step
  9125. m.addItem (tr ("Cut clips at the song position") + key ("playlist.splitAtPlayhead"), true, false, [this] { runAction ("playlist.splitAtPlayhead"); });
  9126. // round 190cg: Live's time commands and loop switch on the same time selection [live-exe-strings.txt:1645342…1645365
  9127. // sMenuTextCutTime / CopyTime / sMenuPasteTime / DuplicateTime; 1645321 sMenuActivateLoop; 1636009 sMenuTextCrop]
  9128. m.addItem (tr ("Duplicate time") + key ("playlist.duplicateTime"), time, false, [this] { timeCommand (0); });
  9129. m.addItem (tr ("Cut time") + key ("playlist.cutTime"), time, false, [this] { timeCommand (1); });
  9130. m.addItem (tr ("Copy time") + key ("playlist.copyTime"), time, false, [this] { timeCommand (2); });
  9131. m.addItem (tr ("Paste time") + key ("playlist.pasteTime"), timeClipboard.length > 0, false, [this] { timeCommand (3); });
  9132. m.addItem (tr ("Crop clips to the time selection") + key ("playlist.cropClips"), time && any, false, [this] { timeCommand (4); });
  9133. m.addSeparator();
  9134. m.addItem (tr ("Loop the time selection") + key ("playlist.loopSwitch"), time, song.loopPlays(), [this] { runAction ("playlist.loopSwitch"); });
  9135. m.addItem (tr ("Halve the time selection") + key ("playlist.loopHalve"), time, false, [this] { runAction ("playlist.loopHalve"); });
  9136. m.addItem (tr ("Double the time selection") + key ("playlist.loopDouble"), time, false, [this] { runAction ("playlist.loopDouble"); });
  9137. m.addSeparator();
  9138. m.addItem (tr ("Automation follows clips") + key ("playlist.automationFollowsClips"), true, automationFollows(),
  9139. [this] { runAction ("playlist.automationFollowsClips"); });
  9140. m.addSeparator();
  9141. m.addItem (tr ("Merge selected clips") + key ("playlist.mergePatternClips"), [this] { runAction ("playlist.mergePatternClips"); });
  9142. m.addItem (tr ("Merge similar pattern clips") + key ("playlist.mergeSimilarClips"), [this] { runAction ("playlist.mergeSimilarClips"); });
  9143. m.addItem (tr ("Merge automation clips") + key ("playlist.mergeAutomationClips"), [this] { runAction ("playlist.mergeAutomationClips"); });
  9144. m.addItem (tr ("Purge unused audio clips"), [this] { runAction ("playlist.purgeUnusedAudio"); });
  9145. m.addSeparator();
  9146. m.addItem (tr ("Pitch selected audio clips one semitone down") + key ("playlist.pitchClipsDown"), [this] { runAction ("playlist.pitchClipsDown"); });
  9147. m.addItem (tr ("Pitch selected audio clips one semitone up") + key ("playlist.pitchClipsUp"), [this] { runAction ("playlist.pitchClipsUp"); });
  9148. m.addItem (tr ("Reverse selected audio clips") + key ("playlist.reverseClips"), [this] { runAction ("playlist.reverseClips"); });
  9149. m.addSeparator();
  9150. m.addItem (tr ("Automatic crossfades (current project)"), true, song.autoCrossfades, [this] { runAction ("playlist.autoCrossfades"); });
  9151. m.addItem (tr ("Link Playlist tracks to mixer tracks (current project)") + key ("playlist.linkTracks"), true, song.linkTracksToMixer,
  9152. [this] { runAction ("playlist.linkTracks"); }); // round 190gz (issue #170), LYNX extra
  9153. m.addItem (tr ("Show insert effects on linked tracks") + key ("playlist.trackInserts"), ! simpleHeaders, showTrackInserts,
  9154. [this] { runAction ("playlist.trackInserts"); }); // round 190ht (issue #154), LYNX extra
  9155. m.addItem (tr ("Create new clips with manual fades") + key ("playlist.manualFades"), true, EditorGlobals::get().manualFades,
  9156. [this] { runAction ("playlist.manualFades"); });
  9157. m.addItem (tr ("Snap fade handles") + key ("playlist.snapFadeHandles"), true, EditorGlobals::get().snapFadeHandles,
  9158. [this] { runAction ("playlist.snapFadeHandles"); });
  9159. m.addItem (tr ("Create variants when stretching audio clips"), true, EditorGlobals::get().createVariants, [this] { runAction ("playlist.createVariants"); });
  9160. m.addItem (tr ("Select tracks when samples are dropped"), true, trackmodes::headerDropOptions().selectTracks, [] {
  9161. trackmodes::headerDropOptions().selectTracks = ! trackmodes::headerDropOptions().selectTracks;
  9162. if (EditorGlobals::get().onOptionsChanged)
  9163. EditorGlobals::get().onOptionsChanged();
  9164. });
  9165. return m;
  9166. }
  9167. juce::PopupMenu PlaylistComponent::selectMenu()
  9168. {
  9169. auto key = [] (const char* id) { return shortcutText != nullptr ? shortcutText (id) : juce::String(); };
  9170. const auto& song = engine.getSong();
  9171. juce::PopupMenu select;
  9172. select.addItem (tr ("Deselect") + key ("playlist.deselect"), ! selection.empty() || song.hasLoop(), false, [this] { runAction ("playlist.deselect"); });
  9173. select.addItem (tr ("Select all") + "\tCtrl+A", [this] { selectAllWithTime(); });
  9174. select.addItem (tr ("Select by selected source") + key ("playlist.selectBySource"), [this] { runAction ("playlist.selectBySource"); });
  9175. // (the counts are LYNX's own, round 153)
  9176. const auto overlapping = clipops::overlappingClips (song), stacked = clipops::stackedClips (song), muted = clipops::mutedClips (song);
  9177. select.addItem (tr ("Muted clips ({0})", { juce::String ((int) muted.size()) }), ! muted.empty(), false, [this, muted] { setSelection (muted); });
  9178. select.addItem (tr ("Overlapping clips ({0})", { juce::String ((int) overlapping.size()) }), ! overlapping.empty(), false,
  9179. [this, overlapping] { setSelection (overlapping); });
  9180. select.addItem (tr ("Stacked clips: hidden duplicates ({0})", { juce::String ((int) stacked.size()) }), ! stacked.empty(), false,
  9181. [this, stacked] { setSelection (stacked); });
  9182. select.addItem (tr ("Invert selection") + key ("playlist.invertSelection"), [this] { runAction ("playlist.invertSelection"); });
  9183. select.addSeparator();
  9184. select.addItem (tr ("Select time around selection") + key ("playlist.selectTimeAround"), ! selection.empty(), false,
  9185. [this] { runAction ("playlist.selectTimeAround"); });
  9186. select.addItem (tr ("Select previous time") + key ("playlist.timePrevious"), song.hasLoop(), false, [this] { runAction ("playlist.timePrevious"); });
  9187. select.addItem (tr ("Select next time") + key ("playlist.timeNext"), song.hasLoop(), false, [this] { runAction ("playlist.timeNext"); });
  9188. select.addSeparator();
  9189. select.addItem (tr ("Magic lasso") + key ("playlist.magicLasso"), true, EditorGlobals::get().magicLasso, [this] { runAction ("playlist.magicLasso"); });
  9190. // round 190qe (D2-PL9, LYNX's own): the selection a click replaced or cleared
  9191. select.addItem (tr ("Restore selection") + " (LYNX)" + key ("playlist.restoreSelection"), selectionHistory.size() > 0, false,
  9192. [this] { runAction ("playlist.restoreSelection"); });
  9193. return select;
  9194. }
  9195. juce::String PlaylistComponent::describeLinkPlan (const Song& song, const autolink::Report& report)
  9196. {
  9197. using Kind = autolink::Change::Kind;
  9198. const auto u8 = [] (const std::string& s) { return juce::String::fromUTF8 (s.c_str()); };
  9199. const auto insert = [] (int m) { return m <= 0 ? tr ("Master") : tr ("Insert {0}", { juce::String (m) }); };
  9200. const auto named = [&u8] (const std::string& name) { return name.empty() ? juce::String() : " (" + u8 (name) + ")"; };
  9201. const auto bullet = juce::String::fromUTF8 ("\xe2\x80\xa2 ");
  9202. juce::StringArray lines;
  9203. for (const auto& c : report.changes)
  9204. {
  9205. juce::String line;
  9206. switch (c.kind)
  9207. {
  9208. case Kind::linkTrack:
  9209. line = tr ("Track {0} is linked to insert {0}", { juce::String (c.to) });
  9210. if (! c.name.empty())
  9211. line += " (" + u8 (c.name) + ")";
  9212. break;
  9213. case Kind::moveInsert:
  9214. line = tr ("{0}{1} moves to insert {2}, with its effects and routing", { insert (c.from), named (c.name), juce::String (c.to) });
  9215. break;
  9216. case Kind::routeInsert:
  9217. line = tr ("{0}{1} sends into insert {2} instead of the Master", { insert (c.from), named (c.name), juce::String (c.to) });
  9218. break;
  9219. case Kind::routeChannel:
  9220. line = tr ("{0}: {1} → insert {2}", { u8 (c.name), insert (c.from), juce::String (c.to) });
  9221. if (c.changesSound)
  9222. line += " " + tr ("(its sound changes: the effects or settings of the insert it leaves or joins apply)");
  9223. break;
  9224. }
  9225. lines.add (bullet + line);
  9226. }
  9227. for (const auto& [track, home] : report.repeats)
  9228. lines.add (bullet + tr ("Track {0} only repeats Track {1}'s instruments: it stays unlinked and plays through insert {1}",
  9229. { juce::String (track + 1), juce::String (home + 1) }));
  9230. constexpr int shown = 24;
  9231. if (lines.size() > shown)
  9232. {
  9233. const auto more = lines.size() - shown;
  9234. lines.removeRange (shown, more);
  9235. lines.add (tr ("...and {0} more", { juce::String (more) }));
  9236. }
  9237. juce::ignoreUnused (song);
  9238. return tr ("Playlist track N becomes mixer insert N: what a track's own instruments and samples play goes through its "
  9239. "insert, and its header's M, S, volume and pan are the insert's. This changes:")
  9240. + "\n\n" + lines.joinIntoString ("\n") + "\n\n" + tr ("It is one step: Edit › Undo takes it all back.");
  9241. }
  9242. void PlaylistComponent::switchLinkTracks (AudioEngine& engine, bool on, std::function<void (bool)> done)
  9243. {
  9244. const auto apply = [&engine, on, done] {
  9245. engine.editSong ([on] (Song& s) { autolink::setOn (s, on); });
  9246. if (done != nullptr)
  9247. done (true);
  9248. };
  9249. if (! on)
  9250. {
  9251. apply();
  9252. return;
  9253. }
  9254. // issue #170: switching on can move inserts and route channels; it says what first
  9255. const auto plan = autolink::planOn (engine.getSong());
  9256. if (! plan.changesRouting() && plan.repeats.empty())
  9257. {
  9258. apply();
  9259. return;
  9260. }
  9261. if (answerLinkConfirmation != nullptr)
  9262. {
  9263. if (answerLinkConfirmation (plan))
  9264. apply();
  9265. else if (done != nullptr)
  9266. done (false);
  9267. return;
  9268. }
  9269. juce::AlertWindow::showOkCancelBox (plan.changesSound() ? juce::MessageBoxIconType::WarningIcon : juce::MessageBoxIconType::QuestionIcon,
  9270. tr ("Link Playlist tracks to mixer tracks"), describeLinkPlan (engine.getSong(), plan), tr ("Link"),
  9271. tr ("Cancel"), nullptr, juce::ModalCallbackFunction::create ([apply, done] (int result) {
  9272. if (result == 1)
  9273. apply();
  9274. else if (done != nullptr)
  9275. done (false);
  9276. }));
  9277. }
  9278. // The Simple header's controls (round 184a; round 190jc, design190ia SG-3/SG-4, BandLab's header): one colour bar at the
  9279. // plate's left; M then S (24 x 20, radius 4) on the track's insert; on the second row the volume as a line in the track's
  9280. // colour with a round thumb, the pan knob and "+FX"
  9281. void PlaylistComponent::paintSimpleHeaderControls (juce::Graphics& g, int t, juce::Rectangle<float> plateArea, bool hovered)
  9282. {
  9283. using namespace theme;
  9284. const auto& song = engine.getSong();
  9285. const auto z = simpleSizes();
  9286. const auto trackColour = t < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) t].colour : 0u;
  9287. if (trackColour != 0)
  9288. {
  9289. g.setColour (juce::Colour (trackColour));
  9290. g.fillRoundedRectangle (plateArea.withWidth (4.0f).reduced (0.0f, 2.0f), 1.5f);
  9291. }
  9292. // round 190oo (CS-24): an FL track's header acts on the insert its clips play through (core/SimpleHeaderTarget.h);
  9293. // its M stays the Playlist track's mute, so a lit M always means this track is silent
  9294. const auto& target = headerTarget (t);
  9295. const auto insert = headerInsert (t);
  9296. const auto* m = insert > 0 ? &song.mixer[(std::size_t) insert] : nullptr;
  9297. const auto buttonFont = font (ui::simplelook::largeControls() ? type::body : type::small, true);
  9298. const auto button = [&g, &buttonFont] (juce::Rectangle<float> r, const char* text, bool on, juce::Colour onColour, bool lit) {
  9299. g.setColour (on ? onColour : (lit ? colour::bg6 : colour::bg4));
  9300. g.fillRoundedRectangle (r, radius::md);
  9301. g.setColour (on ? colour::bg0 : (lit ? colour::textPrimary : colour::textSecondary));
  9302. g.setFont (buttonFont);
  9303. g.drawText (text, r, juce::Justification::centred, false);
  9304. };
  9305. button (trackLed (t).toFloat(), "M", simplehdr::muteLit (song, t, target), colour::warning, hovered && hover.led);
  9306. if (const auto solo = trackSolo (t).toFloat(); ! solo.isEmpty() && m != nullptr)
  9307. button (solo, "S", m->solo, colour::info, hovered && hover.solo);
  9308. const auto bar = trackVolume (t).toFloat();
  9309. if (bar.isEmpty() || m == nullptr)
  9310. return;
  9311. // volume: a 4 px line, filled in the track's colour up to the fader, a tick at 0 dB and a round thumb
  9312. const auto lit = (hovered && hover.volume) || (levelDrag == 1 && levelInsert == insert);
  9313. const auto hue = trackColour != 0 ? juce::Colour (trackColour) : colour::accent;
  9314. const auto line = bar.withSizeKeepingCentre (bar.getWidth(), ui::simplelook::px (4.0f, 6.0f));
  9315. g.setColour (colour::bg0);
  9316. g.fillRoundedRectangle (line, line.getHeight() * 0.5f);
  9317. const auto at = line.getX() + line.getWidth() * juce::jlimit (0.0f, 1.0f, m->volume);
  9318. g.setColour (lit ? hue.brighter (0.25f) : hue);
  9319. g.fillRoundedRectangle (line.withRight (juce::jmax (line.getX() + line.getHeight(), at)), line.getHeight() * 0.5f);
  9320. g.setColour (colour::textSecondary.withAlpha (0.6f));
  9321. g.fillRect (juce::Rectangle<float> (bar.getX() + bar.getWidth() * unityFader - 0.5f, line.getY() - 3.0f, 1.0f, line.getHeight() + 6.0f));
  9322. const auto thumb = ui::simplelook::px (12.0f, 20.0f);
  9323. g.setColour (colour::bg0.withAlpha (0.5f)); // (a dark rim keeps the thumb apart from a light track colour)
  9324. g.fillEllipse (juce::Rectangle<float> (thumb + 2.0f, thumb + 2.0f).withCentre ({ at, line.getCentreY() }));
  9325. g.setColour (lit ? colour::onAccent : colour::textPrimary);
  9326. g.fillEllipse (juce::Rectangle<float> (thumb, thumb).withCentre ({ at, line.getCentreY() }));
  9327. // pan: a knob, its arc from the top
  9328. const auto pan = trackPan (t).toFloat();
  9329. const auto knob = pan.getWidth() * 0.5f - 1.5f;
  9330. g.setColour (colour::bg4);
  9331. g.fillEllipse (pan.reduced (1.0f));
  9332. juce::Path arc;
  9333. const auto angle = m->pan * 2.356f;
  9334. arc.addCentredArc (pan.getCentreX(), pan.getCentreY(), knob, knob, 0.0f, juce::jmin (0.0f, angle), juce::jmax (0.0f, angle), true);
  9335. g.setColour ((hovered && hover.pan) || (levelDrag == 2 && levelInsert == insert) ? colour::accentHover : colour::info);
  9336. g.strokePath (arc, juce::PathStrokeType (2.0f));
  9337. g.setColour (colour::textPrimary);
  9338. g.drawLine (pan.getCentreX(), pan.getCentreY(), pan.getCentreX() + (knob - 1.5f) * std::sin (angle), pan.getCentreY() - (knob - 1.5f) * std::cos (angle), 1.5f);
  9339. // "+FX", with the insert's effect count; with a chain preset BandLab's pill: "Fx <preset>" in the track's colour
  9340. // (round 190ld, DS-13: bandlab190p 11-sounds-free-loops.png, the Drum Machine track's purple "Fx Bass Boost")
  9341. if (const auto fx = trackFx (t).toFloat(); ! fx.isEmpty() && ! m->chainPreset.empty())
  9342. {
  9343. const auto fill = trackColour != 0 ? juce::Colour (trackColour) : colour::accent;
  9344. g.setColour (hovered && hover.fx ? fill.brighter (0.15f) : fill);
  9345. g.fillRoundedRectangle (fx, fx.getHeight() * 0.5f);
  9346. g.setColour (fill.getPerceivedBrightness() > 0.5f ? colour::bg0 : juce::Colours::white);
  9347. g.setFont (simpleFxFont());
  9348. g.drawText ("Fx " + simpleFxPreset (t), fx.reduced (fx.getHeight() * 0.5f, 0.0f), juce::Justification::centred, true);
  9349. }
  9350. else if (const auto fx = trackFx (t).toFloat(); ! fx.isEmpty())
  9351. {
  9352. const auto count = (int) m->effects.size();
  9353. g.setColour (hovered && hover.fx ? colour::bg6 : colour::bg4);
  9354. g.fillRoundedRectangle (fx, fx.getHeight() * 0.5f);
  9355. g.setColour (count > 0 ? colour::accentHover : colour::textSecondary);
  9356. g.setFont (buttonFont);
  9357. g.drawText (count > 0 ? "FX " + juce::String (count) : juce::String ("+ FX"), fx, juce::Justification::centred, false);
  9358. }
  9359. }
  9360. int PlaylistComponent::simpleTrackHeight() { return simpleSizes().row; }
  9361. int PlaylistComponent::simpleTwoRows() { return simpleSizes().twoRows; }
  9362. juce::Rectangle<int> PlaylistComponent::trackLed (int track) const
  9363. {
  9364. const auto h = heightOf (track);
  9365. if (simpleHeaders)
  9366. {
  9367. // the M button, in the first row (round 184a); round 190jc (SG-3): M then S, as BandLab, Live and most DAWs order
  9368. // them, so M sits left of the S place
  9369. const auto z = simpleSizes();
  9370. const auto height = juce::jmin (z.buttonHeight, h - 2);
  9371. return { headerWidth - 10 - rightColumn() - 2 * z.button - z.gap, trackToY (track) + juce::jmin (z.top, juce::jmax (0, h / 2 - height / 2)), z.button, height };
  9372. }
  9373. if (simpleInsert (track) > 0) // a linked header's M button (round 190gz): the first row, or centred on a short row
  9374. return { headerWidth - 22 - rightColumn() - insertsColumn(), trackToY (track) + (h >= linkedTwoRows ? 4 : juce::jmax (1, (h - 14) / 2)), 18,
  9375. juce::jmin (14, h - 2) };
  9376. if (liveHeaders()) // round 190jn: Live's activator, 46 x 13 with its frame, 2 px under the row's top (an expanded lane: at its top)
  9377. return { headerWidth - rightColumn() - 4 - 46, trackToY (track) + juce::jmin (2, juce::jmax (0, (h - 2 - 13) / 2)), 46, juce::jmin (13, h - 2) };
  9378. if (flHeaders() && h >= flTallHeader) // FL's tall track (round 190ig, FM-23): the LED at the bottom right
  9379. return { headerWidth - 16 - rightColumn(), trackToY (track) + h - 18, 12, 12 };
  9380. return { headerWidth - 17 - rightColumn(), trackToY (track) + h / 2 - 6, 12, 12 };
  9381. }
  9382. int PlaylistComponent::simpleInsert (int track) const
  9383. {
  9384. if (simpleHeaders)
  9385. return simpletracks::insertOf (engine.getSong(), track);
  9386. // round 190gz: a linked track's header acts on the same insert (an audio track's, an instrument track's channel's)
  9387. return linkedHeaders() ? simpletracks::insertOf (engine.getSong(), track) : -1;
  9388. }
  9389. // Round 190oo (CS-24): the Simple headers' targets, built once per published song (one pass over the clips; a level-only
  9390. // edit, as a volume drag, publishes no new count: the routing it reads cannot have changed)
  9391. const simplehdr::HeaderTarget& PlaylistComponent::headerTarget (int track) const
  9392. {
  9393. static const simplehdr::HeaderTarget none;
  9394. if (! simpleHeaders)
  9395. return none;
  9396. if (headerTargetStamp != engine.getPublishCount())
  9397. {
  9398. headerTargetList = simplehdr::headerTargets (engine.getSong());
  9399. headerTargetStamp = engine.getPublishCount();
  9400. }
  9401. return track >= 0 && track < (int) headerTargetList.size() ? headerTargetList[(std::size_t) track] : none;
  9402. }
  9403. int PlaylistComponent::headerInsert (int track) const
  9404. {
  9405. if (! simpleHeaders)
  9406. return simpleInsert (track); // (the linked headers: their own insert only)
  9407. const auto insert = headerTarget (track).insert;
  9408. return insert > 0 && insert < (int) engine.getSong().mixer.size() ? insert : -1;
  9409. }
  9410. // Round 190oo (CS-24): a small link mark left of M (and of an audio track's arm / input buttons) when the insert the
  9411. // header acts on also plays other tracks; pointing at it names them (hint bar)
  9412. juce::Rectangle<int> PlaylistComponent::trackSharedMark (int track) const
  9413. {
  9414. if (! simpleHeaders || noteedit::isFoldedAway (engine.getSong(), track))
  9415. return {};
  9416. if (const auto& target = headerTarget (track); target.insert <= 0 || target.sharedWith <= 0)
  9417. return {};
  9418. const auto led = trackLed (track);
  9419. auto leftmost = led.getX();
  9420. for (const auto& other : { trackArm (track), trackInput (track), trackArrow (track), trackAudition (track) })
  9421. if (! other.isEmpty() && other.getY() < led.getBottom() && other.getBottom() > led.getY())
  9422. leftmost = juce::jmin (leftmost, other.getX());
  9423. const auto size = juce::jmin (simpleSizes().icon, led.getHeight());
  9424. return { leftmost - 4 - size, led.getCentreY() - size / 2, size, size };
  9425. }
  9426. // Round 190rs (G-01, queue item 92): an unassigned Playlist track holds clips only, and each clip plays through its
  9427. // channels' mixer inserts, so the header hint says where the track's clips are heard (FL's hint bar shows the name only;
  9428. // the LYNX extra "Routing hints", on by default, text only)
  9429. juce::String PlaylistComponent::routeHintFor (const Song& song, int track)
  9430. {
  9431. const auto r = trackmodes::routeSummary (song, track);
  9432. if (! r.clips)
  9433. return tr ("(a lane for clips: they play through their channels' inserts)");
  9434. if (r.channels.empty())
  9435. return {};
  9436. if (r.channels.size() == 1)
  9437. {
  9438. const auto& ch = song.channels[(std::size_t) r.channels.front()];
  9439. const auto name = ch.name.empty() ? tr ("Channel {0}", { juce::String (r.channels.front() + 1) }) : juce::String::fromUTF8 (ch.name.c_str());
  9440. const auto t = r.inserts.front();
  9441. if (t == 0)
  9442. return tr ("plays {0} → Master", { name });
  9443. const auto own = t < (int) song.mixer.size() ? juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str()).trim() : juce::String();
  9444. return own.isEmpty() || own == "Insert " + juce::String (t) ? tr ("plays {0} → insert {1}", { name, juce::String (t) })
  9445. : tr ("plays {0} → insert {1} ({2})", { name, juce::String (t), own });
  9446. }
  9447. const auto count = juce::String ((int) r.channels.size());
  9448. if (r.inserts.size() == 1)
  9449. return r.inserts.front() == 0 ? tr ("plays {0} channels → Master", { count })
  9450. : tr ("plays {0} channels → insert {1}", { count, juce::String (r.inserts.front()) });
  9451. juce::StringArray list;
  9452. for (const auto t : r.inserts)
  9453. {
  9454. if (list.size() == 8)
  9455. {
  9456. list.add ("...");
  9457. break;
  9458. }
  9459. list.add (t == 0 ? tr ("Master") : juce::String (t));
  9460. }
  9461. return tr ("plays {0} channels → inserts {1}", { count, list.joinIntoString (", ") });
  9462. }
  9463. bool PlaylistComponent::linkedHeaders() const
  9464. {
  9465. return ! simpleHeaders && engine.getSong().linkTracksToMixer;
  9466. }
  9467. void PlaylistComponent::updateHeaderWidth()
  9468. {
  9469. // (round 190ig, FM-23: FL's 98 px header plates + the 8 px selection / activity column in the Pattern layout;
  9470. // round 190ht, issue #154: the linked headers' inserts column)
  9471. const auto base = simpleHeaders ? (ui::simplelook::largeControls() ? simpleHeaderWidthLarge : simpleHeaderWidth) : linkedHeaders() ? linkedHeaderWidth + insertsColumn()
  9472. : liveHeaders() ? liveHeaderWidth : flHeaderWidthNow();
  9473. headerBaseWidth = base;
  9474. // round 190jq (issue #164, LYNX extra): the width dragged at the column's right edge (FL's own width by default; Simple
  9475. // and Live's measured header keep theirs)
  9476. const auto width = simpleHeaders || liveHeaders() ? base : headerwidth::widthOf (base);
  9477. if (width == headerWidth)
  9478. return;
  9479. headerWidth = width;
  9480. hover = {};
  9481. resized();
  9482. repaint();
  9483. }
  9484. juce::Rectangle<int> PlaylistComponent::trackSolo (int track) const
  9485. {
  9486. if (headerInsert (track) < 0 || noteedit::isFoldedAway (engine.getSong(), track)) // (round 190oo CS-24: an FL track's too)
  9487. return {};
  9488. if (simpleHeaders) // (round 190jc: right of M)
  9489. return trackLed (track).translated (simpleSizes().button + simpleSizes().gap, 0);
  9490. return trackLed (track).translated (-20, 0);
  9491. }
  9492. juce::Rectangle<int> PlaylistComponent::trackVolume (int track) const
  9493. {
  9494. const auto h = heightOf (track);
  9495. if (headerInsert (track) < 0 || h < (simpleHeaders ? simpleTwoRows() : linkedTwoRows) || noteedit::isFoldedAway (engine.getSong(), track))
  9496. return {};
  9497. if (simpleHeaders)
  9498. {
  9499. // round 190jc (SG-3): the volume line from the name's left to the pan knob, the "+FX" pill at the plate's right
  9500. const auto z = simpleSizes();
  9501. const auto right = headerWidth - rightColumn() - 10 - simpleFxWidth (track) - 8 - z.knob - 10;
  9502. return { 12, trackToY (track) + h - 6 - z.volumeHit, juce::jmax (20, right - 12), z.volumeHit };
  9503. }
  9504. // a linked header (round 190gz): the bar under the first row, the pan knob at its right (Logic / Bitwig's compact row)
  9505. const auto& song = engine.getSong();
  9506. const auto left = headerIndent (song, track);
  9507. // (rollup 0.1.28: between 190gw's lock strip, the header's first 10 px, and its selection strip at the right edge)
  9508. const auto x = juce::jmax (left + 6, trackhdr::lockStripWidth + 1);
  9509. return { x, trackToY (track) + 20, headerWidth - rightColumn() - insertsColumn() - x - 26, 12 };
  9510. }
  9511. juce::Rectangle<int> PlaylistComponent::trackPan (int track) const
  9512. {
  9513. const auto v = trackVolume (track);
  9514. if (v.isEmpty())
  9515. return {};
  9516. if (simpleHeaders)
  9517. {
  9518. const auto knob = simpleSizes().knob;
  9519. return { v.getRight() + 10, v.getCentreY() - knob / 2, knob, knob };
  9520. }
  9521. return { v.getRight() + 6, v.getCentreY() - 7, 14, 14 };
  9522. }
  9523. juce::Rectangle<int> PlaylistComponent::trackFx (int track) const
  9524. {
  9525. const auto v = trackVolume (track);
  9526. if (v.isEmpty() || ! simpleHeaders)
  9527. return {};
  9528. const auto z = simpleSizes();
  9529. return { trackPan (track).getRight() + 8, v.getCentreY() - z.fxHeight / 2, simpleFxWidth (track), z.fxHeight };
  9530. }
  9531. juce::Font PlaylistComponent::simpleFxFont()
  9532. {
  9533. return theme::font (ui::simplelook::largeControls() ? theme::type::body : theme::type::small, true);
  9534. }
  9535. // round 190ld (details DS-13, BandLab B11 "Fx Bass Boost"): the insert's chain preset, "" = none
  9536. juce::String PlaylistComponent::simpleFxPreset (int track) const
  9537. {
  9538. const auto insert = headerInsert (track); // (round 190oo CS-24: an FL track's borrowed insert too)
  9539. const auto& song = engine.getSong();
  9540. return insert > 0 && insert < (int) song.mixer.size() ? juce::String::fromUTF8 (song.mixer[(std::size_t) insert].chainPreset.c_str()) : juce::String();
  9541. }
  9542. // The Fx pill's width: "+ FX" / "FX n" in the usual pill; with a chain preset BandLab's "Fx <preset>" pill, as wide as
  9543. // its name needs (at most 2.6 pills, the volume line gives the room; the name is cut with "..." beyond that)
  9544. int PlaylistComponent::simpleFxWidth (int track) const
  9545. {
  9546. const auto z = simpleSizes();
  9547. const auto preset = simpleFxPreset (track);
  9548. if (preset.isEmpty())
  9549. return z.fxWidth;
  9550. const auto text = juce::GlyphArrangement::getStringWidthInt (simpleFxFont(), "Fx " + preset);
  9551. return juce::jlimit (z.fxWidth, juce::roundToInt ((float) z.fxWidth * 2.6f), text + z.fxHeight);
  9552. }
  9553. // --- issue #154 (round 190ht): the insert effects column of the linked headers -------------------------------------
  9554. int PlaylistComponent::insertsColumn() const
  9555. {
  9556. return showTrackInserts && linkedHeaders() ? insertsColumnWidth : 0;
  9557. }
  9558. juce::Rectangle<int> PlaylistComponent::trackInserts (int track) const
  9559. {
  9560. if (insertsColumn() == 0 || simpleInsert (track) <= 0 || noteedit::isFoldedAway (engine.getSong(), track))
  9561. return {};
  9562. const auto h = heightOf (track) - 5;
  9563. if (trackinserts::rowsThatFit (h) == 0)
  9564. return {};
  9565. return { headerWidth - rightColumn() - insertsColumnWidth + 1, trackToY (track) + 2, insertsColumnWidth - 4, h };
  9566. }
  9567. int PlaylistComponent::insertsFirst (int track) const
  9568. {
  9569. const auto insert = simpleInsert (track);
  9570. const auto found = insertsScroll.find (insert);
  9571. const auto effects = insert > 0 ? (int) engine.getSong().mixer[(std::size_t) insert].effects.size() : 0;
  9572. return trackinserts::clampFirst (found == insertsScroll.end() ? 0 : found->second, effects, trackinserts::rowsThatFit (trackInserts (track).getHeight()));
  9573. }
  9574. int PlaylistComponent::insertsItemAt (int track, juce::Point<int> p) const
  9575. {
  9576. const auto box = trackInserts (track);
  9577. if (! box.contains (p))
  9578. return -1;
  9579. const auto effects = (int) engine.getSong().mixer[(std::size_t) simpleInsert (track)].effects.size();
  9580. return trackinserts::itemAt (effects, insertsFirst (track), trackinserts::rowsThatFit (box.getHeight()), p.y - box.getY());
  9581. }
  9582. void PlaylistComponent::paintInserts (juce::Graphics& g, int track, bool hovered)
  9583. {
  9584. using namespace theme;
  9585. const auto box = trackInserts (track);
  9586. if (box.isEmpty())
  9587. return;
  9588. const auto& song = engine.getSong();
  9589. const auto insert = simpleInsert (track);
  9590. const auto& fx = song.mixer[(std::size_t) insert].effects;
  9591. const auto effects = (int) fx.size();
  9592. const auto rows = trackinserts::rowsThatFit (box.getHeight());
  9593. const auto first = insertsFirst (track);
  9594. // a recessed well, as the Mixer's slot list; one row per effect in chain order, then "+" while a slot is free
  9595. g.setColour (colour::bg1.withAlpha (0.85f));
  9596. g.fillRoundedRectangle (box.toFloat(), radius::sm);
  9597. g.setFont (font (type::caption));
  9598. for (int r = 0; r < rows; ++r)
  9599. {
  9600. const auto item = first + r;
  9601. if (item > effects || (item == effects && effects >= maxEffectSlots))
  9602. break;
  9603. const auto row = juce::Rectangle<int> (box.getX() + 1, box.getY() + r * trackinserts::rowHeight, box.getWidth() - 2, trackinserts::rowHeight);
  9604. const auto isAdd = item == effects;
  9605. const auto under = hovered && hover.insertItem == (isAdd ? trackinserts::addRow : item);
  9606. const auto dragged = insertsDragging && insertsPressTrack == track && insertsPressItem == item;
  9607. if (under || dragged)
  9608. {
  9609. g.setColour (colour::bg5.withAlpha (dragged ? 0.9f : 0.6f));
  9610. g.fillRoundedRectangle (row.toFloat().reduced (0.0f, 0.5f), 2.0f);
  9611. }
  9612. if (isAdd)
  9613. {
  9614. g.setColour (under ? colour::textPrimary : colour::textSecondary.withAlpha (0.8f));
  9615. g.drawText ("+", row.withWidth (trackinserts::ledWidth), juce::Justification::centred, false);
  9616. g.drawText (tr ("Add"), row.withTrimmedLeft (trackinserts::ledWidth + 1), juce::Justification::centredLeft, false);
  9617. continue;
  9618. }
  9619. const auto& slot = fx[(std::size_t) item];
  9620. // the on/off dot (the Mixer slot's LED): filled while on, a ring while bypassed
  9621. const auto dot = row.withWidth (trackinserts::ledWidth).toFloat().withSizeKeepingCentre (6.0f, 6.0f);
  9622. if (slot.enabled)
  9623. {
  9624. g.setColour (hovered && hover.insertItem == item && hover.insertLed ? colour::accentHover : colour::accent);
  9625. g.fillEllipse (dot);
  9626. }
  9627. else
  9628. {
  9629. g.setColour (hovered && hover.insertItem == item && hover.insertLed ? colour::textPrimary : colour::textSecondary.withAlpha (0.7f));
  9630. g.drawEllipse (dot.reduced (0.5f), 1.0f);
  9631. }
  9632. g.setColour (slot.enabled ? colour::textPrimary : colour::textSecondary.withAlpha (0.6f));
  9633. textcache::drawText (g, quickpick::slotName (engine, slot), row.withTrimmedLeft (trackinserts::ledWidth + 1).withTrimmedRight (2),
  9634. juce::Justification::centredLeft, true);
  9635. }
  9636. // more rows than fit: a thin scroll mark at the right edge
  9637. if (const auto items = trackinserts::itemCount (effects); items > rows)
  9638. {
  9639. const auto h = juce::jmax (4.0f, (float) box.getHeight() * (float) rows / (float) items);
  9640. const auto y = (float) box.getY() + ((float) box.getHeight() - h) * (float) first / (float) juce::jmax (1, items - rows);
  9641. g.setColour (colour::textSecondary.withAlpha (0.5f));
  9642. g.fillRoundedRectangle (juce::Rectangle<float> ((float) box.getRight() - 2.5f, y, 2.0f, h), 1.0f);
  9643. }
  9644. // a drag in progress: where the effect lands
  9645. if (insertsDragging && insertsDropTrack == track && insertsDropAt >= 0)
  9646. {
  9647. const auto y = box.getY() + (insertsDropAt - first) * trackinserts::rowHeight;
  9648. if (y >= box.getY() - 1 && y <= box.getBottom() + 1)
  9649. {
  9650. g.setColour (colour::accent);
  9651. g.fillRect (box.getX() + 2, juce::jlimit (box.getY(), box.getBottom() - 2, y - 1), box.getWidth() - 4, 2);
  9652. }
  9653. }
  9654. }
  9655. EffectsPanel& PlaylistComponent::insertActions (int insert)
  9656. {
  9657. if (insertActionsPanel == nullptr)
  9658. {
  9659. insertActionsPanel = std::make_unique<EffectsPanel> (engine); // never shown: the Mixer slot's own code
  9660. insertActionsPanel->setMenuTarget (this);
  9661. }
  9662. insertActionsPanel->setTrack (insert);
  9663. return *insertActionsPanel;
  9664. }
  9665. bool PlaylistComponent::insertsMouseDown (const juce::MouseEvent& e)
  9666. {
  9667. if (e.x >= headerWidth || e.y < tracksTop() || e.y >= gridArea().getBottom())
  9668. return false;
  9669. const auto track = yToTrack (e.y);
  9670. if (! trackInserts (track).contains (e.getPosition()))
  9671. return false;
  9672. const auto insert = simpleInsert (track);
  9673. const auto item = insertsItemAt (track, e.getPosition());
  9674. insertsPressTrack = insertsPressItem = insertsDropTrack = insertsDropAt = -1;
  9675. insertsDragging = false;
  9676. if (flmods::popup (e.mods))
  9677. {
  9678. // the Mixer slot's own menu; on "+" or below the list, the slot's add menu
  9679. auto& actions = insertActions (insert);
  9680. if (item >= 0)
  9681. actions.showSlotMenuFor (item);
  9682. else if (engine.getSong().mixer[(std::size_t) insert].effects.size() < (std::size_t) maxEffectSlots)
  9683. actions.showAddMenuFor (trackinserts::nextFreeRow (engine.getSong().mixer[(std::size_t) insert].effects));
  9684. return true;
  9685. }
  9686. if (e.getNumberOfClicks() > 1)
  9687. return true; // (a double click opens nothing twice)
  9688. insertsPressTrack = track;
  9689. insertsPressItem = item;
  9690. return true;
  9691. }
  9692. bool PlaylistComponent::insertsAddSearch (juce::Point<int> p)
  9693. {
  9694. if (p.x >= headerWidth || p.y < tracksTop() || p.y >= gridArea().getBottom())
  9695. return false;
  9696. const auto track = yToTrack (p.y);
  9697. if (! trackInserts (track).contains (p) || insertsItemAt (track, p) != trackinserts::addRow)
  9698. return false;
  9699. const auto insert = simpleInsert (track);
  9700. if (insert <= 0)
  9701. return false;
  9702. insertActions (insert).showSlotSearch (trackinserts::nextFreeRow (engine.getSong().mixer[(std::size_t) insert].effects));
  9703. return true;
  9704. }
  9705. bool PlaylistComponent::insertsMouseDrag (const juce::MouseEvent& e)
  9706. {
  9707. if (insertsPressTrack < 0)
  9708. return false;
  9709. if (insertsPressItem >= 0 && (insertsDragging || e.getDistanceFromDragStart() > 4))
  9710. {
  9711. // drag an effect: up / down in its list reorders it, onto another linked track's list moves it there (Ctrl: a copy)
  9712. insertsDragging = true;
  9713. const auto over = e.y >= tracksTop() && e.y < gridArea().getBottom() ? yToTrack (e.y) : -1;
  9714. const auto box = over >= 0 ? trackInserts (over) : juce::Rectangle<int>();
  9715. if (! box.isEmpty() && e.x < headerWidth && e.y >= box.getY() - trackinserts::rowHeight && e.y < box.getBottom() + trackinserts::rowHeight)
  9716. {
  9717. const auto effects = (int) engine.getSong().mixer[(std::size_t) simpleInsert (over)].effects.size();
  9718. insertsDropTrack = over;
  9719. insertsDropAt = over == insertsPressTrack
  9720. ? trackinserts::dropPosition (effects, insertsFirst (over), trackinserts::rowsThatFit (box.getHeight()), e.y - box.getY())
  9721. : effects;
  9722. }
  9723. else
  9724. insertsDropTrack = insertsDropAt = -1;
  9725. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  9726. }
  9727. return true;
  9728. }
  9729. bool PlaylistComponent::insertsMouseUp (const juce::MouseEvent& e)
  9730. {
  9731. if (insertsPressTrack < 0)
  9732. return false;
  9733. const auto track = insertsPressTrack, item = insertsPressItem, dropTrack = insertsDropTrack, dropAt = insertsDropAt;
  9734. const auto dragged = insertsDragging;
  9735. insertsPressTrack = insertsPressItem = insertsDropTrack = insertsDropAt = -1;
  9736. insertsDragging = false;
  9737. const auto insert = simpleInsert (track);
  9738. if (insert <= 0)
  9739. return true;
  9740. const auto copy = flmods::ctrl (e.mods);
  9741. if (dragged)
  9742. {
  9743. const auto target = dropTrack >= 0 && item >= 0 ? simpleInsert (dropTrack) : -1; // (outside a list: nothing changes)
  9744. if (target > 0 && target != insert)
  9745. {
  9746. auto moved = -1;
  9747. engine.editSongStructural ([insert, item, target, copy, &moved] (Song& s) { moved = detailchain::moveEffectToInsert (s, insert, item, target, copy); });
  9748. if (moved < 0)
  9749. ui::postHint ({ tr ("This insert has no free slot ({0} effects)", { juce::String (maxEffectSlots) }), {} }, 3000);
  9750. }
  9751. else if (target == insert && copy)
  9752. {
  9753. if (engine.getSong().mixer[(std::size_t) insert].effects.size() >= (std::size_t) maxEffectSlots)
  9754. ui::postHint ({ tr ("This insert has no free slot ({0} effects)", { juce::String (maxEffectSlots) }), {} }, 3000);
  9755. else
  9756. engine.editSong ([insert, item, dropAt] (Song& s) { detailchain::duplicateEffect (s, insert, item, dropAt); });
  9757. }
  9758. else if (target == insert)
  9759. engine.editSongStructural ([insert, item, dropAt] (Song& s) { detailchain::moveEffectBefore (s, insert, item, dropAt); });
  9760. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  9761. return true;
  9762. }
  9763. if (item == trackinserts::addRow)
  9764. {
  9765. const auto row = trackinserts::nextFreeRow (engine.getSong().mixer[(std::size_t) insert].effects);
  9766. auto& actions = insertActions (insert);
  9767. // issue #206 follow-up (round 190qb): a second press on the menu soon after is a double-click: the effect search
  9768. if (! e.mods.isAnyModifierKeyDown())
  9769. actions.armSlotSearchOnSecondClick (e, row);
  9770. actions.showAddMenuFor (row);
  9771. return true;
  9772. }
  9773. if (item < 0)
  9774. return true;
  9775. const auto row = trackInserts (track);
  9776. if (e.getMouseDownX() < row.getX() + trackinserts::ledWidth + 1)
  9777. {
  9778. // the dot: the effect on / off (the Mixer slot LED's edit)
  9779. engine.editSong ([insert, item] (Song& s) {
  9780. auto& fx = s.mixer[(std::size_t) insert].effects;
  9781. if (item < (int) fx.size())
  9782. fx[(std::size_t) item].enabled = ! fx[(std::size_t) item].enabled;
  9783. });
  9784. return true;
  9785. }
  9786. insertActions (insert).toggleSlotEditor (item); // the name: its window (as a click on a Mixer slot)
  9787. return true;
  9788. }
  9789. bool PlaylistComponent::insertsWheel (const juce::MouseEvent& e, float deltaY)
  9790. {
  9791. if (e.x >= headerWidth || e.y < tracksTop() || deltaY == 0.0f)
  9792. return false;
  9793. const auto track = yToTrack (e.y);
  9794. const auto box = trackInserts (track);
  9795. if (! box.contains (e.getPosition()))
  9796. return false;
  9797. const auto insert = simpleInsert (track);
  9798. const auto effects = (int) engine.getSong().mixer[(std::size_t) insert].effects.size();
  9799. const auto rows = trackinserts::rowsThatFit (box.getHeight());
  9800. if (trackinserts::itemCount (effects) <= rows)
  9801. return false; // everything shows: the wheel scrolls the Playlist as usual
  9802. insertsScroll[insert] = trackinserts::clampFirst (insertsFirst (track) + (deltaY > 0 ? -1 : 1), effects, rows);
  9803. repaint (box);
  9804. return true;
  9805. }
  9806. bool PlaylistComponent::insertsDrop (int track, juce::Point<int> p, EffectSlot fx)
  9807. {
  9808. const auto box = trackInserts (track);
  9809. if (! box.contains (p))
  9810. return false;
  9811. const auto insert = simpleInsert (track);
  9812. const auto effects = (int) engine.getSong().mixer[(std::size_t) insert].effects.size();
  9813. if (effects >= maxEffectSlots)
  9814. {
  9815. ui::postHint ({ tr ("This insert has no free slot ({0} effects)", { juce::String (maxEffectSlots) }), {} }, 3000);
  9816. return true;
  9817. }
  9818. // between the rows it is dropped on (the Device View's drop), not in place of one
  9819. const auto position = trackinserts::dropPosition (effects, insertsFirst (track), trackinserts::rowsThatFit (box.getHeight()), p.y - box.getY());
  9820. auto added = -1;
  9821. engine.editSong ([insert, position, &added, fx = std::move (fx)] (Song& s) mutable {
  9822. added = detailchain::insertEffectAt (s, insert, std::move (fx), position);
  9823. if (added >= 0)
  9824. mixerops::linkAddedSidechain (s, insert, added); // (as the Mixer's add)
  9825. });
  9826. if (added >= 0)
  9827. if (const auto& list = engine.getSong().mixer[(std::size_t) insert].effects; added < (int) list.size() && list[(std::size_t) added].kind == EffectKind::plugin)
  9828. insertActions (insert).toggleSlotEditor (added); // (a plugin opens its window when added, as in the Mixer)
  9829. return true;
  9830. }
  9831. void PlaylistComponent::setSimpleHeaders (bool on)
  9832. {
  9833. if (on == simpleHeaders)
  9834. return;
  9835. simpleHeaders = on;
  9836. hover = {};
  9837. headerWidth = -1; // (always laid out again)
  9838. updateHeaderWidth();
  9839. refreshTrackLayout(); // (round 190jq: no automation lanes in Simple)
  9840. sectionsLaneChanged(); // (round 190ol: the lane's look and visibility follow the layout)
  9841. chordLaneChanged(); // (round 190pf)
  9842. }
  9843. int PlaylistComponent::simpleInstrumentChannel (int track) const
  9844. {
  9845. const auto& song = engine.getSong();
  9846. const auto kind = simpletracks::kindOf (song, track);
  9847. if (! kind || (*kind != simpletracks::Kind::instrument && *kind != simpletracks::Kind::drums && *kind != simpletracks::Kind::sampler))
  9848. return -1;
  9849. if (*kind != simpletracks::Kind::drums)
  9850. {
  9851. const auto c = song.playlistTracks[(std::size_t) track].channel;
  9852. return c >= 0 && c < (int) song.channels.size() ? c : -1;
  9853. }
  9854. const auto insert = simpletracks::insertOf (song, track);
  9855. for (int c = 0; c < (int) song.channels.size(); ++c)
  9856. if (song.channels[(std::size_t) c].mixerTrack == insert && song.channels[(std::size_t) c].instrument != InstrumentKind::audioClip)
  9857. return c;
  9858. return -1;
  9859. }
  9860. void PlaylistComponent::selectTrackChannel (int track)
  9861. {
  9862. if (onSimpleTrackSelected)
  9863. onSimpleTrackSelected (track);
  9864. const auto& song = engine.getSong();
  9865. const auto kind = simpletracks::kindOf (song, track);
  9866. if (! kind)
  9867. return;
  9868. int channel = -1;
  9869. if (*kind == simpletracks::Kind::instrument || *kind == simpletracks::Kind::sampler)
  9870. channel = song.playlistTracks[(std::size_t) track].channel;
  9871. else if (*kind == simpletracks::Kind::drums)
  9872. {
  9873. const auto insert = simpletracks::insertOf (song, track);
  9874. for (int c = 0; c < (int) song.channels.size() && channel < 0; ++c)
  9875. if (song.channels[(std::size_t) c].mixerTrack == insert && song.channels[(std::size_t) c].instrument != InstrumentKind::audioClip)
  9876. channel = c;
  9877. }
  9878. if (channel >= 0 && channel != engine.getSelectedChannel())
  9879. engine.setSelectedChannel (channel);
  9880. }
  9881. void PlaylistComponent::selectTracks (const std::vector<int>& tracks)
  9882. {
  9883. std::vector<int> valid;
  9884. for (auto t : tracks)
  9885. if (t >= 0 && t < numTracks() && std::find (valid.begin(), valid.end(), t) == valid.end())
  9886. valid.push_back (t);
  9887. if (valid.empty())
  9888. return;
  9889. selectTrack (valid.front());
  9890. selectedTracks = valid;
  9891. repaint();
  9892. }
  9893. void PlaylistComponent::selectTrack (int track)
  9894. {
  9895. if (track < 0)
  9896. return;
  9897. track = juce::jmin (track, juce::jmax (0, numTracks() - 1));
  9898. selectedTracks = { track };
  9899. currentTrack = track;
  9900. if (simpleHeaders)
  9901. selectTrackChannel (track);
  9902. // into view (vertically)
  9903. const auto grid = gridArea();
  9904. const auto top = trackToY (track), bottom = top + heightOf (track);
  9905. if (top < grid.getY() || bottom > grid.getBottom())
  9906. {
  9907. scrollY = juce::jmax (0, scrollY + (top < grid.getY() ? top - grid.getY() : bottom - grid.getBottom()));
  9908. updateScrollBars();
  9909. }
  9910. repaint();
  9911. }
  9912. int PlaylistComponent::dropLaneTrack() const
  9913. {
  9914. return simpleHeaders ? simpletracks::nextEmptyTrack (engine.getSong()) : -1;
  9915. }
  9916. int PlaylistComponent::paintedRows() const
  9917. {
  9918. return simpleHeaders ? simpletracks::rowsShown (engine.getSong(), numTracks()) : numTracks();
  9919. }
  9920. bool PlaylistComponent::dropLaneShown() const
  9921. {
  9922. // round 190qu (Discord 11-24): the strip and its "+" are for starting a song; once there is a track only on request
  9923. return dropLaneTrack() >= 0 && (simpletracks::dropStripAlways || ! simpletracks::anyTrack (engine.getSong()));
  9924. }
  9925. juce::Rectangle<int> PlaylistComponent::simpleAddButton() const
  9926. {
  9927. const auto lane = dropLaneTrack();
  9928. if (lane < 0 || ! dropLaneShown())
  9929. return {};
  9930. const auto size = juce::jmin (simpleSizes().add, heightOf (lane) - 6);
  9931. return juce::Rectangle<int> (size, size).withCentre ({ (headerWidth - rightColumn()) / 2, trackToY (lane) + heightOf (lane) / 2 });
  9932. }
  9933. juce::Rectangle<int> PlaylistComponent::dropLaneArea() const
  9934. {
  9935. const auto lane = dropLaneTrack();
  9936. if (lane < 0)
  9937. return {};
  9938. const auto grid = gridArea();
  9939. return juce::Rectangle<int> (grid.getX(), trackToY (lane), grid.getWidth(), heightOf (lane)).getIntersection (grid);
  9940. }
  9941. void PlaylistComponent::simpleLookChanged()
  9942. {
  9943. if (! simpleHeaders)
  9944. return;
  9945. hover = {};
  9946. headerWidth = -1; // (laid out again: the Large controls width)
  9947. updateHeaderWidth();
  9948. refreshTrackLayout();
  9949. updateScrollBars();
  9950. repaint();
  9951. }
  9952. void PlaylistComponent::updateDropLaneProbe()
  9953. {
  9954. const auto area = simpleHeaders ? dropLaneArea().reduced (6, 4) : juce::Rectangle<int>();
  9955. if (area != dropLaneProbe.getBounds())
  9956. dropLaneProbe.setBounds (area);
  9957. dropLaneProbe.setVisible (! area.isEmpty());
  9958. }
  9959. void PlaylistComponent::setDropLaneHot (bool hot)
  9960. {
  9961. if (hot == dropLaneHot)
  9962. return;
  9963. dropLaneHot = hot;
  9964. repaint (dropLaneArea()); // (only the lane: no timer, a repaint on enter and exit)
  9965. }
  9966. void PlaylistComponent::fileDragMove (const juce::StringArray& files, int x, int y)
  9967. {
  9968. setDropLaneHot (simpleHeaders && dropLaneArea().contains (x, y));
  9969. updateDropGhostForFiles (files, { x, y }); // (round 190jj: files from outside show the ghost too)
  9970. }
  9971. void PlaylistComponent::fileDragExit (const juce::StringArray&)
  9972. {
  9973. setDropLaneHot (false);
  9974. clearDropGhost();
  9975. }
  9976. void PlaylistComponent::itemDragMove (const SourceDetails& details)
  9977. {
  9978. updateDropGhost (details); // (round 190im)
  9979. // (round 190sa: a sound goes on a new track wherever it is dropped on the timeline: the lane lights for it)
  9980. setDropLaneHot (simpleHeaders && (dropLaneArea().contains (details.localPosition)
  9981. || (BrowserComponent::isGeneratorDrag (details) && gridArea().contains (details.localPosition))));
  9982. }
  9983. void PlaylistComponent::itemDragExit (const SourceDetails&)
  9984. {
  9985. clearDropGhost(); // (round 190im)
  9986. setDropLaneHot (false);
  9987. }
  9988. juce::Rectangle<int> PlaylistComponent::trackArrow (int track) const
  9989. {
  9990. if (! noteedit::isGroupHeader (engine.getSong(), track))
  9991. return {};
  9992. const auto solo = trackSolo (track);
  9993. // (the leftmost button: S left of the LED with FL's / the linked headers, M left of S on the Simple ones)
  9994. const auto led = solo.isEmpty() ? trackLed (track) : solo.getX() < trackLed (track).getX() ? solo : trackLed (track);
  9995. return { led.getX() - 15, led.getY() - 1, 13, led.getHeight() + 2 };
  9996. }
  9997. juce::Rectangle<int> PlaylistComponent::trackArm (int track) const
  9998. {
  9999. // FL's View › "Show controls on audio tracks" (round 190w) hides them all
  10000. if (! showAudioTrackControls || trackmodes::armableInsert (engine.getSong(), track) < 0 || noteedit::isFoldedAway (engine.getSong(), track))
  10001. return {};
  10002. if (simpleHeaders && simpletracks::kindOf (engine.getSong(), track) == simpletracks::Kind::drums)
  10003. return {}; // (a drum track is FL's audio track only to keep its insert: nothing to record on it)
  10004. const auto arrow = trackArrow (track);
  10005. const auto solo = trackSolo (track);
  10006. const auto led = solo.isEmpty() ? trackLed (track) : solo.getX() < trackLed (track).getX() ? solo : trackLed (track); // (leftmost)
  10007. if (simpleHeaders || simpleInsert (track) > 0) // (the Simple and the linked headers: beside the S button)
  10008. return { (arrow.isEmpty() ? led.getX() : arrow.getX()) - 17, led.getY() + (led.getHeight() - 12) / 2, 12, 12 };
  10009. return { (arrow.isEmpty() ? led.getX() : arrow.getX()) - 15, led.getY(), 12, 12 };
  10010. }
  10011. juce::Rectangle<int> PlaylistComponent::trackAudition (int track) const
  10012. {
  10013. const auto& song = engine.getSong();
  10014. if (noteedit::isFoldedAway (song, track) || ! comp::groupOf (song, track).isLane (track) || ! comp::isComp (song, comp::groupOf (song, track).comp))
  10015. return {};
  10016. // left of whatever else the row shows
  10017. auto left = trackLed (track);
  10018. for (const auto& other : { trackSolo (track), trackArrow (track), trackArm (track), trackInput (track) })
  10019. if (! other.isEmpty() && other.getX() < left.getX())
  10020. left = other;
  10021. return { left.getX() - 15, trackLed (track).getY(), 12, 12 };
  10022. }
  10023. juce::Rectangle<int> PlaylistComponent::trackInput (int track) const
  10024. {
  10025. const auto arm = trackArm (track);
  10026. if (arm.isEmpty() || heightOf (track) < inputButtonMinHeight)
  10027. return {};
  10028. return arm.translated (-15, 0);
  10029. }
  10030. bool PlaylistComponent::isTrackSelected (int track) const
  10031. {
  10032. // the selected tracks; with none (set elsewhere through currentTrack alone) the current one (round 190ft: a
  10033. // Ctrl+Shift+click can leave the clicked track out of the selection)
  10034. if (! selectedTracks.empty())
  10035. return std::find (selectedTracks.begin(), selectedTracks.end(), track) != selectedTracks.end();
  10036. return track == currentTrack;
  10037. }
  10038. std::vector<int> PlaylistComponent::sortedTrackSelection() const
  10039. {
  10040. auto sel = selectedTracks;
  10041. if (sel.empty() && currentTrack >= 0)
  10042. sel.push_back (currentTrack);
  10043. std::sort (sel.begin(), sel.end());
  10044. sel.erase (std::unique (sel.begin(), sel.end()), sel.end());
  10045. return sel;
  10046. }
  10047. void PlaylistComponent::selectClipsOnTracks (int fromTrack, int toTrack, bool add)
  10048. {
  10049. // FL's clip box started from a header (FUN_00e684e0 with the "from the header" flag): the whole song, the tracks
  10050. // from the press to the mouse
  10051. const auto lo = juce::jmin (fromTrack, toTrack), hi = juce::jmax (fromTrack, toTrack);
  10052. std::vector<int> chosen = add ? headerClipBase : std::vector<int> {};
  10053. const auto& song = engine.getSong();
  10054. for (int i = 0; i < (int) song.playlist.size(); ++i)
  10055. {
  10056. const auto& c = song.playlist[(std::size_t) i];
  10057. if (c.gridSlot >= 0 || c.track < lo || c.track > hi || noteedit::isFoldedAway (song, c.track))
  10058. continue;
  10059. if (std::find (chosen.begin(), chosen.end(), i) == chosen.end())
  10060. chosen.push_back (i);
  10061. }
  10062. setSelection (chosen);
  10063. }
  10064. void PlaylistComponent::followLinkedTrack (int track)
  10065. {
  10066. // FL FUN_012e3aa0 (selecting a track alone): an instrument track selects its channel; with the mixer showing, an
  10067. // audio track's linked mixer track or the instrument channel's mixer track becomes the mixer's current track
  10068. const auto& song = engine.getSong();
  10069. if (track < 0 || track >= (int) song.playlistTracks.size())
  10070. return;
  10071. const auto t = song.playlistTracks[(std::size_t) track];
  10072. int insert = -1;
  10073. if (t.mode == PlaylistTrackMode::instrument && t.channel >= 0 && t.channel < (int) song.channels.size())
  10074. {
  10075. if (engine.getSelectedChannel() != t.channel || engine.getSelectedChannels().size() != 1)
  10076. engine.setSelectedChannel (t.channel);
  10077. insert = engine.getSong().channels[(std::size_t) t.channel].mixerTrack;
  10078. }
  10079. else if (t.mode == PlaylistTrackMode::audio)
  10080. insert = t.mixerTrack;
  10081. if (insert > 0 && insert < (int) engine.getSong().mixer.size() && onLinkedMixerTrack)
  10082. onLinkedMixerTrack (insert);
  10083. chooseArrangementTrack (track);
  10084. }
  10085. void PlaylistComponent::chooseArrangementTrack (int track)
  10086. {
  10087. if (! onArrangementTrackChosen || track < 0 || track >= numTracks())
  10088. return;
  10089. if (projection.isChild (track)) // (an automation lane: its owner track)
  10090. track = projection.ownerOf (track);
  10091. if (track >= 0)
  10092. onArrangementTrackChosen (track);
  10093. }
  10094. std::vector<int> PlaylistComponent::bandTargets (int track) const
  10095. {
  10096. // FL FUN_012eafa0: a change made on a selected track is copied to the other selected tracks
  10097. auto sel = sortedTrackSelection();
  10098. if (sel.size() > 1 && std::binary_search (sel.begin(), sel.end(), track))
  10099. {
  10100. sel.erase (std::find (sel.begin(), sel.end(), track));
  10101. sel.insert (sel.begin(), track);
  10102. return sel;
  10103. }
  10104. return { track };
  10105. }
  10106. void PlaylistComponent::bandToggleLock (int track)
  10107. {
  10108. // FL: the locked size is negated (a row never locked gets 1 = the smallest), the selected tracks copy it (mask 0x10)
  10109. engine.editSong ([tracks = bandTargets (track)] (Song& s) {
  10110. for (auto t : tracks)
  10111. if ((int) s.playlistTracks.size() <= t)
  10112. s.playlistTracks.resize ((std::size_t) t + 1);
  10113. const auto value = trackhdr::flippedLock (s.playlistTracks[(std::size_t) tracks.front()].lockedHeight);
  10114. for (auto t : tracks)
  10115. s.playlistTracks[(std::size_t) t].lockedHeight = value;
  10116. });
  10117. refreshTrackLayout();
  10118. updateScrollBars();
  10119. repaint();
  10120. }
  10121. void PlaylistComponent::bandReset (int track)
  10122. {
  10123. // FL: size 1.0 and unlocked (−1), the selected tracks copy both (mask 0x90)
  10124. engine.editSong ([tracks = bandTargets (track)] (Song& s) {
  10125. for (auto t : tracks)
  10126. {
  10127. if ((int) s.playlistTracks.size() <= t)
  10128. s.playlistTracks.resize ((std::size_t) t + 1);
  10129. s.playlistTracks[(std::size_t) t].height = 0;
  10130. s.playlistTracks[(std::size_t) t].lockedHeight = -1;
  10131. }
  10132. });
  10133. refreshTrackLayout();
  10134. updateScrollBars();
  10135. repaint();
  10136. }
  10137. // FL's Delete of the selected tracks (round 190ri, FL 2026 live: "Are you sure you want to delete 3 selected tracks?" /
  10138. // "Selected tracks: 2-4" with their names, Ok / Cancel); one track goes at once, as before
  10139. void PlaylistComponent::deleteTracksAsked (std::vector<int> tracks)
  10140. {
  10141. const auto remove = [safe = juce::Component::SafePointer<PlaylistComponent> (this), tracks] {
  10142. if (safe == nullptr)
  10143. return;
  10144. safe->setSelection ({});
  10145. safe->selectedTracks.clear();
  10146. safe->engine.editSong ([tracks] (Song& s) {
  10147. for (auto it = tracks.rbegin(); it != tracks.rend(); ++it)
  10148. noteedit::removeTrack (s, *it);
  10149. });
  10150. };
  10151. if (tracks.size() < 2)
  10152. return remove();
  10153. juce::String names, ranges;
  10154. for (std::size_t i = 0; i < tracks.size(); ++i)
  10155. {
  10156. const auto t = tracks[i];
  10157. const auto& list = engine.getSong().playlistTracks;
  10158. names << "\n" << (t < (int) list.size() && ! list[(std::size_t) t].name.empty() ? juce::String::fromUTF8 (list[(std::size_t) t].name.c_str())
  10159. : tr ("Track {0}", { juce::String (t + 1) }));
  10160. if (i == 0 || tracks[i - 1] != t - 1)
  10161. {
  10162. auto j = i;
  10163. while (j + 1 < tracks.size() && tracks[j + 1] == tracks[j] + 1)
  10164. ++j;
  10165. ranges << (ranges.isEmpty() ? "" : ", ") << juce::String (t + 1) << (j > i ? "-" + juce::String (tracks[j] + 1) : juce::String());
  10166. }
  10167. }
  10168. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("Confirm"),
  10169. tr ("Are you sure you want to delete {0} selected tracks?", { juce::String ((int) tracks.size()) }) + "\n"
  10170. + tr ("Selected tracks: {0}", { ranges }) + "\n" + names,
  10171. tr ("OK"), tr ("Cancel"), this, juce::ModalCallbackFunction::create ([remove] (int r) { if (r != 0) remove(); }));
  10172. }
  10173. void PlaylistComponent::moveTracksBy (std::vector<int> tracks, int direction)
  10174. {
  10175. std::sort (tracks.begin(), tracks.end());
  10176. std::vector<int> after;
  10177. engine.editSong ([&tracks, direction, &after, count = numTracks()] (Song& s) { after = noteedit::moveTrackBlock (s, tracks, direction, count); });
  10178. if (selectedTracks.size() > 1 || ! after.empty())
  10179. selectedTracks = after;
  10180. refreshTrackLayout();
  10181. repaint();
  10182. }
  10183. std::vector<int> PlaylistComponent::tracksForMenu (int track) const
  10184. {
  10185. // the menu's track and, when it is one of them, the other selected tracks
  10186. if (! isTrackSelected (track) || selectedTracks.size() < 2)
  10187. return { track };
  10188. auto out = selectedTracks;
  10189. if (std::find (out.begin(), out.end(), track) == out.end())
  10190. out.push_back (track);
  10191. std::sort (out.begin(), out.end());
  10192. return out;
  10193. }
  10194. // A track's colour as "Rename and color" sets it (the Simple workflow's track also colours its insert and channel)
  10195. void PlaylistComponent::recolourTrack (Song& s, int track, std::uint32_t colour, bool simple)
  10196. {
  10197. if (track < 0)
  10198. return;
  10199. if ((int) s.playlistTracks.size() <= track)
  10200. s.playlistTracks.resize ((std::size_t) track + 1);
  10201. if (simple && simpletracks::kindOf (s, track).has_value())
  10202. simpletracks::recolour (s, track, colour);
  10203. else
  10204. s.playlistTracks[(std::size_t) track].colour = colour;
  10205. }
  10206. void PlaylistComponent::colourTracks (const std::vector<int>& tracks, std::uint32_t colour)
  10207. {
  10208. engine.editSong ([tracks, colour, simple = simpleHeaders] (Song& s) {
  10209. for (const auto t : tracks)
  10210. recolourTrack (s, t, colour, simple);
  10211. });
  10212. }
  10213. void PlaylistComponent::editTrack (int track, std::function<void (PlaylistTrack&)> change)
  10214. {
  10215. if (track < 0)
  10216. return;
  10217. engine.editSong ([track, change] (Song& s) {
  10218. if ((int) s.playlistTracks.size() <= track)
  10219. s.playlistTracks.resize ((std::size_t) track + 1);
  10220. change (s.playlistTracks[(std::size_t) track]);
  10221. });
  10222. }
  10223. // The track menu in FL's order (REA round 104): name and colour, size, grouping, its clips, insert / clone /
  10224. // delete, move; track modes and Consolidate since round 146a. FL items LYNX has no counterpart for (icons, performance
  10225. // settings, ghost notes) are left out.
  10226. void PlaylistComponent::showTrackMenu (int track)
  10227. {
  10228. buildTrackMenu (track).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  10229. }
  10230. juce::PopupMenu PlaylistComponent::buildTrackMenu (int track)
  10231. {
  10232. const auto& song = engine.getSong();
  10233. const auto count = numTracks();
  10234. const auto info = track < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) track] : PlaylistTrack {};
  10235. juce::PopupMenu menu;
  10236. ui::addItemHeader (menu, tr ("Playlist track"), ! info.name.empty() ? juce::String::fromUTF8 (info.name.c_str()) : tr ("Track {0}", { juce::String (track + 1) }),
  10237. info.colour != 0 ? juce::Colour (info.colour) : juce::Colour());
  10238. menu.addItem (theme::mnemonic (tr ("Rename, color and icon..."), 'R'), [this, track] { renameTrack (track); }); // (FL's text, round 190ng)
  10239. // (issue #201, round 190ll: a colour picked here goes to every selected track when this one is among them)
  10240. // round 190rs (G-15): FL 2026's "Change color..." opens the colour selector (one undo step for every selected track);
  10241. // LYNX's palette stays right under it as "Color palette" (add, never remove)
  10242. {
  10243. const auto mouse = juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1);
  10244. menu.addItem (tr ("Change color..."), [this, tracks = tracksForMenu (track), mouse, current = info.colour] {
  10245. ui::showColourPickerPopup (mouse, tr ("Change color..."), current != 0 ? juce::Colour (current) : juce::Colour (lynxPalette()[0]), {},
  10246. [this, tracks] (juce::Colour c) { colourTracks (tracks, c.getARGB()); }, {},
  10247. [this, tracks] { colourTracks (tracks, 0); });
  10248. });
  10249. menu.addSubMenu (tr ("Color palette"), ui::colourMenu (info.colour, [this, tracks = tracksForMenu (track)] (std::uint32_t colour) {
  10250. colourTracks (tracks, colour);
  10251. }, mouse));
  10252. }
  10253. menu.addItem (tr ("Random color"), [this, tracks = tracksForMenu (track)] {
  10254. // (FL 2026, round 190ri: each selected track its own random colour, one undo step)
  10255. const auto& palette = lynxPalette();
  10256. std::vector<std::uint32_t> colours;
  10257. for (std::size_t i = 0; i < tracks.size(); ++i)
  10258. colours.push_back (palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())]);
  10259. engine.editSong ([tracks, colours, simple = simpleHeaders] (Song& s) {
  10260. for (std::size_t i = 0; i < tracks.size(); ++i)
  10261. recolourTrack (s, tracks[i], colours[i], simple);
  10262. });
  10263. });
  10264. // FL's "Change icon" (EEPLTrackIconMenuClick, REA round 168h); LYNX's own icon set
  10265. menu.addItem (tr ("Change icon..."), [this, track, current = info.icon] {
  10266. ui::showTrackIconPicker (juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1), current, [this, track] (int icon) {
  10267. engine.editSong ([tracks = tracksForMenu (track), icon] (Song& s) {
  10268. for (const auto t : tracks)
  10269. {
  10270. if ((int) s.playlistTracks.size() <= t)
  10271. s.playlistTracks.resize ((std::size_t) t + 1);
  10272. s.playlistTracks[(std::size_t) t].icon = icon;
  10273. }
  10274. });
  10275. });
  10276. });
  10277. // FL's "Auto name" (EEPLTrackAutoNameMenuClick → FUN_012ef490, round 168f): the name and colour of what the track plays most
  10278. menu.addItem (theme::mnemonic (tr ("Auto name"), 'A'), [this, tracks = tracksForMenu (track)] {
  10279. engine.editSong ([tracks] (Song& s) {
  10280. for (const auto t : tracks)
  10281. pltracks::autoName (s, t);
  10282. });
  10283. });
  10284. // FL's "Auto name clips" (round 190mp, DE-127; EEPLTrackAutoNameChildMenuClick, capture 190mp A1): after "Auto name"
  10285. menu.addItem (tr ("Auto name clips"), [this, track, tracks = tracksForMenu (track)] { autoNameClipsFromMenu (track, tracks); });
  10286. menu.addItem (tr ("Reset"), [this, tracks = tracksForMenu (track)] { // (FL 2026: every selected track, round 190ri)
  10287. engine.editSong ([tracks] (Song& s) {
  10288. for (const auto track : tracks)
  10289. {
  10290. if ((int) s.playlistTracks.size() <= track)
  10291. s.playlistTracks.resize ((std::size_t) track + 1);
  10292. auto& t = s.playlistTracks[(std::size_t) track];
  10293. t.name.clear();
  10294. t.colour = 0;
  10295. t.height = 0;
  10296. t.muted = false;
  10297. }
  10298. });
  10299. });
  10300. menu.addSeparator();
  10301. {
  10302. // FL's "Track mode" (round 146a): unassigned, an audio track (linked to a mixer track) or an instrument
  10303. // track (a channel and its mixer track)
  10304. juce::PopupMenu modes, audio, instruments;
  10305. modes.addItem (theme::mnemonic (tr ("Unassigned"), 'U'), true, info.mode == PlaylistTrackMode::unassigned, [this, tracks = tracksForMenu (track)] {
  10306. engine.editSong ([tracks] (Song& s) {
  10307. for (const auto t : tracks)
  10308. trackmodes::unassign (s, t);
  10309. });
  10310. });
  10311. // FL's Audio track ▸ (REA round 190cp, FUN_0122eff0 / FUN_012ec590; round 165 issue11c f5): "New mixer
  10312. // track(s)", then every insert as "N. name", the linked one ticked, one linked to another track greyed. A pick
  10313. // works on the selected tracks, one undo step; an insert left behind is disarmed (FL).
  10314. const auto assign = [this, tracks = tracksForMenu (track)] (int mixer) {
  10315. std::vector<int> before;
  10316. for (const auto t : tracks)
  10317. before.push_back (trackmodes::armableInsert (engine.getSong(), t));
  10318. int linked = 0;
  10319. engine.editSong ([&tracks, mixer, &linked] (Song& s) { linked = trackmodes::assignAudioTracks (s, tracks, mixer); });
  10320. for (std::size_t i = 0; i < tracks.size(); ++i)
  10321. if (before[i] > 0 && before[i] != trackmodes::armableInsert (engine.getSong(), tracks[i]) && engine.isInsertArmed (before[i]))
  10322. engine.setInsertArmed (before[i], false);
  10323. if (linked == 0 && mixer == trackmodes::newMixerTrack)
  10324. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't create new audio track"),
  10325. tr ("There are no available mixer tracks."));
  10326. };
  10327. const auto audioMenu = trackmodes::audioTrackMenu (song, track);
  10328. audio.addItem (tr ("New mixer track(s)"), audioMenu.canAddMixerTrack, false, [assign] { assign (trackmodes::newMixerTrack); });
  10329. audio.addSeparator();
  10330. for (const auto& item : audioMenu.inserts)
  10331. audio.addItem (juce::String (item.mixer) + ". " + (item.name.empty() ? tr ("Insert {0}", { juce::String (item.mixer) }) : juce::String::fromUTF8 (item.name.c_str())),
  10332. item.enabled, item.ticked, [assign, m = item.mixer] { assign (m); });
  10333. modes.addSubMenu (theme::mnemonic (tr ("Audio track"), 'A'), audio, true, nullptr, info.mode == PlaylistTrackMode::audio);
  10334. // FL's Instrument track › (EEPLTrackModeInstrMenu, round 190dx): "Use existing channel" ›, a line, "More
  10335. // plugins..." (FL's default item), a line, then the generator list of the Channel rack's Insert menu
  10336. juce::PopupMenu existing;
  10337. for (int c = 0; c < (int) song.channels.size(); ++c)
  10338. {
  10339. const auto kind = song.channels[(std::size_t) c].instrument;
  10340. if (kind == InstrumentKind::audioClip || kind == InstrumentKind::controller)
  10341. continue;
  10342. existing.addItem (juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str()), true,
  10343. info.mode == PlaylistTrackMode::instrument && info.channel == c, [this, track, c] {
  10344. bool ok = false;
  10345. engine.editSong ([track, c, &ok] (Song& s) { ok = trackmodes::makeInstrumentTrack (s, track, c); });
  10346. if (! ok)
  10347. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't create new instrument track"),
  10348. tr ("There are no available mixer tracks."));
  10349. });
  10350. }
  10351. instruments.addSubMenu (theme::mnemonic (tr ("Use existing channel"), 'U'), existing, existing.getNumItems() > 0);
  10352. instruments.addSeparator();
  10353. instruments.addItem (tr ("More plugins..."), [this, track] { morePluginsForTrack (track); });
  10354. instruments.addSeparator();
  10355. quickpick::addGeneratorMenu (instruments, engine, [this, track] (ChannelDef c) { instrumentForTrack (track, std::move (c)); }, nullptr, nullptr, this);
  10356. quickpick::addFolderViewItems (instruments, engine);
  10357. modes.addSubMenu (theme::mnemonic (tr ("Instrument track"), 'I'), instruments, true, nullptr, info.mode == PlaylistTrackMode::instrument);
  10358. // LYNX extra (round 190gz, issue #170): the project's switch, where track modes are picked
  10359. modes.addSeparator();
  10360. modes.addItem (tr ("Link Playlist tracks to mixer tracks (current project)"), true, song.linkTracksToMixer,
  10361. [this] { runAction ("playlist.linkTracks"); });
  10362. menu.addSubMenu (theme::mnemonic (tr ("Track mode"), 'T'), modes);
  10363. }
  10364. {
  10365. // FL's "Performance settings" (round 165m [DFM]): how the track's clips in the performance zone launch and play
  10366. using P = TrackPerformance;
  10367. const auto p = info.performance;
  10368. juce::PopupMenu perfMenu;
  10369. // FL's handler (0x1212fe0 → FUN_012ead80) sets the item on every selected track, in one undo step
  10370. auto set = [this, tracks = tracksForMenu (track)] (std::function<void (TrackPerformance&)> change) {
  10371. engine.editSong ([tracks, change] (Song& s) {
  10372. for (const auto t : tracks)
  10373. {
  10374. if ((int) s.playlistTracks.size() <= t)
  10375. s.playlistTracks.resize ((std::size_t) t + 1);
  10376. change (s.playlistTracks[(std::size_t) t].performance);
  10377. }
  10378. });
  10379. };
  10380. perfMenu.addSectionHeader (tr ("Press"));
  10381. for (auto [value, text] : { std::pair { P::Press::retrigger, TR_NOOP ("Retrigger") }, { P::Press::holdStop, TR_NOOP ("Hold & stop") },
  10382. { P::Press::holdMotion, TR_NOOP ("Hold & motion") }, { P::Press::latch, TR_NOOP ("Latch") } })
  10383. perfMenu.addItem (tr (text), true, p.press == value, [set, value = value] { set ([value] (P& x) { x.press = value; }); });
  10384. perfMenu.addSectionHeader (tr ("Motion"));
  10385. for (auto [value, text] : { std::pair { P::Motion::stay, TR_NOOP ("Stay") }, { P::Motion::oneShot, TR_NOOP ("One shot") },
  10386. { P::Motion::marchWrap, TR_NOOP ("March & wrap") }, { P::Motion::marchStay, TR_NOOP ("March & stay") },
  10387. { P::Motion::marchStop, TR_NOOP ("March & stop") }, { P::Motion::random, TR_NOOP ("Random") },
  10388. { P::Motion::exclusiveRandom, TR_NOOP ("Exclusive random") } })
  10389. perfMenu.addItem (tr (text), true, p.motion == value, [set, value = value] { set ([value] (P& x) { x.motion = value; }); });
  10390. const std::pair<P::Sync, const char*> syncs[] = { { P::Sync::off, TR_NOOP ("Off") }, { P::Sync::quarterBeat, TR_NOOP ("1/4 beat") },
  10391. { P::Sync::halfBeat, TR_NOOP ("1/2 beat") }, { P::Sync::beat, TR_NOOP ("1 beat") },
  10392. { P::Sync::twoBeats, TR_NOOP ("2 beats") }, { P::Sync::fourBeats, TR_NOOP ("4 beats") },
  10393. { P::Sync::autoLength, TR_NOOP ("Auto") } };
  10394. perfMenu.addSectionHeader (tr ("Trigger sync"));
  10395. for (const auto& [value, text] : syncs)
  10396. perfMenu.addItem (tr (text), true, p.triggerSync == value, [set, value = value] { set ([value] (P& x) { x.triggerSync = value; }); });
  10397. perfMenu.addSeparator();
  10398. perfMenu.addItem (tr ("Queue"), true, p.queue, [set] { set ([] (P& x) { x.queue = ! x.queue; }); });
  10399. perfMenu.addItem (tr ("Tolerant"), true, p.tolerant, [set] { set ([] (P& x) { x.tolerant = ! x.tolerant; }); });
  10400. perfMenu.addSectionHeader (tr ("Position sync"));
  10401. for (const auto& [value, text] : syncs)
  10402. perfMenu.addItem (tr (text), true, p.positionSync == value, [set, value = value] { set ([value] (P& x) { x.positionSync = value; }); });
  10403. menu.addSubMenu (theme::mnemonic (tr ("Performance settings"), 'P'), perfMenu);
  10404. }
  10405. menu.addSeparator();
  10406. {
  10407. // FL's sizes are relative to the default row; dragging the divider under a header sets any size (P18)
  10408. juce::PopupMenu size, all;
  10409. const auto current = heightOf (track);
  10410. for (int percent : { 33, 50, 100, 150, 200 })
  10411. {
  10412. // FL's Size menu sets the size factor (0.333, 0.5, 1, 1.5, 2): 16 px + factor × (default − 16) (round 190ft)
  10413. const auto h = percent == 100 ? baseRowHeight() : polish::heightForFlSize (percent == 33 ? 1.0 / 3.0 : percent / 100.0, baseRowHeight());
  10414. size.addItem (juce::String (percent) + "%", true, current == scaledHeight (h), [this, tracks = tracksForMenu (track), h] { setTrackHeights (tracks, h); });
  10415. all.addItem (juce::String (percent) + "%", [this, count, h] {
  10416. std::vector<int> tracks;
  10417. for (int t = 0; t < count; ++t)
  10418. tracks.push_back (t);
  10419. setTrackHeights (tracks, h);
  10420. });
  10421. }
  10422. size.addSeparator();
  10423. size.addSubMenu (tr ("Every track"), all);
  10424. menu.addSubMenu (theme::mnemonic (tr ("Size"), 'S'), size);
  10425. }
  10426. // FL's "Lock to this size" (EEPLTrackLockMenuClick 0x1228cb0, round 168f): the row keeps the height it has now
  10427. menu.addItem (theme::mnemonic (tr ("Lock to this size"), 'L'), true, info.lockedHeight > 0, [this, track, tracks = tracksForMenu (track)] {
  10428. const auto shown = heightOf (track);
  10429. engine.editSong ([tracks, shown] (Song& s) { pltracks::toggleSizeLock (s, tracks, shown); });
  10430. refreshTrackLayout();
  10431. updateScrollBars();
  10432. repaint();
  10433. });
  10434. // round 190op (P4, LYNX extra): Hide track (with the selected tracks), and in the Clip-launch / Simple layouts
  10435. // Deactivate track (its instrument and own insert unloaded, silent; core/TrackStates.h)
  10436. if (trackStateMenus() || trackstates::isHidden (song, track))
  10437. {
  10438. const auto hidden = trackstates::isHidden (song, track);
  10439. menu.addItem (tr ("Hide track"), true, hidden, [this, hidden, tracks = tracksForMenu (track)] {
  10440. engine.editSong ([tracks, hidden] (Song& s) { trackstates::setHidden (s, tracks, ! hidden); });
  10441. if (! hidden && ! showHiddenTracks)
  10442. setSelection ({});
  10443. refreshTrackLayout();
  10444. updateScrollBars();
  10445. repaint();
  10446. });
  10447. if (liveStyle || simpleHeaders)
  10448. addDeactivateTrackItem (menu, track);
  10449. }
  10450. // round 190pe (P20, LYNX extra; Cubase's Track Versions, Pro Tools' playlists): the Clip-launch layout, the Pattern one
  10451. // with its Settings › LYNX extras switch (FL's menu stays FL's) or for a track that has versions already
  10452. if (! simpleHeaders && (liveStyle || trackversions::patternMenus() || trackversions::count (song, track) > 0))
  10453. menu.addSubMenu (tr ("Track versions"), buildTrackVersionMenu (track));
  10454. menu.addSeparator();
  10455. {
  10456. const auto header = noteedit::groupHeaderOf (song, track);
  10457. const auto member = info.grouped && track > 0;
  10458. const auto folded = header >= 0 && header < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) header].collapsed;
  10459. // (FL 2026, round 190ri, kainproctor: Group / Ungroup act on every selected track, in one undo step)
  10460. menu.addItem (theme::mnemonic (tr ("Group with above track"), 'G'), track > 0 && ! member, member, [this, tracks = tracksForMenu (track)] {
  10461. // (round 190cg) in the Clip-launch workflow the group is a bus: its members play through the header's mixer track
  10462. const auto group = [tracks, live = liveStyle] (Song& s) {
  10463. for (const auto t : tracks)
  10464. if (t > 0)
  10465. {
  10466. noteedit::groupWithAbove (s, t);
  10467. if (live)
  10468. arrange::makeGroupBus (s, t);
  10469. }
  10470. };
  10471. if (liveStyle)
  10472. engine.editSongStructural (group);
  10473. else
  10474. engine.editSong (group);
  10475. });
  10476. // the same for a group made in another layout; ticked while the group plays through its header's mixer track
  10477. // (round 190jf, B17: offered for every group, a folder's bus "if the user wants"; the innermost folder of the track)
  10478. if (const auto group = arrange::groupOf (song, track); group.valid())
  10479. menu.addItem (tr ("Group plays through its own mixer track"), arrange::groupBus (song, track) < 0, arrange::groupBus (song, track) >= 0,
  10480. [this, track] { engine.editSongStructural ([track] (Song& s) { arrange::makeGroupBus (s, track); }); });
  10481. // round 190cg: Live's track fold [live-exe-strings.txt:1645415…1645430 sMenuFoldSelectedTrack(s) / sMenuUnfoldAllTracks]
  10482. {
  10483. const auto anyFolded = std::any_of (song.playlistTracks.begin(), song.playlistTracks.end(), [] (const PlaylistTrack& t) { return t.folded; });
  10484. if (liveStyle || anyFolded)
  10485. {
  10486. const auto isFolded = arrange::isFolded (song, track);
  10487. menu.addItem (tr ("Fold track"), true, isFolded, [this, track, isFolded] {
  10488. auto tracks = selectedTracks;
  10489. if (std::find (tracks.begin(), tracks.end(), track) == tracks.end())
  10490. tracks = { track };
  10491. engine.editSong ([tracks, isFolded] (Song& s) { arrange::setFolded (s, std::vector<int> (tracks.begin(), tracks.end()), ! isFolded); });
  10492. resized();
  10493. });
  10494. menu.addItem (tr ("Unfold all tracks"), anyFolded, false, [this] {
  10495. engine.editSong ([] (Song& s) { arrange::setAllFolded (s, false); });
  10496. resized();
  10497. });
  10498. }
  10499. }
  10500. menu.addItem (theme::mnemonic (tr ("Ungroup"), 'n'), member, false, [this, tracks = tracksForMenu (track)] {
  10501. engine.editSong ([tracks] (Song& s) {
  10502. for (const auto t : tracks)
  10503. noteedit::ungroupTrack (s, t);
  10504. });
  10505. });
  10506. // round 190jf (B17, LYNX's nested folders; FL's groups have one level): shown for grouped tracks only
  10507. if (member)
  10508. {
  10509. const auto depth = noteedit::folderDepth (song, track);
  10510. menu.addItem (tr ("Nest under the track above (a group in the group)"), depth <= noteedit::folderDepth (song, track - 1), false,
  10511. [this, track] { engine.editSong ([track] (Song& s) { noteedit::nestTrack (s, track); }); });
  10512. if (depth > 1)
  10513. menu.addItem (tr ("Move out of its group (one level up)"), [this, track] {
  10514. engine.editSong ([track] (Song& s) { noteedit::unnestTrack (s, track); });
  10515. refreshTrackLayout();
  10516. });
  10517. }
  10518. menu.addItem (tr ("Auto color group"), header >= 0, false, [this, track] { engine.editSong ([track] (Song& s) { noteedit::colourGroup (s, track); }); });
  10519. menu.addItem (tr ("Collapse grouped tracks"), header >= 0, folded, [this, track, folded] {
  10520. engine.editSong ([track, folded] (Song& s) { noteedit::setGroupCollapsed (s, track, ! folded); });
  10521. });
  10522. // round 177c: comping starts here, recording never moves tracks
  10523. if (comp::selectionSwipes (comp::swipeStyle) && comp::groupOf (song, track).isLane (track) && comp::isComp (song, comp::groupOf (song, track).comp))
  10524. menu.addItem (tr ("Send the time selection to the comp"), exportopts::hasSelection (song), false,
  10525. [this, track] { swipeTimeSelectionToComp (track); });
  10526. menu.addItem (tr ("Comp these takes"), comp::canComp (song, track), false, [this, track] {
  10527. setSelection ({});
  10528. engine.editSong ([track] (Song& s) { comp::compTakes (s, track); });
  10529. sortClips();
  10530. });
  10531. const auto compGroup = comp::groupOf (song, track);
  10532. if (comp::isComp (song, compGroup.comp))
  10533. menu.addItem (tr ("Flatten comp (keeps what plays, removes the take lanes)"), [this, head = compGroup.comp] {
  10534. setSelection ({});
  10535. engine.editSong ([head] (Song& s) { comp::flatten (s, head); });
  10536. sortClips();
  10537. });
  10538. }
  10539. menu.addSeparator();
  10540. {
  10541. // the sources of the track's clips: choosing one makes it what the pencil paints (FL's "Current clip source")
  10542. juce::PopupMenu sources;
  10543. std::vector<std::pair<ClipKind, int>> seen;
  10544. for (const auto& c : song.playlist)
  10545. {
  10546. if (c.track != track)
  10547. continue;
  10548. const auto key = std::pair { c.kind, c.kind == ClipKind::pattern ? c.pattern : c.kind == ClipKind::audio ? c.channel : c.automation };
  10549. if (std::find (seen.begin(), seen.end(), key) != seen.end())
  10550. continue;
  10551. seen.push_back (key);
  10552. juce::String name;
  10553. if (key.first == ClipKind::pattern && key.second >= 0 && key.second < (int) song.patterns.size())
  10554. name = juce::String::fromUTF8 (song.patterns[(std::size_t) key.second].name.c_str());
  10555. else if (key.first == ClipKind::automation && key.second >= 0 && key.second < (int) song.automations.size())
  10556. name = juce::String::fromUTF8 (song.automations[(std::size_t) key.second].name.c_str());
  10557. else if (key.second >= 0 && key.second < (int) song.channels.size())
  10558. name = juce::String::fromUTF8 (song.channels[(std::size_t) key.second].name.c_str());
  10559. const auto ticked = brush.kind == key.first && (key.first == ClipKind::pattern ? song.currentPattern == key.second : brush.index == key.second);
  10560. sources.addItem (name, true, ticked, [this, key] {
  10561. brush.kind = key.first;
  10562. brush.index = key.first == ClipKind::pattern ? -1 : key.second;
  10563. brush.picked.reset(); // (a source chosen from the list: its plain version, as a Picker choice)
  10564. if (key.first == ClipKind::pattern)
  10565. engine.editSong ([p = key.second] (Song& s) { s.currentPattern = p; }, false);
  10566. engine.sendChangeMessage();
  10567. });
  10568. }
  10569. menu.addSubMenu (tr ("Current clip source"), sources, ! seen.empty());
  10570. // FL's "Lock to content" (EEPLTrackClipLockMenuClick → FUN_012e7a90, round 168f): painting on the track places
  10571. // its own content
  10572. menu.addItem (tr ("Lock to content"), true, info.lockedToContent, [this, tracks = tracksForMenu (track)] {
  10573. engine.editSong ([tracks] (Song& s) { pltracks::toggleLockToContent (s, tracks); });
  10574. });
  10575. // round 190ne (LYNX extra, core/TrackClips.h): an instrument track whose clips own their notes; the selected
  10576. // instrument tracks follow this one's new state, one undo step
  10577. menu.addItem (tr ("Clips own their notes"), info.mode == PlaylistTrackMode::instrument, info.ownClips && info.mode == PlaylistTrackMode::instrument,
  10578. [this, on = ! info.ownClips, tracks = tracksForMenu (track)] {
  10579. engine.editSong ([tracks, on] (Song& s) {
  10580. for (const auto t : tracks)
  10581. if (t >= 0 && t < (int) s.playlistTracks.size() && s.playlistTracks[(std::size_t) t].mode == PlaylistTrackMode::instrument)
  10582. trackclips::setOwnClips (s, t, on);
  10583. });
  10584. });
  10585. // round 190ne: a bus track (an audio track whose insert other inserts send into) shows its insert's volume and
  10586. // pan as lanes under its header (round 177b's lanes; LYNX extra)
  10587. if (trackclips::isBusTrack (song, track))
  10588. menu.addItem (tr ("Show the bus insert's volume and pan lanes"), [this, track, insert = info.mixerTrack] {
  10589. for (const auto kind : { AutomationTargetKind::mixerVolume, AutomationTargetKind::mixerPan })
  10590. {
  10591. const AutomationTarget target { kind, insert, 0, 0 };
  10592. const auto& song = engine.getSong();
  10593. const auto& lanes = song.playlistTracks[(std::size_t) track].lanes;
  10594. if (std::none_of (lanes.begin(), lanes.end(), [&song, &target] (const AutomationLane& l) {
  10595. return l.automation >= 0 && l.automation < (int) song.automations.size() && song.automations[(std::size_t) l.automation].target == target;
  10596. }))
  10597. createAutomationLane (engine, target, track);
  10598. }
  10599. if (! autolanes::shown())
  10600. toggleAutomationLanes();
  10601. });
  10602. auto muteAll = [this, tracks = tracksForMenu (track)] (bool mute) { // (FL 2026: the selected tracks' clips, round 190ri)
  10603. engine.editSong ([tracks, mute] (Song& s) {
  10604. for (auto& c : s.playlist)
  10605. if (std::find (tracks.begin(), tracks.end(), c.track) != tracks.end())
  10606. c.muted = mute;
  10607. });
  10608. };
  10609. const auto targets = tracksForMenu (track);
  10610. const auto hasClips = ! seen.empty() || std::any_of (song.playlist.begin(), song.playlist.end(), [&targets] (const Clip& c) {
  10611. return std::find (targets.begin(), targets.end(), c.track) != targets.end();
  10612. });
  10613. {
  10614. // FL's "Consolidate track(s)" (round 146a): the track's clips rendered into one audio clip
  10615. juce::PopupMenu consolidate;
  10616. consolidate.addItem (theme::mnemonic (tr ("From track start"), 'F'), hasClips, false, [this, track] { consolidatePlaylistTrack (engine, track, false); });
  10617. consolidate.addItem (theme::mnemonic (tr ("From song start"), 's'), hasClips, false, [this, track] { consolidatePlaylistTrack (engine, track, true); });
  10618. menu.addSubMenu (theme::mnemonic (tr ("Consolidate track"), 'o'), consolidate, hasClips);
  10619. }
  10620. if (simpleHeaders && onExportTrack && simpletracks::kindOf (song, track).has_value())
  10621. {
  10622. // round 190fo (Simple workflow, as the original's track menu): the track as a WAV, a note track's notes as MIDI
  10623. const auto kind = simpletracks::kindOf (song, track);
  10624. const auto notes = std::any_of (seen.begin(), seen.end(), [] (const std::pair<ClipKind, int>& k) { return k.first == ClipKind::pattern; });
  10625. juce::PopupMenu exportTrack;
  10626. exportTrack.addItem (tr ("As audio (WAV)..."), hasClips, false, [this, track] { onExportTrack (track, false); });
  10627. exportTrack.addItem (tr ("As MIDI..."), notes && ! simpletracks::isAudioKind (*kind) && kind != simpletracks::Kind::audio, false,
  10628. [this, track] { onExportTrack (track, true); });
  10629. menu.addSubMenu (tr ("Export this track"), exportTrack, hasClips);
  10630. }
  10631. if (simpleHeaders && simpletracks::kindOf (song, track).has_value() && ! simpletracks::isAudioKind (*simpletracks::kindOf (song, track))
  10632. && simpletracks::kindOf (song, track) != simpletracks::Kind::audio)
  10633. {
  10634. // round 190fo (Simple workflow, as the original's track menu): Freeze / Unfreeze the track — its instrument
  10635. // channels (a Drums or Sampler track: all of them), with the Channel Rack's own freeze (round 190ay)
  10636. std::vector<std::uint64_t> uids;
  10637. bool anyFrozen = false;
  10638. const auto insert = simpletracks::insertOf (song, track);
  10639. for (const auto& c : song.channels)
  10640. if (c.mixerTrack == insert && c.instrument != InstrumentKind::audioClip && c.instrument != InstrumentKind::controller
  10641. && (c.instrument != InstrumentKind::sampler || ! c.samplePath.empty() || c.simplePad.index < 0) && c.uid != 0)
  10642. {
  10643. uids.push_back (c.uid);
  10644. anyFrozen = anyFrozen || c.freeze.on();
  10645. }
  10646. if (anyFrozen)
  10647. menu.addItem (tr ("Unfreeze track"), [this, uids] {
  10648. for (auto uid : uids)
  10649. for (int c = 0; c < (int) engine.getSong().channels.size(); ++c)
  10650. if (engine.getSong().channels[(std::size_t) c].uid == uid && engine.getSong().channels[(std::size_t) c].freeze.on())
  10651. unfreezeChannel (engine, c);
  10652. });
  10653. else
  10654. menu.addItem (tr ("Freeze track"), ! uids.empty() && hasClips, false, [this, uids] { freezeTrackChannels (uids); });
  10655. }
  10656. if (simpleHeaders && simpletracks::kindOf (song, track).has_value())
  10657. // round 190fo (the original's mobile app: "Reset all tracks"): every Simple track's level and pan back to the start
  10658. menu.addItem (tr ("Reset all tracks (level and pan)"), [this] {
  10659. engine.editSong ([] (Song& s) { simpletracks::resetLevels (s); });
  10660. });
  10661. menu.addItem (tr ("Merge clips"), hasClips, false, [this, track] {
  10662. setSelection ({});
  10663. engine.editSong ([track] (Song& s) { clipops::mergeTrackClips (s, track); });
  10664. sortClips();
  10665. });
  10666. // FL's "Send pattern instances here" (EEPLTrackSendPatMenuClick → FUN_012db4e0, round 168f): the selected pattern
  10667. // clips, or every clip of the current pattern, move to this track
  10668. menu.addItem (tr ("Send pattern instances here"), [this, track] {
  10669. const auto chosen = selection;
  10670. engine.editSong ([track, chosen] (Song& s) { pltracks::sendPatternInstancesHere (s, track, chosen); });
  10671. sortClips();
  10672. });
  10673. menu.addItem (tr ("Mute all clips"), hasClips, false, [muteAll] { muteAll (true); });
  10674. menu.addItem (tr ("Unmute all clips"), hasClips, false, [muteAll] { muteAll (false); });
  10675. }
  10676. // round 190ch (LYNX's own): one click cleans a recorded voice, a chain of LYNX's effects on the track's insert
  10677. if (const auto insert = simpleHeaders ? simpletracks::insertOf (engine.getSong(), track) : -1; insert > 0)
  10678. menu.addSubMenu (tr ("Clean voice"), ui::cleanVoiceMenu (engine, insert));
  10679. menu.addSeparator();
  10680. menu.addItem (theme::mnemonic (tr ("Insert one"), 'I'), [this, track] {
  10681. setSelection ({});
  10682. engine.editSong ([track] (Song& s) { noteedit::insertTrack (s, track); });
  10683. });
  10684. menu.addItem (theme::mnemonic (tr ("Clone..."), 'o'), [this, track] { cloneTracksWithDialog (tracksForMenu (track)); });
  10685. menu.addItem (theme::mnemonic (tr ("Delete"), 'e'), [this, tracks = tracksForMenu (track)] { deleteTracksAsked (tracks); });
  10686. menu.addSeparator();
  10687. // (FL 2026, round 190ri: the selected tracks move together, past a whole group; one undo step)
  10688. const auto tracks = tracksForMenu (track);
  10689. menu.addItem (theme::mnemonic (tr ("Move up"), 'u'), tracks.front() > 0, false, [this, tracks] { moveTracksBy (tracks, -1); });
  10690. menu.addItem (theme::mnemonic (tr ("Move down"), 'd'), tracks.back() + 1 < count, false, [this, tracks] { moveTracksBy (tracks, 1); });
  10691. return menu;
  10692. }
  10693. // Round 190op (P4): over the headers, a hidden track shown by "Show hidden tracks" is dimmed with a crossed eye, and a
  10694. // deactivated track (its instrument or own insert, core/TrackStates.h) is dimmed with the power tag. Nothing is drawn
  10695. // (nor looked up per row) while there are none.
  10696. void PlaylistComponent::paintTrackStateMarks (juce::Graphics& g, juce::Rectangle<int> headers, int rows)
  10697. {
  10698. const auto& song = engine.getSong();
  10699. const auto hiddenShown = showHiddenTracks && anyHiddenTracks;
  10700. const auto deactivated = deactivate::anyMarked (song);
  10701. if (! hiddenShown && ! deactivated)
  10702. return;
  10703. const auto plateRight = (float) (headerWidth - rightColumn());
  10704. for (int t = 0; t < rows; ++t)
  10705. {
  10706. const auto y = trackToY (t), h = heightOf (t);
  10707. if (h <= 0 || y > headers.getBottom() || y + h < headers.getY() || projection.isChild (t))
  10708. continue;
  10709. const auto hidden = hiddenShown && trackstates::isHidden (song, t);
  10710. const auto off = deactivated && trackstates::trackDeactivated (song, trackstates::unitsOfTrack (song, t));
  10711. if (! hidden && ! off)
  10712. continue;
  10713. const auto plate = juce::Rectangle<float> ((float) headerIndent (song, t), (float) y, plateRight - (float) headerIndent (song, t), (float) h - 1.0f);
  10714. g.setColour (theme::colour::bg0.withAlpha (0.45f));
  10715. g.fillRect (plate);
  10716. const auto size = juce::jmin (13.0f, (float) h - 4.0f);
  10717. if (size < 7.0f)
  10718. continue;
  10719. auto x = plate.getRight() - size - 4.0f;
  10720. const auto top = (float) y + juce::jmin (((float) h - size) * 0.5f, 3.0f);
  10721. if (off)
  10722. {
  10723. ui::drawPluginOffTag (g, { x, top, size + 1.0f, size });
  10724. x -= size + 4.0f;
  10725. }
  10726. if (hidden) // a crossed eye: an almond outline, its pupil and a slash
  10727. {
  10728. const auto box = juce::Rectangle<float> (x, top, size, size);
  10729. const auto c = box.getCentre();
  10730. juce::Path eye;
  10731. eye.startNewSubPath (box.getX(), c.y);
  10732. eye.quadraticTo (c.x, box.getY() + size * 0.1f, box.getRight(), c.y);
  10733. eye.quadraticTo (c.x, box.getBottom() - size * 0.1f, box.getX(), c.y);
  10734. eye.closeSubPath();
  10735. g.setColour (theme::colour::textSecondary);
  10736. g.strokePath (eye, juce::PathStrokeType (1.2f));
  10737. g.fillEllipse (juce::Rectangle<float> (size * 0.28f, size * 0.28f).withCentre (c));
  10738. g.drawLine (box.getX() + 1.0f, box.getBottom() - 1.0f, box.getRight() - 1.0f, box.getY() + 1.0f, 1.3f);
  10739. }
  10740. }
  10741. }
  10742. // Round 190op (P4): whether the Hide / Deactivate items show (always outside the Pattern layout; there a LYNX extra)
  10743. bool PlaylistComponent::trackStateMenus() const
  10744. {
  10745. return liveStyle || simpleHeaders || trackstates::patternMenus();
  10746. }
  10747. // Round 190op (P4): "Deactivate track" / "Reactivate track" for the track's units (core/TrackStates.h unitsOfTrack);
  10748. // the selected tracks follow the clicked one
  10749. void PlaylistComponent::addDeactivateTrackItem (juce::PopupMenu& menu, int track)
  10750. {
  10751. const auto& song = engine.getSong();
  10752. const auto units = trackstates::unitsOfTrack (song, track);
  10753. const auto off = trackstates::trackDeactivated (song, units);
  10754. menu.addItem (off ? tr ("Reactivate track") : tr ("Deactivate track"), ! units.empty(), off, [this, off, tracks = tracksForMenu (track)] {
  10755. const auto& s = engine.getSong();
  10756. std::vector<int> channels, inserts;
  10757. for (const auto t : tracks)
  10758. {
  10759. const auto u = trackstates::unitsOfTrack (s, t);
  10760. channels.insert (channels.end(), u.channels.begin(), u.channels.end());
  10761. inserts.insert (inserts.end(), u.inserts.begin(), u.inserts.end());
  10762. }
  10763. engine.setDeactivated (channels, inserts, ! off);
  10764. ui::postHint ({ off ? tr ("Track reactivated: its plugins load again with their settings")
  10765. : tr ("Track deactivated: its plugins are unloaded and it is silent (its settings are kept)"), {}, false, false }, 3000);
  10766. repaint();
  10767. });
  10768. }
  10769. // Round 190pe (P20, LYNX extra): the track's versions. The list (the active one ticked; a click switches), then New version
  10770. // (empty, the device chain as it is), Duplicate version, Rename, Delete and, with a time selection, Promote: the selected
  10771. // part of another version replaces that part of the active one (Pro Tools' "copy selection to main playlist").
  10772. juce::PopupMenu PlaylistComponent::buildTrackVersionMenu (int track)
  10773. {
  10774. const auto& song = engine.getSong();
  10775. juce::PopupMenu menu;
  10776. const auto count = trackversions::count (song, track);
  10777. const auto active = trackversions::active (song, track);
  10778. const auto here = count == 0 || trackversions::inCurrentArrangement (song, track);
  10779. const auto refresh = [this] {
  10780. sortClips();
  10781. refreshTrackLayout();
  10782. updateScrollBars();
  10783. repaint();
  10784. };
  10785. if (count > 0)
  10786. {
  10787. menu.addSectionHeader (tr ("Track versions"));
  10788. for (int v = 0; v < count; ++v)
  10789. menu.addItem (juce::String::fromUTF8 (trackversions::nameOf (song, track, v).c_str()), here, v == active, [this, track, v, refresh] {
  10790. setSelection ({});
  10791. engine.editSongStructural ([track, v] (Song& s) { trackversions::switchTo (s, track, v); });
  10792. refresh();
  10793. });
  10794. if (! here)
  10795. menu.addItem (tr ("(made in another arrangement: show that arrangement to switch them)"), false, false, [] {});
  10796. menu.addSeparator();
  10797. }
  10798. const auto first = tr ("Version {0}", { juce::String (1) }).toStdString();
  10799. const auto next = [&song, track, count] {
  10800. return trackversions::freeName (song, track, tr ("Version {0}", { juce::String (juce::jmax (2, count + 1)) }).toStdString());
  10801. };
  10802. menu.addItem (tr ("New version"), here, false, [this, track, next, first, refresh] {
  10803. setSelection ({});
  10804. const auto name = next();
  10805. engine.editSongStructural ([track, name, first] (Song& s) { trackversions::add (s, track, trackversions::Start::empty, name, first); });
  10806. refresh();
  10807. });
  10808. menu.addItem (tr ("Duplicate version"), here, false, [this, track, next, first, refresh] {
  10809. setSelection ({});
  10810. const auto name = next();
  10811. engine.editSongStructural ([track, name, first] (Song& s) { trackversions::add (s, track, trackversions::Start::duplicate, name, first); });
  10812. refresh();
  10813. });
  10814. menu.addItem (tr ("Rename version..."), count > 0, false, [this, track, active] { renameTrackVersion (track, active); });
  10815. menu.addItem (tr ("Delete version"), count > 0 && here, false, [this, track, active, refresh] {
  10816. setSelection ({});
  10817. engine.editSongStructural ([track, active] (Song& s) { trackversions::remove (s, track, active); });
  10818. refresh();
  10819. });
  10820. if (count > 1)
  10821. {
  10822. juce::PopupMenu promote;
  10823. const auto selection = exportopts::hasSelection (song);
  10824. for (int v = 0; v < count; ++v)
  10825. if (v != active)
  10826. promote.addItem (juce::String::fromUTF8 (trackversions::nameOf (song, track, v).c_str()), selection && here, false, [this, track, v, refresh] {
  10827. setSelection ({});
  10828. engine.editSong ([track, v] (Song& s) { trackversions::promote (s, track, v, s.loopStart, s.loopEnd); });
  10829. refresh();
  10830. });
  10831. menu.addSubMenu (selection ? tr ("Promote the time selection from") : tr ("Promote the time selection from (select a time range first)"), promote, here);
  10832. }
  10833. return menu;
  10834. }
  10835. void PlaylistComponent::renameTrackVersion (int track, int version)
  10836. {
  10837. auto* window = new juce::AlertWindow (tr ("Rename version"), {}, juce::MessageBoxIconType::NoIcon);
  10838. window->addTextEditor ("name", juce::String::fromUTF8 (trackversions::nameOf (engine.getSong(), track, version).c_str()));
  10839. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  10840. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  10841. juce::Component::SafePointer<PlaylistComponent> safe (this);
  10842. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, track, version, window] (int result) {
  10843. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  10844. if (safe != nullptr && result == 1 && ! name.empty())
  10845. {
  10846. safe->engine.editSong ([track, version, name] (Song& s) { trackversions::rename (s, track, version, name); });
  10847. safe->repaint();
  10848. }
  10849. }),
  10850. true);
  10851. }
  10852. // Round 190pe (P20): the chip of a track with versions, left of the header's buttons in the row's lower half (the name
  10853. // keeps the upper one); none on a row too short for two lines, nor in the Simple layout (no versions there)
  10854. juce::Rectangle<int> PlaylistComponent::trackVersionChip (int track) const
  10855. {
  10856. const auto& song = engine.getSong();
  10857. if (simpleHeaders || trackversions::count (song, track) == 0 || noteedit::isFoldedAway (song, track) || projection.isChild (track))
  10858. return {};
  10859. const auto h = heightOf (track);
  10860. if (h < 30)
  10861. return {};
  10862. auto right = trackLed (track).getX();
  10863. for (const auto& r : { trackSolo (track), trackArrow (track), trackArm (track), trackInput (track), trackAddLane (track) })
  10864. if (! r.isEmpty())
  10865. right = juce::jmin (right, r.getX());
  10866. const auto name = juce::String::fromUTF8 (trackversions::nameOf (song, track, trackversions::active (song, track)).c_str());
  10867. const auto width = juce::jlimit (30, 92, juce::GlyphArrangement::getStringWidthInt (theme::font (theme::type::caption), name) + 18);
  10868. const auto left = juce::jmax (headerIndent (song, track) + 4, right - 4 - width);
  10869. return { left, trackToY (track) + h - 17, right - 4 - left, 14 };
  10870. }
  10871. void PlaylistComponent::paintVersionChips (juce::Graphics& g, juce::Rectangle<int> headers, int rows)
  10872. {
  10873. const auto& song = engine.getSong();
  10874. if (simpleHeaders || ! trackversions::any (song))
  10875. return;
  10876. g.setFont (theme::font (theme::type::caption));
  10877. for (int t = 0; t < rows; ++t)
  10878. {
  10879. if (trackversions::count (song, t) == 0)
  10880. continue;
  10881. const auto chip = trackVersionChip (t);
  10882. if (chip.getWidth() < 24 || chip.getY() > headers.getBottom() || chip.getBottom() < headers.getY())
  10883. continue;
  10884. const auto box = chip.toFloat().reduced (0.5f);
  10885. const auto here = trackversions::inCurrentArrangement (song, t);
  10886. g.setColour (theme::colour::bg4);
  10887. g.fillRoundedRectangle (box, 3.0f);
  10888. g.setColour (theme::colour::borderStrong);
  10889. g.drawRoundedRectangle (box, 3.0f, 1.0f);
  10890. g.setColour (here ? theme::colour::textPrimary : theme::colour::textDisabled);
  10891. const auto name = juce::String::fromUTF8 (trackversions::nameOf (song, t, trackversions::active (song, t)).c_str());
  10892. g.drawFittedText (name, chip.withTrimmedLeft (5).withTrimmedRight (12), juce::Justification::centredLeft, 1, 0.85f);
  10893. // the drop-down caret
  10894. juce::Path caret;
  10895. const auto cx = box.getRight() - 7.0f, cy = box.getCentreY();
  10896. caret.addTriangle (cx - 3.0f, cy - 1.5f, cx + 3.0f, cy - 1.5f, cx, cy + 2.0f);
  10897. g.setColour (theme::colour::textSecondary);
  10898. g.fillPath (caret);
  10899. }
  10900. }
  10901. // round 190fo: the Simple track menu's Freeze, one channel after the other (each freeze runs in the background)
  10902. void PlaylistComponent::freezeTrackChannels (std::vector<std::uint64_t> uids)
  10903. {
  10904. while (! uids.empty())
  10905. {
  10906. const auto uid = uids.front();
  10907. uids.erase (uids.begin());
  10908. for (int c = 0; c < (int) engine.getSong().channels.size(); ++c)
  10909. if (engine.getSong().channels[(std::size_t) c].uid == uid && ! engine.getSong().channels[(std::size_t) c].freeze.on()
  10910. && freezeRefusal (engine, c).isEmpty())
  10911. {
  10912. freezeChannel (engine, c, [safe = juce::Component::SafePointer<PlaylistComponent> (this), uids] (bool) {
  10913. if (safe != nullptr)
  10914. safe->freezeTrackChannels (uids);
  10915. });
  10916. return;
  10917. }
  10918. }
  10919. }
  10920. void PlaylistComponent::renameTrack (int track, std::function<void (Song&)> alsoEdit)
  10921. {
  10922. const auto& tracks = engine.getSong().playlistTracks;
  10923. const auto current = track < (int) tracks.size() ? juce::String::fromUTF8 (tracks[(std::size_t) track].name.c_str()) : juce::String();
  10924. const auto colour = track < (int) tracks.size() ? tracks[(std::size_t) track].colour : 0u;
  10925. const auto oldIcon = track < (int) tracks.size() ? tracks[(std::size_t) track].icon : 0;
  10926. // issue #201 (round 190ll, core/SelectionRename.h): a new colour goes to every selected track (the name to this one)
  10927. // issue #220 (round 190ng): FL's "Rename, color and icon": the icon in the same window, for every selected track too
  10928. showNameColourIconDialog (tr ("Rename track"), current.isNotEmpty() ? current : tr ("Track {0}", { juce::String (track + 1) }), colour, oldIcon,
  10929. [this, track, colour, oldIcon, targets = tracksForMenu (track), alsoEdit] (const juce::String& newName, std::uint32_t newColour, int icon) {
  10930. const auto name = newName.trim().toStdString();
  10931. const auto together = simpleHeaders && simpletracks::kindOf (engine.getSong(), track).has_value();
  10932. engine.editSong ([track, name, newColour, together, colour, targets, alsoEdit, icon, oldIcon] (Song& s) {
  10933. if (icon >= 0 && icon != oldIcon)
  10934. for (const auto t : targets)
  10935. {
  10936. if ((int) s.playlistTracks.size() <= t)
  10937. s.playlistTracks.resize ((std::size_t) t + 1);
  10938. s.playlistTracks[(std::size_t) t].icon = icon;
  10939. }
  10940. if ((int) s.playlistTracks.size() <= track)
  10941. s.playlistTracks.resize ((std::size_t) track + 1);
  10942. if (together) // (the Simple workflow: the track, its insert and its channel, round 184a)
  10943. {
  10944. simpletracks::rename (s, track, name);
  10945. simpletracks::recolour (s, track, newColour);
  10946. if (newColour != colour)
  10947. for (const auto t : targets)
  10948. if (t != track)
  10949. recolourTrack (s, t, newColour, true);
  10950. }
  10951. else
  10952. selrename::applyToPlaylistTracks (s, track, targets, { {}, name, colour, newColour });
  10953. // (round 190mp: FL's Auto name clips asks for a name first, then names the clips)
  10954. if (alsoEdit != nullptr && ! name.empty())
  10955. alsoEdit (s);
  10956. });
  10957. });
  10958. }
  10959. // FL's Auto name clips (FUN_01213040, round 190mp REA): a track without a name asks for one first (FL's name box; Cancel
  10960. // changes nothing); then the other selected tracks without a name take it ("Name #2"…, FUN_012eb350) and every selected
  10961. // track's clips are named after their track (FUN_012ef5f0; FUN_012eafa0 mask 0x40). One undo step.
  10962. void PlaylistComponent::autoNameClipsFromMenu (int track, const std::vector<int>& tracks)
  10963. {
  10964. const auto apply = [track, tracks] (Song& s) {
  10965. if (track < 0 || track >= (int) s.playlistTracks.size() || s.playlistTracks[(std::size_t) track].name.empty())
  10966. return;
  10967. const auto name = s.playlistTracks[(std::size_t) track].name;
  10968. int suffix = 2;
  10969. for (std::size_t i = 0; i < tracks.size(); ++i)
  10970. {
  10971. const auto t = tracks[i];
  10972. if ((int) s.playlistTracks.size() <= t)
  10973. s.playlistTracks.resize ((std::size_t) t + 1);
  10974. if (s.playlistTracks[(std::size_t) t].name.empty())
  10975. s.playlistTracks[(std::size_t) t].name = i > 0 ? name + " #" + std::to_string (suffix++) : name;
  10976. }
  10977. pltracks::autoNameClips (s, track);
  10978. for (const auto t : tracks)
  10979. if (t != track)
  10980. pltracks::autoNameClips (s, t);
  10981. };
  10982. const auto& song = engine.getSong();
  10983. if (track >= (int) song.playlistTracks.size() || song.playlistTracks[(std::size_t) track].name.empty())
  10984. renameTrack (track, apply);
  10985. else
  10986. engine.editSong (apply);
  10987. }
  10988. juce::String PlaylistComponent::markerLabel (const Marker& m)
  10989. {
  10990. auto label = juce::String::fromUTF8 (m.name.c_str());
  10991. if (const auto fraction = juce::String (m.numerator) + "/" + juce::String (m.denominator); m.isSignature() && label != fraction)
  10992. label = fraction + (label.isEmpty() ? "" : " " + label);
  10993. // FL's marker actions: a symbol before the name (unnamed: the action's name)
  10994. if (! m.isSignature() && m.action != 0 && m.action != Marker::punchIn && m.action != Marker::punchOut)
  10995. {
  10996. if (label.isEmpty())
  10997. label = tr (markers::actionName (m.action));
  10998. label = juce::String::fromUTF8 (markers::actionTag (m.action)) + " " + label;
  10999. }
  11000. if (label.isEmpty())
  11001. label = "*";
  11002. return label;
  11003. }
  11004. int PlaylistComponent::markerTagAt (int x, int y) const
  11005. {
  11006. // the tags hang at the bottom of the ruler (see paint); round 190ri (kainproctor): 3 px above the 11 px tag count too,
  11007. // the right-click on a tag's top edge gave the ruler menu
  11008. if (y < rulerTop + timelineHeight - 14 || y >= headerHeight)
  11009. return -1;
  11010. const auto& list = engine.getSong().markers();
  11011. const auto f = theme::font (theme::type::caption, true);
  11012. for (int i = (int) list.size(); --i >= 0;) // the later tag is drawn on top
  11013. {
  11014. const auto mx = tickToX ((double) list[(std::size_t) i].tick);
  11015. const auto width = (double) juce::GlyphArrangement::getStringWidthInt (f, markerLabel (list[(std::size_t) i])) + 8.0;
  11016. if (x >= mx - 2.0 && x <= mx + width)
  11017. return i;
  11018. }
  11019. return -1;
  11020. }
  11021. int PlaylistComponent::tempoTagAt (int x, int y) const
  11022. {
  11023. if (y < rulerTop + timelineHeight - 12 || y >= headerHeight)
  11024. return -1;
  11025. const auto marks = tempomarkers::list (engine.getSong());
  11026. const auto f = theme::font (theme::type::caption, true);
  11027. for (int i = (int) marks.size(); --i >= 0;)
  11028. {
  11029. const auto& m = marks[(std::size_t) i];
  11030. const auto mx = tickToX ((double) m.tick);
  11031. const auto label = (m.glide ? juce::String ("/ ") : juce::String()) + juce::String (tempomarkers::tempoText (m.bpm));
  11032. const auto width = (double) juce::GlyphArrangement::getStringWidthInt (f, label) + 8.0;
  11033. if (x >= mx - 2.0 && x <= mx + width)
  11034. return i;
  11035. }
  11036. return -1;
  11037. }
  11038. void PlaylistComponent::editTempoMarker (std::int64_t tick, int existing)
  11039. {
  11040. // round 190hq (B11): the tempo (BPM) of a new or existing tempo marker; it writes the tempo markers' automation clip
  11041. const auto& song = engine.getSong();
  11042. const auto marks = tempomarkers::list (song);
  11043. const auto editing = existing >= 0 && existing < (int) marks.size();
  11044. const auto current = editing ? marks[(std::size_t) existing].bpm : song.tempoAt ((double) tick);
  11045. auto* window = new juce::AlertWindow (editing ? tr ("Edit tempo change") : tr ("Add tempo change"), {}, juce::MessageBoxIconType::NoIcon, this);
  11046. window->addTextEditor ("bpm", juce::String (current, 2), tr ("Tempo (BPM)"));
  11047. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  11048. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  11049. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, tick, existing, editing, window] (int result) {
  11050. if (result != 1)
  11051. return;
  11052. const auto bpm = window->getTextEditorContents ("bpm").getDoubleValue();
  11053. if (! (bpm >= minTempo && bpm <= maxTempo))
  11054. return;
  11055. engine.editSong ([tick, existing, editing, bpm] (Song& s) {
  11056. if (editing)
  11057. tempomarkers::setTempo (s, existing, bpm);
  11058. else
  11059. tempomarkers::add (s, tick, bpm);
  11060. });
  11061. repaint();
  11062. }),
  11063. true);
  11064. }
  11065. // Round 190ri (kainproctor, Discord 11-25; FL 2026 live, raw/mg3.png and his k5): a right-click on a marker's tag gives FL's
  11066. // marker menu — Add marker..., Add time signature..., Place loop, the marker ("name at 11:01:00"), Delete, Rename..., Move
  11067. // content left / right, then the Action list. LYNX showed its whole ruler menu with the marker's part at its far end, below the
  11068. // screen on a laptop; that menu stays one level down (LYNX's "Ruler" submenu)
  11069. juce::PopupMenu PlaylistComponent::markerMenu (int index, int x)
  11070. {
  11071. const auto& song = engine.getSong();
  11072. juce::PopupMenu menu;
  11073. if (index < 0 || index >= (int) song.markers().size())
  11074. return menu;
  11075. const auto& marker = song.markers()[(std::size_t) index];
  11076. const auto tick = marker.tick;
  11077. menu.addItem (tr ("Add marker..."), [this, at = juce::jmax<std::int64_t> (0, snap (xToTick (x), true))] { editMarkerName (at, -1); });
  11078. menu.addItem (tr ("Add time signature..."), [this] { runAction ("playlist.markerSignature"); });
  11079. menu.addItem (tr ("Place loop"), [this, tick] {
  11080. engine.editSong ([tick] (Song& s) { markers::placeSongLoop (s, tick); });
  11081. repaint();
  11082. });
  11083. {
  11084. const auto bar = song.barAt (tick);
  11085. const auto rest = tick - bar.tick;
  11086. const auto two = [] (std::int64_t v) { return juce::String (v).paddedLeft ('0', 2); };
  11087. const auto at = juce::String (bar.number) + ":" + two (rest / ticksPerStep + 1) + ":" + two ((rest % ticksPerStep) * 96 / ppq);
  11088. const auto name = marker.name.empty() ? markerLabel (marker) : juce::String::fromUTF8 (marker.name.c_str());
  11089. menu.addSectionHeader (tr ("{0} at {1}", { name, at }));
  11090. }
  11091. menu.addItem (tr ("Delete"), [this, index] {
  11092. engine.editSong ([index] (Song& s) {
  11093. if (index < (int) s.markers().size())
  11094. s.markers().erase (s.markers().begin() + index);
  11095. });
  11096. repaint();
  11097. });
  11098. menu.addItem (tr ("Rename..."), [this, index] { editMarkerName (0, index); });
  11099. menu.addSeparator();
  11100. for (const auto direction : { -1, 1 })
  11101. menu.addItem (direction < 0 ? tr ("Move content left") : tr ("Move content right"), markers::canMoveContent (song, index, direction), false,
  11102. [this, index, direction] {
  11103. setSelection ({});
  11104. engine.editSong ([index, direction] (Song& s) { markers::moveContent (s, index, direction); });
  11105. sortClips();
  11106. repaint();
  11107. });
  11108. menu.addSectionHeader (tr ("Action"));
  11109. const auto current = marker.isSignature() ? Marker::timeSignature : marker.action;
  11110. for (auto [value, text] : { std::pair { Marker::none, TR_NOOP ("None") }, { Marker::start, TR_NOOP ("Start") }, { Marker::songLoop, TR_NOOP ("Loop") },
  11111. { Marker::markerLoop, TR_NOOP ("Marker loop") }, { Marker::markerSkip, TR_NOOP ("Marker skip") },
  11112. { Marker::markerPause, TR_NOOP ("Marker pause") }, { Marker::timeSignature, TR_NOOP ("Time signature") },
  11113. { Marker::punchIn, TR_NOOP ("Start recording") }, { Marker::punchOut, TR_NOOP ("Stop recording") } })
  11114. quickpick::addRadioItem (menu, tr (text), current == value, [this, index, value = value] {
  11115. engine.editSong ([index, value] (Song& s) {
  11116. if (index < (int) s.markers().size())
  11117. markers::setAction (s, s.markers()[(std::size_t) index], value);
  11118. });
  11119. repaint();
  11120. });
  11121. // LYNX: the rest of its ruler menu (loop region, time markers, tempo changes, LYNX's extras)
  11122. menu.addSeparator();
  11123. menu.addSubMenu (tr ("Ruler"), rulerMenu (x, -1));
  11124. return menu;
  11125. }
  11126. juce::PopupMenu PlaylistComponent::rulerMenu (int x, int y)
  11127. {
  11128. const auto& song = engine.getSong();
  11129. const auto tick = juce::jmax<std::int64_t> (0, snap (xToTick (x), true));
  11130. // the marker whose tag was pressed (issue #281, round 190qr: the whole tag, as FL; it was only 6 px around the
  11131. // marker's line, so a right-click on its name gave the menu without "Delete"), else one near the click (up to 6 px)
  11132. int near = y >= 0 ? markerTagAt (x, y) : -1;
  11133. for (int i = 0; near < 0 && i < (int) song.markers().size(); ++i)
  11134. if (std::abs (tickToX ((double) song.markers()[(std::size_t) i].tick) - x) <= 6.0)
  11135. near = i;
  11136. juce::PopupMenu menu;
  11137. // round 190ol (research190oe P6, GarageBand's complaint G1): the Simple layout's time signature change at the bar under
  11138. // the pointer (core/SignatureEdit.h); the FL items below stay
  11139. if (simpleHeaders)
  11140. {
  11141. const auto bar = signatureedit::barLine (song, (std::int64_t) juce::jmax (0.0, xToTick (x)));
  11142. menu.addItem (tr ("Change time signature here..."), [this, bar] { askSimpleSignature (bar); });
  11143. if (bar > 0 && signatureedit::changeAt (song, bar) >= 0)
  11144. menu.addItem (tr ("Delete this time signature change"), [this, bar] {
  11145. engine.editSong ([bar] (Song& s) { signatureedit::remove (s, bar); });
  11146. repaint();
  11147. });
  11148. // round 190pf (research190oe P13): the Chord lane (a LYNX extra in every layout; here beside the Simple ruler's own)
  11149. menu.addItem (tr ("Chord lane"), true, chordlane::laneOn(), [] { workflowextras::setExtra ("playlist.chordLane", ! chordlane::laneOn()); });
  11150. menu.addSeparator();
  11151. }
  11152. menu.addItem (tr ("Add marker here..."), [this, tick] { editMarkerName (tick, -1); });
  11153. juce::PopupMenu signatures;
  11154. for (auto [n, d] : { std::pair { 2, 4 }, { 3, 4 }, { 4, 4 }, { 5, 4 }, { 6, 4 }, { 7, 4 }, { 6, 8 }, { 7, 8 }, { 9, 8 }, { 12, 8 } })
  11155. signatures.addItem (juce::String (n) + "/" + juce::String (d), [this, tick, n = n, d = d] {
  11156. engine.editSong ([tick, n, d] (Song& s) { s.addMarker ({ tick, {}, n, d }); });
  11157. });
  11158. menu.addSubMenu (tr ("Time signature change here"), signatures);
  11159. {
  11160. // round 190cg [live-exe-strings.txt:1667947 sMenuClearTimeSignatureChanges]: the one at the song's start stays
  11161. const auto later = std::any_of (song.markers().begin(), song.markers().end(), [] (const Marker& m) { return m.numerator > 0 && m.tick > 0; });
  11162. menu.addItem (tr ("Delete all time signature changes"), later, false, [this] {
  11163. engine.editSong ([] (Song& s) {
  11164. auto& m = s.markers();
  11165. m.erase (std::remove_if (m.begin(), m.end(), [] (const Marker& x) { return x.numerator > 0 && x.tick > 0; }), m.end());
  11166. });
  11167. });
  11168. }
  11169. // round 190hq (B11, LYNX extra): tempo markers on the ruler, written into the tempo markers' automation clip
  11170. {
  11171. const auto marks = tempomarkers::list (song);
  11172. menu.addItem (tr ("Add tempo change here...") + " (LYNX)", [this, tick] { editTempoMarker (tick, -1); });
  11173. menu.addItem (tr ("Delete all tempo changes"), ! marks.empty(), false, [this] {
  11174. engine.editSong ([] (Song& s) {
  11175. while (! tempomarkers::list (s).empty())
  11176. tempomarkers::remove (s, 0);
  11177. });
  11178. });
  11179. int tempoNear = -1;
  11180. for (int i = 0; i < (int) marks.size(); ++i)
  11181. if (std::abs (tickToX ((double) marks[(std::size_t) i].tick) - x) <= 6.0)
  11182. tempoNear = i;
  11183. if (tempoNear >= 0)
  11184. {
  11185. const auto& m = marks[(std::size_t) tempoNear];
  11186. menu.addSeparator();
  11187. menu.addSectionHeader (juce::String (tempomarkers::tempoText (m.bpm)));
  11188. menu.addItem (tr ("Edit tempo..."), [this, tempoNear] { editTempoMarker (0, tempoNear); });
  11189. menu.addItem (tr ("Glide into this tempo"), true, m.glide, [this, tempoNear, glide = ! m.glide] {
  11190. engine.editSong ([tempoNear, glide] (Song& s) { tempomarkers::setGlide (s, tempoNear, glide); });
  11191. });
  11192. menu.addItem (tr ("Remove tempo change"), [this, tempoNear] {
  11193. engine.editSong ([tempoNear] (Song& s) { tempomarkers::remove (s, tempoNear); });
  11194. });
  11195. menu.addSeparator();
  11196. }
  11197. }
  11198. // FL's marker actions "Start recording" / "Stop recording" (punch in / out; Record menu › Enable recording markers)
  11199. menu.addItem (tr ("Add a Start recording marker here"), [this, tick] {
  11200. engine.editSong ([tick] (Song& s) {
  11201. Marker m;
  11202. m.tick = tick;
  11203. m.name = tr ("Start recording").toStdString();
  11204. m.action = Marker::punchIn;
  11205. s.addMarker (m);
  11206. });
  11207. });
  11208. menu.addItem (tr ("Add a Stop recording marker here"), [this, tick] {
  11209. engine.editSong ([tick] (Song& s) {
  11210. Marker m;
  11211. m.tick = tick;
  11212. m.name = tr ("Stop recording").toStdString();
  11213. m.action = Marker::punchOut;
  11214. s.addMarker (m);
  11215. });
  11216. });
  11217. // FL's "Start" marker: the song starts there; in Performance mode the clips before it are the performance zone
  11218. menu.addItem (tr ("Add a Start marker here (the song starts here; Performance mode launches the clips before it)"), [this, tick] {
  11219. engine.editSong ([tick] (Song& s) {
  11220. Marker m;
  11221. m.tick = tick;
  11222. m.name = tr ("Start").toStdString();
  11223. m.action = Marker::songStart;
  11224. s.addMarker (m);
  11225. });
  11226. });
  11227. if (song.performanceZoneEnd() > 0 && tick < song.performanceZoneEnd())
  11228. {
  11229. // a marker of the zone: launch every clip of its column (from this marker to the next one)
  11230. std::int64_t from = 0, to = song.performanceZoneEnd();
  11231. for (const auto& m : song.markers())
  11232. {
  11233. if (m.tick <= tick)
  11234. from = juce::jmax (from, m.tick);
  11235. else
  11236. to = juce::jmin (to, m.tick);
  11237. }
  11238. menu.addItem (tr ("Launch this column's clips"), engine.getTransport().playing.load(), false, [this, from, to] {
  11239. perf::Command c;
  11240. c.type = perf::Command::Type::launchColumn;
  11241. c.columnStart = from;
  11242. c.columnEnd = to;
  11243. engine.performanceCommand (c);
  11244. });
  11245. menu.addItem (tr ("Stop all performance clips"), engine.getTransport().playing.load(), false, [this] {
  11246. perf::Command c;
  11247. c.type = perf::Command::Type::stopAll;
  11248. engine.performanceCommand (c);
  11249. });
  11250. }
  11251. // #227 (round 190nq): the LYNX extra "A click on the ruler moves the song position with every tool", also here
  11252. menu.addSeparator();
  11253. menu.addItem (tr ("A click on the ruler moves the song position with every tool"), true, ruler::seekWithAnyTool(),
  11254. [] { workflowextras::setExtra ("playlist.rulerSeeksAnyTool", ! ruler::seekWithAnyTool()); });
  11255. // FL's Playlist menu › Time markers (REA_rodada165f-markers §1.4)
  11256. {
  11257. juce::PopupMenu timeMarkers;
  11258. // (round 190sj, issue #327: the key map's keys, a remapped one too; they were written in)
  11259. auto markerKey = [] (const char* id) { return shortcutText != nullptr ? shortcutText (id) : juce::String(); };
  11260. juce::PopupMenu every;
  11261. for (auto [bars, text] : { std::pair { 1, TR_NOOP ("Bar") }, { 2, TR_NOOP ("2 bars") }, { 4, TR_NOOP ("4 bars") }, { 8, TR_NOOP ("8 bars") } })
  11262. every.addItem (tr (text), [this, bars = bars] {
  11263. engine.editSong ([bars] (Song& s) { markers::addEvery (s, bars); });
  11264. });
  11265. timeMarkers.addItem (tr ("Add one...") + markerKey ("playlist.markerAdd"), [this] { runAction ("playlist.markerAdd"); });
  11266. timeMarkers.addItem (tr ("Add auto") + markerKey ("playlist.markerAuto"), [this] { runAction ("playlist.markerAuto"); });
  11267. timeMarkers.addSubMenu (tr ("Add one every"), every);
  11268. timeMarkers.addItem (tr ("Add jump to next bar"), [this, tick] {
  11269. engine.editSong ([tick] (Song& s) { markers::addJumpToNextBar (s, tick); });
  11270. });
  11271. timeMarkers.addItem (tr ("Add time signature change...") + markerKey ("playlist.markerSignature"), [this] { runAction ("playlist.markerSignature"); });
  11272. // round 190hq (B11, LYNX extra; FL has no tempo marker): at the time selection's start, else the song position
  11273. timeMarkers.addItem (tr ("Add tempo change...") + " (LYNX)", [this] {
  11274. const auto& sg = engine.getSong();
  11275. editTempoMarker (sg.hasLoop() ? sg.loopStart : snap ((double) songPositionTick(), true), -1);
  11276. });
  11277. timeMarkers.addItem (tr ("Place loop") + "\tShift+T", [this] { runAction ("playlist.markerLoop"); });
  11278. // issue #281 (round 190qr): FL's Time markers › Delete, between Place loop and Change to marker loop
  11279. timeMarkers.addItem (tr ("Delete"), ! song.markers().empty(), false, [this] {
  11280. engine.editSong ([] (Song& s) { markers::deleteInSelection (s); });
  11281. repaint();
  11282. });
  11283. timeMarkers.addItem (tr ("Change to marker loop"), song.hasLoop(), false, [this] {
  11284. engine.editSong ([] (Song& s) { markers::changeToMarkerLoop (s); });
  11285. });
  11286. menu.addSubMenu (tr ("Time markers"), timeMarkers);
  11287. juce::PopupMenu quantize;
  11288. const auto current = engine.quantizeSongJumps.load();
  11289. for (auto [value, text] : { std::pair { 0, TR_NOOP ("Off") }, { 1, TR_NOOP ("Beats") }, { 2, TR_NOOP ("Bars") }, { 3, TR_NOOP ("2 bars") },
  11290. { 4, TR_NOOP ("4 bars") }, { 5, TR_NOOP ("8 bars") } })
  11291. quantize.addItem (tr (text), true, current == value, [this, value = value] { engine.quantizeSongJumps.store (value); });
  11292. menu.addSubMenu (tr ("Quantize song jumps"), quantize);
  11293. }
  11294. if (near >= 0)
  11295. {
  11296. menu.addSeparator();
  11297. menu.addSectionHeader (markerLabel (song.markers()[(std::size_t) near]));
  11298. // FL's marker menu (FL 2026, round 190qr shot 281-fl-marker-menu.png): the header, Delete, Rename..., ...
  11299. menu.addItem (tr ("Delete"), [this, near] {
  11300. engine.editSong ([near] (Song& s) {
  11301. if (near < (int) s.markers().size())
  11302. s.markers().erase (s.markers().begin() + near);
  11303. });
  11304. repaint();
  11305. });
  11306. menu.addItem (tr ("Rename marker..."), [this, near] { editMarkerName (0, near); });
  11307. menu.addItem (tr ("Place loop (from this marker to the next)"), [this, near] {
  11308. engine.editSong ([near] (Song& s) {
  11309. if (near >= (int) s.markers().size())
  11310. return;
  11311. const auto from = s.markers()[(std::size_t) near].tick;
  11312. std::int64_t to = s.songLength();
  11313. for (const auto& m : s.markers())
  11314. if (m.tick > from)
  11315. {
  11316. to = m.tick;
  11317. break;
  11318. }
  11319. if (to > from)
  11320. {
  11321. s.loopStart = from;
  11322. s.loopEnd = to;
  11323. }
  11324. }, false);
  11325. });
  11326. {
  11327. // FL's marker "Action" list, in FL's order (the values are FL's .flp marker types)
  11328. juce::PopupMenu action;
  11329. const auto& marker = song.markers()[(std::size_t) near];
  11330. const auto current = marker.isSignature() ? Marker::timeSignature : marker.action;
  11331. // (FL's Playlist shows these 9; Pattern length, Bar override and Key/Scale are its Piano Roll markers' actions)
  11332. for (auto [value, text] : { std::pair { Marker::none, TR_NOOP ("None (plain marker)") }, { Marker::start, TR_NOOP ("Start") },
  11333. { Marker::songLoop, TR_NOOP ("Loop") }, { Marker::markerLoop, TR_NOOP ("Marker loop") },
  11334. { Marker::markerSkip, TR_NOOP ("Marker skip") }, { Marker::markerPause, TR_NOOP ("Marker pause") },
  11335. { Marker::timeSignature, TR_NOOP ("Time signature") }, { Marker::punchIn, TR_NOOP ("Start recording") },
  11336. { Marker::punchOut, TR_NOOP ("Stop recording") } })
  11337. action.addItem (tr (text), true, current == value, [this, near, value = value] {
  11338. engine.editSong ([near, value] (Song& s) {
  11339. if (near < (int) s.markers().size())
  11340. markers::setAction (s, s.markers()[(std::size_t) near], value);
  11341. });
  11342. });
  11343. menu.addSubMenu (tr ("Marker action"), action);
  11344. }
  11345. }
  11346. if (song.hasLoop())
  11347. {
  11348. menu.addSeparator();
  11349. menu.addItem (tr ("Remove loop"), [this] { engine.editSong ([] (Song& s) { s.loopStart = s.loopEnd = 0; }, false); });
  11350. // round 190cg: the loop switched off keeps its range
  11351. menu.addItem (tr ("Loop the time selection"), true, song.loopPlays(), [this] { runAction ("playlist.loopSwitch"); });
  11352. }
  11353. menu.addSeparator();
  11354. {
  11355. // FL's Select submenu (REA round 153; FL's full list and order, round 189e)
  11356. menu.addSubMenu (tr ("Select"), selectMenu());
  11357. }
  11358. menu.addItem (tr ("Ripple editing (resizing and deleting move the later clips)") + "\tShift+S", true, ripple, [this] { setRipple (! ripple); });
  11359. {
  11360. auto anyAudio = false;
  11361. for (auto i : selection)
  11362. anyAudio = anyAudio || (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio);
  11363. menu.addItem (tr ("Pitch selected audio clips one semitone down") + "\t7", anyAudio, false, [this] { runAction ("playlist.pitchClipsDown"); });
  11364. menu.addItem (tr ("Pitch selected audio clips one semitone up") + "\t8", anyAudio, false, [this] { runAction ("playlist.pitchClipsUp"); });
  11365. menu.addItem (tr ("Reverse selected audio clips") + "\t9", anyAudio, false, [this] { runAction ("playlist.reverseClips"); });
  11366. }
  11367. menu.addItem (tr ("Automatic crossfades (current project)"), true, engine.getSong().autoCrossfades, [this] { runAction ("playlist.autoCrossfades"); });
  11368. // LYNX extra (round 190gz, issue #170)
  11369. menu.addItem (tr ("Link Playlist tracks to mixer tracks (current project)"), true, engine.getSong().linkTracksToMixer,
  11370. [this] { runAction ("playlist.linkTracks"); });
  11371. // FL's legacy Pattern Blocks (round 170f)
  11372. menu.addItem (tr ("Pattern blocks (current project)"), true, engine.getSong().patternBlocksOn, [this] { runAction ("playlist.patternBlocks"); });
  11373. menu.addItem (tr ("Turn pattern blocks into clips"), ! engine.getSong().blocks.empty(), false, [this] { runAction ("playlist.blocksToClips"); });
  11374. menu.addItem (tr ("Automation lanes"), true, autolanes::shown(), [this] { runAction ("playlist.automationLanes"); }); // round 177b
  11375. {
  11376. juce::PopupMenu zoom;
  11377. zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("playlist.zoomIn"); });
  11378. zoom.addItem (tr ("Zoom out") + "\tPageDown", [this] { runAction ("playlist.zoomOut"); });
  11379. zoom.addItem (tr ("Zoom: one bar") + "\tShift+1", [this] { runAction ("playlist.zoom1"); });
  11380. zoom.addItem (tr ("Zoom: four bars") + "\tShift+2", [this] { runAction ("playlist.zoom2"); });
  11381. zoom.addItem (tr ("Zoom: sixteen bars") + "\tShift+3", [this] { runAction ("playlist.zoom3"); });
  11382. zoom.addItem (tr ("Zoom to show everything") + "\tShift+4", [this] { runAction ("playlist.zoomAll"); });
  11383. zoom.addItem (tr ("Zoom to the selection") + "\tShift+5", [this] { runAction ("playlist.zoomSelection"); });
  11384. zoom.addItem (tr ("Previous view"), viewStack.depth() > 0, false, [this] { runAction ("playlist.previousView"); }); // round 190qe
  11385. zoom.addItem (tr ("Centre the view on the playhead") + "\tShift+0", [this] { runAction ("playlist.centrePlayhead"); });
  11386. // issue #276 (round 190qr): the LYNX extra's switch
  11387. zoom.addSeparator();
  11388. zoom.addItem (tr ("Zoom around the song position") + " (LYNX)", true, zoomanchor::atSongPosition(),
  11389. [] { workflowextras::setExtra ("editing.zoomAtSongPosition", ! zoomanchor::atSongPosition()); });
  11390. // round 190ro (D-2): round 190qe's zoom keys, off as FL in the Pattern layout
  11391. zoom.addItem (tr ("Zoom keys: LYNX's anchor, and Shift+5 again goes back (LYNX)"), true, zoomanchor::lynxKeys(),
  11392. [] { workflowextras::setExtra ("editing.zoomKeysLynx", ! zoomanchor::lynxKeys()); });
  11393. menu.addSubMenu (tr ("Zoom"), zoom);
  11394. }
  11395. return menu;
  11396. }
  11397. void PlaylistComponent::showFollowMenu()
  11398. {
  11399. juce::PopupMenu menu;
  11400. menu.addItem (tr("Continuous scrolling"), true, EditorGlobals::get().isContinuousScroll(), [] {
  11401. EditorGlobals::get().setContinuousScroll (! EditorGlobals::get().isContinuousScroll());
  11402. });
  11403. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&followButton));
  11404. }
  11405. void PlaylistComponent::showRulerMenu (int x, int y)
  11406. {
  11407. if (const auto marker = y >= 0 ? markerTagAt (x, y) : -1; marker >= 0)
  11408. return markerMenu (marker, x).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  11409. rulerMenu (x, y).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  11410. }
  11411. // Round 190ol (P6): the Simple layout's "Change time signature here...": numerator 1-16, denominator 2 / 4 / 8 / 16, the
  11412. // signature in force at that bar to start with; on bar 1 it is the song's own (the top bar's box shows it)
  11413. void PlaylistComponent::askSimpleSignature (std::int64_t bar)
  11414. {
  11415. const auto& song = engine.getSong();
  11416. const auto current = bar <= 0 ? signatureedit::atStart (song) : markers::signatureAt (song, bar);
  11417. auto* window = new juce::AlertWindow (tr ("Change time signature here..."), tr ("From bar {0}", { juce::String (song.barAt (bar).number) }),
  11418. juce::MessageBoxIconType::NoIcon, this);
  11419. juce::StringArray numerators, denominators;
  11420. for (int n = signatureedit::minNumerator; n <= signatureedit::maxNumerator; ++n)
  11421. numerators.add (juce::String (n));
  11422. for (const auto d : signatureedit::denominators)
  11423. denominators.add (juce::String (d));
  11424. window->addComboBox ("numerator", numerators, tr ("Numerator"));
  11425. window->addComboBox ("denominator", denominators, tr ("Denominator"));
  11426. window->getComboBoxComponent ("numerator")->setText (juce::String (current.first), juce::dontSendNotification);
  11427. window->getComboBoxComponent ("denominator")->setText (juce::String (signatureedit::clampDenominator (current.second)), juce::dontSendNotification);
  11428. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  11429. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  11430. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, bar, window] (int result) {
  11431. if (result != 1)
  11432. return;
  11433. const auto n = window->getComboBoxComponent ("numerator")->getText().getIntValue();
  11434. const auto d = window->getComboBoxComponent ("denominator")->getText().getIntValue();
  11435. engine.editSong ([bar, n, d] (Song& s) { signatureedit::set (s, bar, n, d); });
  11436. repaint();
  11437. }),
  11438. true);
  11439. }
  11440. void PlaylistComponent::editMarkerName (std::int64_t tick, int existing)
  11441. {
  11442. const auto& markers = engine.getSong().markers();
  11443. const auto current = existing >= 0 && existing < (int) markers.size() ? juce::String::fromUTF8 (markers[(std::size_t) existing].name.c_str())
  11444. : tr ("Marker");
  11445. auto* window = new juce::AlertWindow (existing >= 0 ? tr ("Rename marker") : tr ("New marker"), {}, juce::MessageBoxIconType::NoIcon);
  11446. window->addTextEditor ("name", current);
  11447. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  11448. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  11449. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, tick, existing, window] (int result) {
  11450. if (result != 1)
  11451. return;
  11452. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  11453. engine.editSong ([tick, existing, name] (Song& s) {
  11454. if (existing < 0)
  11455. s.addMarker ({ tick, name, 0, 4 });
  11456. else if (existing < (int) s.markers().size())
  11457. s.markers()[(std::size_t) existing].name = name;
  11458. });
  11459. }),
  11460. true);
  11461. }
  11462. void PlaylistComponent::showClipMenu (int index)
  11463. {
  11464. auto menu = withRegionLoopItems (buildClipMenu (index, getMouseXYRelative().x), index);
  11465. if (menu.getNumItems() > 0)
  11466. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  11467. }
  11468. juce::Rectangle<int> PlaylistComponent::openClipMenuForDemo (int index)
  11469. {
  11470. if (index < 0 || index >= (int) engine.getSong().playlist.size())
  11471. return {};
  11472. const auto bounds = clipBounds (index).getIntersection (getLocalBounds());
  11473. if (bounds.isEmpty())
  11474. return {};
  11475. if (! isSelected (index))
  11476. setSelection ({ index }); // (a right-click on a clip selects it first)
  11477. const auto at = bounds.getCentre();
  11478. auto menu = withRegionLoopItems (buildClipMenu (index, at.x), index);
  11479. if (menu.getNumItems() > 0)
  11480. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withTargetScreenArea (localAreaToGlobal (juce::Rectangle<int> (at.x, at.y, 1, 1))));
  11481. return localAreaToGlobal (bounds);
  11482. }
  11483. // round 190jr (BUILD-LIST 13, BandLab's region loop): the Simple layout's loop items, added at the end of the clip's own
  11484. // menu (its layout and header stay as they are)
  11485. juce::PopupMenu PlaylistComponent::withRegionLoopItems (juce::PopupMenu menu, int index)
  11486. {
  11487. if (! simpleHeaders || ! regionloop::loopable (engine.getSong(), index) || menu.getNumItems() == 0)
  11488. return menu;
  11489. const auto run = regionloop::runOf (engine.getSong(), index);
  11490. const auto& region = engine.getSong().playlist[(std::size_t) run.clips.front()];
  11491. auto at = [this, track = region.track, start = region.start, like = region] { return regionloop::regionAt (engine.getSong(), track, start, like); };
  11492. menu.addSeparator();
  11493. menu.addItem (tr ("Loop until next"), [this, at] {
  11494. const auto end = juce::jmax (engine.getSong().songLength(), (std::int64_t) 0);
  11495. engine.editSong ([end, region = at()] (Song& s) { regionloop::loopUntilNext (s, region, end); });
  11496. sortClips();
  11497. });
  11498. menu.addItem (tr ("Unloop"), run.passes() > 1, false, [this, at] {
  11499. engine.editSong ([region = at()] (Song& s) { regionloop::unloop (s, region); });
  11500. sortClips();
  11501. });
  11502. return menu;
  11503. }
  11504. juce::PopupMenu PlaylistComponent::getClipMenuForSnapshot (int index)
  11505. {
  11506. if (index < 0 || index >= (int) engine.getSong().playlist.size())
  11507. return {};
  11508. const auto& c = engine.getSong().playlist[(std::size_t) index];
  11509. return withRegionLoopItems (buildClipMenu (index, (int) tickToX ((double) c.start + (double) c.length / 2.0)), index);
  11510. }
  11511. // "Follow the project key" (with what it does now) and "Loop key ▸" for an audio clip (round 190ds, core/KeyFollow.h)
  11512. void PlaylistComponent::addKeyFollowItems (juce::PopupMenu& menu, int index, const std::vector<int>& targets)
  11513. {
  11514. const auto& song = engine.getSong();
  11515. const auto& clip = song.playlist[(std::size_t) index];
  11516. const auto key = keyfollow::loopKeyOf (song, clip.channel);
  11517. const auto keyText = [] (const keyfollow::LoopKey& k) {
  11518. return juce::String (projectkey::rootName (k.root)) + " " + (k.minor ? tr ("minor") : tr ("major"));
  11519. };
  11520. juce::String state;
  11521. if (! key)
  11522. state = tr ("the loop's key is not known");
  11523. else if (! projectkey::get (song))
  11524. state = tr ("no project key");
  11525. else if (clip.followKey)
  11526. {
  11527. const auto shift = keyfollow::shiftOf (song, clip);
  11528. state = shift == 0 ? tr ("already in key") : tr ("moved {0} semitones", { (shift > 0 ? "+" : "") + juce::String (shift) });
  11529. }
  11530. menu.addSeparator();
  11531. menu.addItem (tr ("Follow the project key") + (state.isEmpty() ? juce::String() : " (" + state + ")"), key.has_value(), clip.followKey,
  11532. [this, targets, on = ! clip.followKey] { engine.editSong ([targets, on] (Song& s) { keyfollow::setFollow (s, targets, on); }); });
  11533. juce::PopupMenu keys;
  11534. const auto channel = clip.channel;
  11535. for (const bool minor : { false, true })
  11536. {
  11537. juce::PopupMenu roots;
  11538. for (int r = 0; r < 12; ++r)
  11539. roots.addItem (juce::String (projectkey::rootName (r)), true, key && key->root == r && key->minor == minor, [this, channel, r, minor] {
  11540. engine.editSong ([channel, r, minor] (Song& s) { keyfollow::setLoopKey (s, channel, keyfollow::LoopKey { r, minor }, 3); });
  11541. });
  11542. keys.addSubMenu (minor ? tr ("Minor") : tr ("Major"), roots);
  11543. }
  11544. keys.addSeparator();
  11545. // round 190kx: the key of the audio itself (core/LoopAnalysis detectKey, on a worker thread): found, it becomes the
  11546. // loop key ("detected"); not found, the hint says so and nothing changes
  11547. {
  11548. const auto path = juce::String::fromUTF8 (song.channels[(std::size_t) channel].samplePath.c_str());
  11549. keys.addItem (tr ("Detect from the audio"), path.isNotEmpty(), false, [this, channel, path] {
  11550. auto sample = engine.getSampleLibrary().load (path);
  11551. if (sample == nullptr)
  11552. return;
  11553. ui::postHint ({ tr ("Detecting the loop's key..."), {}, false, false });
  11554. juce::Thread::launch ([safe = juce::Component::SafePointer<PlaylistComponent> (this), sample, channel, path] {
  11555. const auto d = loopanalysis::detectKey (*sample);
  11556. juce::MessageManager::callAsync ([safe, d, channel, path] {
  11557. if (safe == nullptr)
  11558. return;
  11559. auto& song = safe->engine.getSong();
  11560. if (channel >= (int) song.channels.size() || juce::String::fromUTF8 (song.channels[(std::size_t) channel].samplePath.c_str()) != path)
  11561. return; // (the channel changed meanwhile)
  11562. if (! d.key)
  11563. {
  11564. ui::postHint ({ tr ("No clear key in this audio (drums, noise or too short)"), {}, false, false });
  11565. return;
  11566. }
  11567. const auto key = *d.key;
  11568. safe->engine.editSong ([channel, key] (Song& s) { keyfollow::setLoopKey (s, channel, key, 2); });
  11569. ui::postHint ({ tr ("Loop key"), juce::String (projectkey::rootName (key.root)) + " " + (key.minor ? tr ("minor") : tr ("major")), false, false });
  11570. });
  11571. });
  11572. });
  11573. }
  11574. keys.addItem (tr ("Not known"), true, ! key, [this, channel] { engine.editSong ([channel] (Song& s) { keyfollow::setLoopKey (s, channel, std::nullopt, 0); }); });
  11575. const auto source = song.channels[(std::size_t) channel].sampler.loopKeySource;
  11576. menu.addSubMenu (tr ("Loop key") + (key ? ": " + keyText (*key) + (source == 1 ? " (" + tr ("from its name") + ")" : source == 2 ? " (" + tr ("detected") + ")" : juce::String())
  11577. : juce::String()),
  11578. keys);
  11579. menu.addSeparator();
  11580. }
  11581. namespace
  11582. {
  11583. // Live's audio clip › Slice to New MIDI Track (round 190ec; dialog as Live's since round 190el, 190ei B6): "Create one
  11584. // slice per" (Warp Marker, Transient, Bar, 1/2 Note … 1/32 Note), the count line, "Slicing Preset" and "Preserve warped
  11585. // timing", then a new channel holding a Drum Rack named after the clip with one pad per slice ("Slice 1"… from C1) and
  11586. // a pattern that replays the slices where they were, on a new track under the clip, all named after the clip
  11587. // (core/Rack.h). The presets are LYNX's own (Live's slicing presets are Live content): Default (the facts of Live's
  11588. // Default: gated, choke group 1) or One-shot.
  11589. struct ClipSlices
  11590. {
  11591. std::vector<float> slices; // starts, fractions of the file
  11592. float from = 0.0f, to = 1.0f;
  11593. double beats = 0.0; // the clip region's length
  11594. std::function<double (float)> tickOf;
  11595. std::string name, samplePath;
  11596. std::uint32_t colour = 0;
  11597. bool ok = false;
  11598. };
  11599. ClipSlices clipSlices (AudioEngine& engine, int clipIndex, rack::SlicePer per, bool preserveWarpedTiming)
  11600. {
  11601. ClipSlices out;
  11602. const auto& song = engine.getSong();
  11603. if (clipIndex < 0 || clipIndex >= (int) song.playlist.size())
  11604. return out;
  11605. const auto clip = song.playlist[(std::size_t) clipIndex];
  11606. if (clip.kind != ClipKind::audio || clip.channel < 0 || clip.channel >= (int) song.channels.size())
  11607. return out;
  11608. const auto channel = song.channels[(std::size_t) clip.channel];
  11609. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str()));
  11610. if (sample == nullptr || sample->frames() == 0 || sample->sampleRate <= 0.0 || clipops::playsBackwards (channel, clip))
  11611. return out;
  11612. // the part of the file the clip plays, as fractions of the file (the clip's own timing: its trim, stretch and pitch)
  11613. const auto fileFrames = (double) sample->frames();
  11614. const auto span = clipops::clipSpan (channel, sample);
  11615. const auto perTick = clipops::framesPerTick (channel, clip, (double) span.frames, sample->sampleRate, song.bpm);
  11616. if (perTick <= 0.0)
  11617. return out;
  11618. out.from = (float) std::clamp (((double) span.first + (double) clip.offset * perTick) / fileFrames, 0.0, 1.0);
  11619. out.to = (float) std::clamp (((double) span.first + (double) (clip.offset + clip.length) * perTick) / fileFrames, (double) out.from, 1.0);
  11620. out.beats = (double) clip.length / (double) ppq;
  11621. switch (per)
  11622. {
  11623. case rack::SlicePer::transient:
  11624. out.slices = rack::slicesInRegion (detectSlices (*sample, 0.5f, rack::drumPadCount), out.from, out.to);
  11625. break;
  11626. case rack::SlicePer::warpMarker: // (seconds of the file)
  11627. {
  11628. std::vector<float> marks;
  11629. for (const auto& w : channel.sampler.warp)
  11630. marks.push_back ((float) (w.seconds * sample->sampleRate / fileFrames));
  11631. out.slices = rack::slicesInRegion (marks, out.from, out.to);
  11632. break;
  11633. }
  11634. default: // a bar or a note division (a whole note = 4 beats), in the clip's time
  11635. {
  11636. const auto secondsPerSlice = rack::slicePerBeats (per, song.meter()) * ppq * perTick / sample->sampleRate;
  11637. out.slices = rack::gridSlices (fileFrames / sample->sampleRate, out.from, out.to, secondsPerSlice);
  11638. break;
  11639. }
  11640. }
  11641. // Preserve warped timing on: the notes where the clip plays each slice (its stretch and pitch); off: at the file's
  11642. // own timing from the clip's start, at the song tempo
  11643. const auto fromFrame = (double) span.first + (double) clip.offset * perTick;
  11644. if (preserveWarpedTiming)
  11645. out.tickOf = [=] (float fraction) { return ((double) fraction * fileFrames - (double) span.first) / perTick - (double) clip.offset; };
  11646. else
  11647. out.tickOf = [=, rate = sample->sampleRate, bpm = song.bpm] (float fraction) {
  11648. return ((double) fraction * fileFrames - fromFrame) / rate * std::max (1.0, bpm) / 60.0 * (double) ppq;
  11649. };
  11650. const auto stem = juce::File (juce::String::fromUTF8 (channel.samplePath.c_str())).getFileNameWithoutExtension().toStdString();
  11651. out.name = ! channel.name.empty() ? channel.name : stem; // (the audio clip's name: its channel's, as the Playlist shows it)
  11652. out.samplePath = channel.samplePath;
  11653. out.colour = channel.colour;
  11654. out.ok = true;
  11655. return out;
  11656. }
  11657. void sliceClipToNewTrack (AudioEngine& engine, int clipIndex, rack::SlicePer per, bool oneShot, bool preserveWarpedTiming, std::function<void()> done)
  11658. {
  11659. const auto cut = clipSlices (engine, clipIndex, per, preserveWarpedTiming);
  11660. if (! cut.ok)
  11661. return;
  11662. auto notes = rack::sliceNotes (cut.slices, cut.to, cut.tickOf, 0);
  11663. auto drum = rack::sliceToDrumRack (cut.samplePath, cut.slices, tr ("Slice").toStdString(), oneShot ? rack::SliceTemplate::oneShot : rack::SliceTemplate::gated,
  11664. cut.to, cut.name);
  11665. drum.colour = cut.colour;
  11666. const auto capped = (int) cut.slices.size() > rack::maxSlicePads;
  11667. auto added = -1;
  11668. engine.editSong ([&] (Song& s) {
  11669. added = rack::addSliceTrack (s, clipIndex, std::move (drum), std::move (notes), cut.name);
  11670. if (added >= 0)
  11671. s.currentPattern = (int) s.patterns.size() - 1;
  11672. });
  11673. if (capped && added >= 0)
  11674. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Slice to New MIDI Track"),
  11675. tr ("Only the first {0} slices got a pad.", { juce::String (rack::maxSlicePads) }));
  11676. if (done)
  11677. done();
  11678. }
  11679. // Live's line under "Create one slice per": "The current clip region is 64 beats long - this will result in 128 slices."
  11680. juce::String sliceCountLine (const ClipSlices& cut)
  11681. {
  11682. const auto beats = std::abs (cut.beats - std::round (cut.beats)) < 0.005 ? juce::String (juce::roundToInt (cut.beats)) : juce::String (cut.beats, 2);
  11683. return tr ("The current clip region is {0} beats long - this will result in {1} slices.", { beats, juce::String ((int) cut.slices.size()) });
  11684. }
  11685. // The dialog's own rows: the count line and the Preserve warped timing switch (an AlertWindow holds them, not owns them)
  11686. struct SliceDialogExtras
  11687. {
  11688. juce::Label count;
  11689. juce::Label preserveLabel;
  11690. juce::TextButton preserve;
  11691. juce::Component preserveRow;
  11692. };
  11693. juce::AlertWindow* buildSliceDialog (AudioEngine& engine, juce::Component* owner, int clipIndex, const std::shared_ptr<SliceDialogExtras>& extras)
  11694. {
  11695. auto* box = new juce::AlertWindow (tr ("Slice to New MIDI track"), {}, juce::MessageBoxIconType::NoIcon, owner);
  11696. const juce::StringArray per { tr ("Warp Marker"), tr ("Transient"), tr ("Bar"), tr ("1/2 Note"), tr ("1/4 Note"), tr ("1/8 Note"), tr ("1/16 Note"), tr ("1/32 Note") };
  11697. box->addComboBox ("per", per, tr ("Create one slice per:"));
  11698. box->getComboBoxComponent ("per")->setSelectedItemIndex ((int) rack::SlicePer::transient, juce::dontSendNotification);
  11699. extras->count.setJustificationType (juce::Justification::centredLeft);
  11700. extras->count.setSize (380, 40);
  11701. extras->count.setMinimumHorizontalScale (0.8f);
  11702. box->addCustomComponent (&extras->count);
  11703. box->addComboBox ("preset", { tr ("Default"), tr ("One-shot") }, tr ("Slicing Preset:"));
  11704. extras->preserveLabel.setText (tr ("Preserve warped timing:"), juce::dontSendNotification);
  11705. extras->preserve.setClickingTogglesState (true);
  11706. extras->preserve.setToggleState (true, juce::dontSendNotification);
  11707. extras->preserve.setButtonText (tr ("On"));
  11708. extras->preserveRow.addAndMakeVisible (extras->preserveLabel);
  11709. extras->preserveRow.addAndMakeVisible (extras->preserve);
  11710. extras->preserveRow.setSize (380, 26);
  11711. extras->preserveLabel.setBounds (0, 2, 300, 22);
  11712. extras->preserve.setBounds (310, 2, 60, 22);
  11713. box->addCustomComponent (&extras->preserveRow);
  11714. const auto update = [box, &engine, clipIndex, x = extras.get()] { // (raw: whoever holds the dialog keeps the extras)
  11715. const auto cut = clipSlices (engine, clipIndex, (rack::SlicePer) std::clamp (box->getComboBoxComponent ("per")->getSelectedItemIndex(), 0, rack::slicePerCount - 1),
  11716. x->preserve.getToggleState());
  11717. x->count.setText (cut.ok ? sliceCountLine (cut) : juce::String(), juce::dontSendNotification);
  11718. x->preserve.setButtonText (x->preserve.getToggleState() ? tr ("On") : tr ("Off"));
  11719. };
  11720. box->getComboBoxComponent ("per")->onChange = update;
  11721. extras->preserve.onClick = update;
  11722. update();
  11723. box->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  11724. box->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  11725. return box;
  11726. }
  11727. // Round 190hp (slice B18): the "Split at silence" dialog — Threshold (dB), Minimum silence, Pre-roll and Post-roll (ms),
  11728. // with the last values used
  11729. juce::AlertWindow* buildSplitSilenceDialog (juce::Component* owner)
  11730. {
  11731. const auto& o = PlaylistComponent::splitSilenceOptions();
  11732. auto* box = new juce::AlertWindow (tr ("Split at silence"), tr ("Cuts the clip where it stays below the threshold and removes those quiet parts. The file is not changed."),
  11733. juce::MessageBoxIconType::NoIcon, owner);
  11734. box->addTextEditor ("threshold", juce::String (o.thresholdDb, 1), tr ("Threshold (dB)"));
  11735. box->addTextEditor ("minimum", juce::String (juce::roundToInt (o.minSilenceMs)), tr ("Minimum silence (ms)"));
  11736. box->addTextEditor ("pre", juce::String (juce::roundToInt (o.preRollMs)), tr ("Pre-roll (ms)"));
  11737. box->addTextEditor ("post", juce::String (juce::roundToInt (o.postRollMs)), tr ("Post-roll (ms)"));
  11738. box->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  11739. box->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  11740. return box;
  11741. }
  11742. stripsilence::Options readSplitSilenceDialog (juce::AlertWindow& box)
  11743. {
  11744. stripsilence::Options o;
  11745. o.thresholdDb = juce::jlimit (-96.0f, 0.0f, box.getTextEditorContents ("threshold").trim().getFloatValue());
  11746. o.minSilenceMs = juce::jlimit (0.0, 10000.0, box.getTextEditorContents ("minimum").trim().getDoubleValue());
  11747. o.preRollMs = juce::jlimit (0.0, 2000.0, box.getTextEditorContents ("pre").trim().getDoubleValue());
  11748. o.postRollMs = juce::jlimit (0.0, 5000.0, box.getTextEditorContents ("post").trim().getDoubleValue());
  11749. return o;
  11750. }
  11751. void showSliceToNewTrackDialog (AudioEngine& engine, juce::Component& owner, int clipIndex, std::function<void()> done)
  11752. {
  11753. auto extras = std::make_shared<SliceDialogExtras>();
  11754. auto* box = buildSliceDialog (engine, &owner, clipIndex, extras);
  11755. box->enterModalState (true, juce::ModalCallbackFunction::create ([box, &engine, clipIndex, done, extras] (int result) {
  11756. if (result != 1)
  11757. return;
  11758. const auto per = (rack::SlicePer) std::clamp (box->getComboBoxComponent ("per")->getSelectedItemIndex(), 0, rack::slicePerCount - 1);
  11759. const auto oneShot = box->getComboBoxComponent ("preset")->getSelectedItemIndex() == 1;
  11760. sliceClipToNewTrack (engine, clipIndex, per, oneShot, extras->preserve.getToggleState(), done);
  11761. }),
  11762. true);
  11763. }
  11764. } // namespace
  11765. std::unique_ptr<juce::Component> makeSliceDialogForSnapshot (AudioEngine& engine, int clipIndex, int per)
  11766. {
  11767. struct Holder final : juce::Component
  11768. {
  11769. std::shared_ptr<SliceDialogExtras> extras = std::make_shared<SliceDialogExtras>();
  11770. std::unique_ptr<juce::AlertWindow> box;
  11771. ~Holder() override { box.reset(); }
  11772. };
  11773. auto holder = std::make_unique<Holder>();
  11774. holder->box.reset (buildSliceDialog (engine, nullptr, clipIndex, holder->extras));
  11775. holder->box->getComboBoxComponent ("per")->setSelectedItemIndex (std::clamp (per, 0, rack::slicePerCount - 1), juce::sendNotificationSync);
  11776. holder->addAndMakeVisible (*holder->box);
  11777. holder->box->setTopLeftPosition (0, 0);
  11778. holder->setSize (holder->box->getWidth(), holder->box->getHeight());
  11779. return holder;
  11780. }
  11781. namespace
  11782. {
  11783. // Round 190ff, the Clip-launch workflow only: the reference's group in its arrangement clip menu — Freeze Track, Bounce
  11784. // Track in Place, Bounce to New Track [SHOT live190ei/shots/live-audioclip-context-menu.png] — and Consolidate (its
  11785. // Ctrl+J, Edit menu) for the clip's track (core/StandIns.h lynx::freeze). Elsewhere nothing is added.
  11786. void addLiveTrackItems (AudioEngine& engine, juce::PopupMenu& menu, int index, const std::vector<int>& targets, std::function<void()> changed)
  11787. {
  11788. if (! EditorGlobals::get().clipLaunchWorkflow)
  11789. return;
  11790. const auto& song = engine.getSong();
  11791. if (index < 0 || index >= (int) song.playlist.size())
  11792. return;
  11793. const auto track = song.playlist[(std::size_t) index].track;
  11794. const auto channel = detailchain::forTrack (song, track).channel;
  11795. const auto valid = channel >= 0 && channel < (int) song.channels.size();
  11796. const auto frozen = valid && song.channels[(std::size_t) channel].freeze.on();
  11797. const auto audioChannel = valid && song.channels[(std::size_t) channel].instrument == InstrumentKind::audioClip;
  11798. menu.addSeparator();
  11799. menu.addItem (frozen ? tr ("Unfreeze Track") : tr ("Freeze Track"), valid && ! audioChannel, false, [&engine, channel, frozen, changed] {
  11800. if (frozen)
  11801. {
  11802. unfreezeChannel (engine, channel);
  11803. changed();
  11804. }
  11805. else
  11806. freezeTrack (engine, channel, [changed] (bool) { changed(); });
  11807. });
  11808. menu.addItem (tr ("Bounce Track in Place"), valid && ! audioChannel, false, [&engine, channel, changed] {
  11809. bounceTrackInPlace (engine, channel);
  11810. changed();
  11811. });
  11812. freeze::BouncePlan bounce;
  11813. menu.addItem (tr ("Bounce to New Track"), freeze::planBounceToNewTrack (song, targets, bounce) == nullptr, false, [&engine, targets] {
  11814. bounceToNewTrack (engine, targets);
  11815. });
  11816. freeze::ConsolidatePlan consolidate;
  11817. menu.addItem (tr ("Consolidate"), targets.size() > 1 && freeze::planConsolidate (song, targets, consolidate) == nullptr, false, [&engine, targets, changed] {
  11818. consolidateClips (engine, targets);
  11819. changed();
  11820. });
  11821. }
  11822. } // namespace
  11823. // Round 190fm: the groove of Playlist pattern clips, as Live's Clip View chooser offers it for Arrangement clips [STR:
  11824. // .GrooveChooser / .GrooveCommitButton in every clip's panel]: the chooser (None, the pool's grooves, a groove added
  11825. // now), Commit groove and Extract groove. FL's clip menu has none of this: the items appear in the Clip-launch layout,
  11826. // or once the project has a groove pool, or on a clip that already plays through a groove.
  11827. void PlaylistComponent::addGrooveItems (juce::PopupMenu& menu, int index, const std::vector<int>& targets)
  11828. {
  11829. const auto& song = engine.getSong();
  11830. const auto& clip = song.playlist[(std::size_t) index];
  11831. if (layoutstyle::current() != layoutstyle::Style::clipLaunch && song.grooves.grooves.empty() && clip.groove == 0)
  11832. return;
  11833. menu.addSeparator();
  11834. juce::PopupMenu chooser;
  11835. const auto set = [this, targets] (std::uint32_t id) {
  11836. engine.editSong ([targets, id] (Song& s) { groove::setPlaylistClipGroove (s, targets, id); });
  11837. repaint();
  11838. };
  11839. chooser.addItem (tr ("None"), true, clip.groove == 0, [set] { set (0); });
  11840. for (const auto& g : song.grooves.grooves)
  11841. chooser.addItem (juce::String::fromUTF8 (g.name.c_str()), true, clip.groove == g.id, [set, id = g.id] { set (id); });
  11842. chooser.addSeparator();
  11843. juce::PopupMenu add;
  11844. addGrooveMenuItems (add, engine, this, [safe = juce::Component::SafePointer<PlaylistComponent> (this), targets] (std::uint32_t id) {
  11845. if (safe == nullptr)
  11846. return;
  11847. safe->engine.editSong ([targets, id] (Song& s) { groove::setPlaylistClipGroove (s, targets, id); }, false);
  11848. safe->repaint();
  11849. });
  11850. chooser.addSubMenu (tr ("Add a groove"), add);
  11851. const auto* current = groove::ofClip (song, clip);
  11852. menu.addSubMenu (current != nullptr ? tr ("Groove") + ": " + juce::String::fromUTF8 (current->name.c_str()) : tr ("Groove"), chooser);
  11853. const auto anyGroove = std::any_of (targets.begin(), targets.end(), [&song] (int i) {
  11854. return i >= 0 && i < (int) song.playlist.size() && groove::ofClip (song, song.playlist[(std::size_t) i]) != nullptr;
  11855. });
  11856. menu.addItem (tr ("Commit groove"), anyGroove, false, [this, targets] {
  11857. engine.editSong ([targets] (Song& s) {
  11858. for (const auto i : targets)
  11859. if (i >= 0)
  11860. groove::commitPlaylistClip (s, (std::size_t) i);
  11861. });
  11862. repaint();
  11863. });
  11864. menu.addItem (tr ("Extract groove"), [this, index] {
  11865. engine.editSong ([index] (Song& s) {
  11866. if (index < 0 || index >= (int) s.playlist.size())
  11867. return;
  11868. const auto& c = s.playlist[(std::size_t) index];
  11869. if (c.kind != ClipKind::pattern || c.pattern < 0 || c.pattern >= (int) s.patterns.size())
  11870. return;
  11871. auto g = groove::extractFromClip (s, c, GrooveBase::sixteenth, s.patterns[(std::size_t) c.pattern].name);
  11872. if (! g.points.empty())
  11873. groove::add (s.grooves, std::move (g));
  11874. });
  11875. });
  11876. }
  11877. juce::PopupMenu PlaylistComponent::buildClipMenu (int index, int mouseX)
  11878. {
  11879. const auto& song = engine.getSong();
  11880. juce::PopupMenu menu;
  11881. if (index < 0 || index >= (int) song.playlist.size())
  11882. return menu;
  11883. const auto clip = song.playlist[(std::size_t) index];
  11884. // FL's audio clip menu has its own layout (two columns, FL's sections; round 190dz)
  11885. if (clip.kind == ClipKind::audio && clip.channel >= 0 && clip.channel < (int) song.channels.size())
  11886. return buildAudioClipMenu (index, mouseX);
  11887. const auto targets = isSelected (index) ? selection : std::vector<int> { index };
  11888. const auto many = targets.size() > 1;
  11889. // --- the source: name, colour, uniqueness -------------------------------------------------------
  11890. juce::String sourceName;
  11891. if (clip.kind == ClipKind::pattern && clip.pattern >= 0 && clip.pattern < (int) song.patterns.size())
  11892. sourceName = juce::String::fromUTF8 (song.patterns[(std::size_t) clip.pattern].name.c_str());
  11893. else if (clip.kind == ClipKind::audio && clip.channel >= 0 && clip.channel < (int) song.channels.size())
  11894. sourceName = juce::String::fromUTF8 (song.channels[(std::size_t) clip.channel].name.c_str());
  11895. else if (clip.kind == ClipKind::automation && clip.automation >= 0 && clip.automation < (int) song.automations.size())
  11896. sourceName = juce::String::fromUTF8 (song.automations[(std::size_t) clip.automation].name.c_str());
  11897. {
  11898. // the title band in the clip's colour
  11899. auto colour = theme::colour::automation;
  11900. auto kind = tr ("Automation clip");
  11901. if (clip.kind == ClipKind::pattern)
  11902. {
  11903. colour = patternColour (song, clip.pattern);
  11904. kind = tr ("Pattern clip");
  11905. }
  11906. else if (clip.kind == ClipKind::audio && clip.channel >= 0 && clip.channel < (int) song.channels.size())
  11907. {
  11908. colour = audioClipColour (song.channels[(std::size_t) clip.channel]);
  11909. kind = tr ("Audio clip");
  11910. }
  11911. ui::addItemHeader (menu, many ? kind + " (" + juce::String ((int) targets.size()) + ")" : kind, sourceName, colour);
  11912. }
  11913. // (an audio clip's menu: buildAudioClipMenu, FL's own layout)
  11914. menu.addItem (tr ("Properties..."), [this, index, targets] {
  11915. showClipProperties (engine, index, targets, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] {
  11916. if (safe != nullptr)
  11917. safe->sortClips();
  11918. });
  11919. });
  11920. // (an audio clip's "Follow the project key" / "Loop key", round 190ds: in buildAudioClipMenu's LYNX items)
  11921. if (clip.kind == ClipKind::pattern && onRenamePattern)
  11922. menu.addItem (theme::mnemonic (tr ("Rename and color..."), 'R'), [this, p = clip.pattern] { onRenamePattern (p); });
  11923. // FL's "Change color..." / "Random color" (the clip's source: its pattern, or its audio channel)
  11924. if (clip.kind != ClipKind::automation)
  11925. {
  11926. auto setColour = [this, kind = clip.kind, src = clip.kind == ClipKind::pattern ? clip.pattern : clip.channel] (std::uint32_t colour) {
  11927. engine.editSong ([kind, src, colour] (Song& s) {
  11928. if (kind == ClipKind::pattern && src >= 0 && src < (int) s.patterns.size())
  11929. s.patterns[(std::size_t) src].colour = colour;
  11930. else if (kind == ClipKind::audio && src >= 0 && src < (int) s.channels.size())
  11931. s.channels[(std::size_t) src].colour = colour;
  11932. });
  11933. };
  11934. const auto current = clip.kind == ClipKind::pattern ? (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size() ? song.patterns[(std::size_t) clip.pattern].colour : 0u)
  11935. : (clip.channel >= 0 && clip.channel < (int) song.channels.size() ? song.channels[(std::size_t) clip.channel].colour : 0u);
  11936. menu.addSubMenu (tr ("Change color"), ui::colourMenu (current, setColour, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1)));
  11937. menu.addItem (tr ("Random color"), [setColour] {
  11938. const auto& palette = lynxPalette();
  11939. setColour (palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())]);
  11940. });
  11941. }
  11942. menu.addSeparator();
  11943. // FL's "Select source pattern / channel": the clip plays another source (patterns; audio clip channels; automations)
  11944. {
  11945. juce::PopupMenu sources;
  11946. if (clip.kind == ClipKind::pattern)
  11947. for (int p = 0; p < (int) song.patterns.size(); ++p)
  11948. sources.addItem (juce::String::fromUTF8 (song.patterns[(std::size_t) p].name.c_str()), true, p == clip.pattern,
  11949. [this, targets, p] { engine.editSong ([targets, p] (Song& s) { clipops::setClipSource (s, targets, ClipKind::pattern, p); }); });
  11950. else if (clip.kind == ClipKind::automation)
  11951. for (int a = 0; a < (int) song.automations.size(); ++a)
  11952. sources.addItem (juce::String::fromUTF8 (song.automations[(std::size_t) a].name.c_str()), true, a == clip.automation,
  11953. [this, targets, a] { engine.editSong ([targets, a] (Song& s) { clipops::setClipSource (s, targets, ClipKind::automation, a); }); });
  11954. menu.addSubMenu (clip.kind == ClipKind::pattern ? tr ("Select source pattern") : tr ("Select source channel"), sources, sources.getNumItems() > 1);
  11955. }
  11956. if (clip.kind == ClipKind::pattern)
  11957. {
  11958. menu.addItem (tr ("Make unique") + "\tShift+V+drag", [this, targets] {
  11959. engine.editSong ([targets] (Song& s) { polish::makeClipsUnique (s, targets); });
  11960. });
  11961. // round 190ne (core/TrackClips.h): a track clip's copies are unique; this one keeps sharing its notes
  11962. if (trackclips::isTrackClip (song, clip.pattern))
  11963. menu.addItem (tr ("Make linked copy") + "\tCtrl+Alt+B", [this, targets] {
  11964. setSelection (targets);
  11965. duplicateSelection (true);
  11966. });
  11967. }
  11968. else if (clip.kind == ClipKind::automation)
  11969. {
  11970. // FL's "Articulator tools" (capture 190mk A5: after Channel settings, before Make unique; round 190mk, DE-115)
  11971. menu.addSubMenu (tr ("Articulator tools"), articulator::menu (engine, clip.automation, clip.length, *this));
  11972. menu.addItem (tr ("Make unique"), [this, index] {
  11973. engine.editSong ([index] (Song& s) {
  11974. auto& c = s.playlist[(std::size_t) index];
  11975. auto copy = s.automations[(std::size_t) c.automation];
  11976. copy.name = copyname::next (copy.name, [&s] (const std::string& name) {
  11977. return std::any_of (s.automations.begin(), s.automations.end(), [&name] (const Automation& o) { return o.name == name; });
  11978. });
  11979. s.automations.push_back (std::move (copy));
  11980. c.automation = (int) s.automations.size() - 1;
  11981. });
  11982. });
  11983. }
  11984. // round 177b: with lanes on, an automation clip can become part of the lane of its target. Round 190qu (Discord 11-24):
  11985. // the selected automation clips together when this one is among them, each lane playing what played before
  11986. // (laneview::clipsIntoLanes); a clip no track owns the control of stays (greyed)
  11987. if (clip.kind == ClipKind::automation && autolanes::shown() && clip.automation >= 0 && clip.automation < (int) song.automations.size()
  11988. && song.automations[(std::size_t) clip.automation].target.kind != AutomationTargetKind::none)
  11989. {
  11990. auto chosen = std::find (selection.begin(), selection.end(), index) != selection.end() ? selection : std::vector<int> { index };
  11991. const auto lanes = laneview::laneFlags (song);
  11992. chosen.erase (std::remove_if (chosen.begin(), chosen.end(), [&song, &lanes] (int i) { return ! laneview::movable (song, i, lanes); }), chosen.end());
  11993. menu.addItem (chosen.size() > 1 ? tr ("Move the {0} selected clips into their lanes", { juce::String ((int) chosen.size()) }) : tr ("Move into lane"),
  11994. ! chosen.empty(), false, [this, chosen] {
  11995. setSelection ({});
  11996. engine.editSong ([chosen] (Song& s) { laneview::clipsIntoLanes (s, chosen); });
  11997. });
  11998. }
  11999. menu.addItem (tr ("Select all clips of this source"), [this, index] { setSelection (clipops::sameSource (engine.getSong(), index)); });
  12000. menu.addSeparator();
  12001. // --- cutting and joining -------------------------------------------------------------------------
  12002. const auto splitAt = snap (xToTick (mouseX) + gridTicks() / 2.0, true);
  12003. menu.addItem (tr ("Split here"), splitAt > clip.start && splitAt < clip.end(), false, [this, index, splitAt] {
  12004. setSelection ({});
  12005. engine.editSong ([index, splitAt] (Song& s) {
  12006. if (index < (int) s.playlist.size() && splitAt > s.playlist[(std::size_t) index].start && splitAt < s.playlist[(std::size_t) index].end())
  12007. s.playlist.push_back (splitClip (s.playlist[(std::size_t) index], splitAt));
  12008. });
  12009. sortClips();
  12010. });
  12011. {
  12012. // FL's "Chop" submenu: to the grid, or in bars / beats / parts of a beat
  12013. juce::PopupMenu chop;
  12014. auto chopBy = [this, targets] (std::int64_t grid) {
  12015. setSelection ({});
  12016. engine.editSong ([targets, grid] (Song& s) {
  12017. for (auto i : targets) // chopping adds clips at the end: indices below stay valid
  12018. noteedit::chopClip (s.playlist, i, grid);
  12019. });
  12020. sortClips();
  12021. };
  12022. chop.addItem (tr ("Chop to grid"), [chopBy, grid = gridTicks()] { chopBy (grid); });
  12023. chop.addSeparator();
  12024. const auto bar = song.barTicks();
  12025. const std::pair<const char*, std::int64_t> sizes[] = { { TR_NOOP ("Chop in bars"), bar },
  12026. { TR_NOOP ("Chop in beats"), (std::int64_t) ppq },
  12027. { TR_NOOP ("Chop in half beats"), (std::int64_t) ppq / 2 },
  12028. { TR_NOOP ("Chop in quarter beats"), (std::int64_t) ppq / 4 },
  12029. { TR_NOOP ("Chop in 8th beats"), (std::int64_t) ppq / 8 } };
  12030. for (const auto& [label, ticks] : sizes)
  12031. chop.addItem (tr (label), [chopBy, t = ticks] { chopBy (t); });
  12032. menu.addSubMenu (tr ("Chop"), chop);
  12033. }
  12034. menu.addItem (tr ("Merge clips"), clipops::canMerge (song, targets), false, [this, targets] {
  12035. setSelection ({});
  12036. engine.editSong ([targets] (Song& s) { clipops::mergeClips (s, targets); });
  12037. sortClips();
  12038. });
  12039. addLiveTrackItems (engine, menu, index, targets, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] {
  12040. if (safe != nullptr)
  12041. {
  12042. safe->setSelection ({});
  12043. safe->sortClips();
  12044. }
  12045. });
  12046. // --- pattern -------------------------------------------------------------------------------------
  12047. if (clip.kind == ClipKind::pattern)
  12048. {
  12049. menu.addSeparator();
  12050. menu.addItem (tr ("Open in Channel Rack"), [this, p = clip.pattern] {
  12051. engine.editSong ([p] (Song& s) { if (p < (int) s.patterns.size()) s.currentPattern = p; }, false);
  12052. if (onOpenPattern)
  12053. onOpenPattern();
  12054. });
  12055. menu.addItem (tr ("Open in Piano Roll"), [this, p = clip.pattern] {
  12056. engine.editSong ([p] (Song& s) { if (p < (int) s.patterns.size()) s.currentPattern = p; }, false);
  12057. if (onOpenPianoRoll)
  12058. onOpenPianoRoll();
  12059. });
  12060. addGrooveItems (menu, index, targets);
  12061. }
  12062. // --- automation ----------------------------------------------------------------------------------
  12063. if (clip.kind == ClipKind::automation && clip.automation >= 0 && clip.automation < (int) song.automations.size())
  12064. {
  12065. menu.addSeparator();
  12066. menu.addItem (tr ("Edit points..."), [this, a = clip.automation] { openAutomationEditor (engine, a); });
  12067. menu.addItem (tr ("Delete automation (all of its clips)"), [this, a = clip.automation] {
  12068. setSelection ({});
  12069. engine.editSong ([a] (Song& s) { s.removeAutomation (a); });
  12070. });
  12071. }
  12072. // --- mute and the clipboard ----------------------------------------------------------------------
  12073. menu.addSeparator();
  12074. menu.addItem (clip.muted ? tr ("Unmute") : tr ("Mute"), [this, targets, m = ! clip.muted] {
  12075. engine.editSong ([targets, m] (Song& s) {
  12076. for (auto i : targets)
  12077. if (i < (int) s.playlist.size())
  12078. s.playlist[(std::size_t) i].muted = m;
  12079. });
  12080. });
  12081. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", [this, targets] {
  12082. setSelection (targets);
  12083. copySelection();
  12084. deleteSelection();
  12085. });
  12086. menu.addItem (theme::mnemonic (tr ("Copy"), 'C') + "\tCtrl+C", [this, targets] {
  12087. setSelection (targets);
  12088. copySelection();
  12089. });
  12090. menu.addItem (theme::mnemonic (tr ("Paste here"), 'P') + "\tCtrl+V", canPasteClips(), false, [this, at = snap (xToTick (mouseX), true)] { pasteClips (at); });
  12091. menu.addItem (theme::mnemonic (many ? tr ("Delete selected") : tr ("Delete"), 'D') + "\tDel", [this, targets] {
  12092. setSelection (targets);
  12093. deleteSelection();
  12094. });
  12095. return menu;
  12096. }
  12097. // FL Studio 2026's audio clip menu (round 190dz; the model, FL's evidence and what LYNX leaves out: core/FlClipMenu.h):
  12098. // two columns — "Audio clip" and "Region" on the left, "Sample", "Automation" and "Fades" on the right — in FL's order
  12099. // and with FL's labels, then LYNX's own items (no FL counterpart) below a line at the end.
  12100. juce::PopupMenu PlaylistComponent::buildAudioClipMenu (int index, int mouseX)
  12101. {
  12102. const auto& song = engine.getSong();
  12103. juce::PopupMenu menu;
  12104. const auto clip = song.playlist[(std::size_t) index];
  12105. const auto targets = isSelected (index) ? selection : std::vector<int> { index };
  12106. const auto many = targets.size() > 1;
  12107. const auto ch = clip.channel;
  12108. const auto& channel = song.channels[(std::size_t) ch];
  12109. const auto path = juce::String::fromUTF8 (channel.samplePath.c_str());
  12110. const auto sample = engine.getSampleLibrary().load (path);
  12111. const auto span = sample != nullptr ? clipops::clipSpan (channel, sample) : precompute::PlayedSpan {};
  12112. // the frames the clip plays (its Trim; round 180d), as the drawing and the playback count them
  12113. const auto frames = sample != nullptr ? (double) span.frames : 0.0;
  12114. const auto rate = sample != nullptr ? sample->sampleRate : 44100.0;
  12115. const auto mouse = juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1);
  12116. const auto label = [] (const flclipmenu::Entry& e) { return e.mnemonic != 0 ? theme::mnemonic (tr (e.text.c_str()), e.mnemonic) : tr (e.text.c_str()); };
  12117. auto setColour = [this, ch] (std::uint32_t colour) {
  12118. engine.editSong ([ch, colour] (Song& s) {
  12119. if (ch < (int) s.channels.size())
  12120. s.channels[(std::size_t) ch].colour = colour;
  12121. });
  12122. };
  12123. // FL's Crossfade with › lists the other channels' audio clips that overlap this one in time (EEAUMenuPopup ->
  12124. // FUN_01236f10); with none it is greyed (round 190gw: clipops::crossfadeWith makes FL's clip)
  12125. const auto crossfadeOthers = clipops::crossfadeCandidates (song, index);
  12126. for (const auto& e : flclipmenu::shown (crossfadeOthers.empty(), clipops::showCrossfadeSelected (song.playlist, index, selection)))
  12127. {
  12128. using K = flclipmenu::Entry::Kind;
  12129. const auto& t = e.text;
  12130. if (e.kind == K::separator)
  12131. menu.addSeparator();
  12132. else if (e.kind == K::columnBreak)
  12133. menu.addColumnBreak();
  12134. else if (e.kind == K::header && t == "Audio clip")
  12135. ui::addItemHeader (menu, many ? tr ("Audio clip") + " (" + juce::String ((int) targets.size()) + ")" : tr ("Audio clip"),
  12136. juce::String::fromUTF8 (channel.name.c_str()), audioClipColour (channel));
  12137. else if (e.kind == K::header)
  12138. menu.addSectionHeader (tr (t.c_str()));
  12139. else if (t == "Preview")
  12140. menu.addItem (label (e), [this, index] { previewClipAudio (index); });
  12141. else if (t == "Muted")
  12142. menu.addItem (label (e), true, clip.muted, [this, targets, m = ! clip.muted] {
  12143. engine.editSong ([targets, m] (Song& s) {
  12144. for (auto i : targets)
  12145. if (i < (int) s.playlist.size())
  12146. s.playlist[(std::size_t) i].muted = m;
  12147. });
  12148. });
  12149. else if (t == "Rename and color...")
  12150. menu.addItem (label (e), [this, ch] {
  12151. const auto& c = engine.getSong().channels[(std::size_t) ch];
  12152. showNameAndColourDialog (tr ("Rename audio clip"), juce::String::fromUTF8 (c.name.c_str()), c.colour,
  12153. [this, ch] (const juce::String& name, std::uint32_t colour) {
  12154. if (ch < (int) engine.getSong().channels.size())
  12155. engine.editSong ([ch, n = name.toStdString(), colour] (Song& s) {
  12156. s.channels[(std::size_t) ch].name = n;
  12157. s.channels[(std::size_t) ch].colour = colour;
  12158. });
  12159. });
  12160. });
  12161. else if (t == "Change color...") // (FL: the name dialog with its colour selector, EEAUSetNameMenuClick flag 8)
  12162. menu.addItem (label (e), [setColour, mouse, current = channel.colour] {
  12163. ui::showColourPickerPopup (mouse, tr ("Change color..."), current != 0 ? juce::Colour (current) : juce::Colour (lynxPalette()[0]), {},
  12164. [setColour] (juce::Colour c) { setColour (c.getARGB()); }, {}, [setColour] { setColour (0); });
  12165. });
  12166. else if (t == "Random color")
  12167. menu.addItem (label (e), [setColour] {
  12168. const auto& palette = lynxPalette();
  12169. setColour (palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())]);
  12170. });
  12171. else if (t == "Change icon...") // (FL: the clip channel's icon, EEAUSetNameMenuClick flag 2; LYNX's own icon set)
  12172. menu.addItem (label (e), [this, ch, mouse, current = channel.icon] {
  12173. ui::showTrackIconPicker (mouse, current, [this, ch] (int icon) {
  12174. if (ch < (int) engine.getSong().channels.size())
  12175. engine.editSong ([ch, icon] (Song& s) { s.channels[(std::size_t) ch].icon = icon; });
  12176. });
  12177. });
  12178. else if (t == "Select source channel")
  12179. {
  12180. juce::PopupMenu sources;
  12181. for (int c = 0; c < (int) song.channels.size(); ++c)
  12182. if (song.channels[(std::size_t) c].instrument == InstrumentKind::audioClip)
  12183. sources.addItem (juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str()), true, c == ch,
  12184. [this, targets, c] { engine.editSong ([targets, c] (Song& s) { clipops::setClipSource (s, targets, ClipKind::audio, c); }); });
  12185. menu.addSubMenu (label (e), sources, sources.getNumItems() > 1);
  12186. }
  12187. else if (t == "Channel settings")
  12188. menu.addItem (label (e), [this, ch] { openChannelSettings (engine, ch); });
  12189. else if (t == "Make unique")
  12190. menu.addItem (label (e), [this, targets] { engine.editSong ([targets] (Song& s) { clipops::makeAudioUnique (s, targets); }); });
  12191. else if (t == "Select all similar clips")
  12192. menu.addItem (label (e), [this, index] { setSelection (clipops::sameSource (engine.getSong(), index)); });
  12193. else if (t == "Delete")
  12194. menu.addItem (label (e), [this, targets] {
  12195. setSelection (targets);
  12196. deleteSelection();
  12197. });
  12198. else if (t == "Properties...")
  12199. menu.addItem (label (e), [this, index, targets] {
  12200. showClipProperties (engine, index, targets, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] {
  12201. if (safe != nullptr)
  12202. safe->sortClips();
  12203. });
  12204. });
  12205. else if (t == "Select region")
  12206. {
  12207. // "Full" (FL's Default radio item) and the file's regions (its cue markers): the clip plays that part
  12208. juce::PopupMenu regions;
  12209. const auto perTick = sample != nullptr ? clipops::framesPerTick (channel, clip, frames, rate, song.bpm) : 0.0;
  12210. std::vector<flclipmenu::ClipWindow> windows;
  12211. if (sample != nullptr)
  12212. for (const auto& r : flclipmenu::sampleRegions (sample->markerStarts, (std::int64_t) sample->frames()))
  12213. if (const auto w = flclipmenu::regionWindow (r, span.first, span.frames, perTick))
  12214. windows.push_back (*w);
  12215. const auto current = flclipmenu::currentRegion (windows, clip);
  12216. auto setWindow = [this, targets] (flclipmenu::ClipWindow w) {
  12217. engine.editSong ([targets, w] (Song& s) {
  12218. for (auto i : targets)
  12219. if (i < (int) s.playlist.size() && s.playlist[(std::size_t) i].kind == ClipKind::audio)
  12220. {
  12221. s.playlist[(std::size_t) i].offset = w.offset;
  12222. s.playlist[(std::size_t) i].offsetFraction = 0.0;
  12223. s.playlist[(std::size_t) i].length = w.length;
  12224. }
  12225. });
  12226. sortClips();
  12227. };
  12228. // (FL's radio check, FUN_00ffa400: "Full" while the clip has no start / end of its own — it plays its source
  12229. // from the start to the end, however long the clip is drawn — a region when it plays exactly that region,
  12230. // none otherwise)
  12231. const auto full = flclipmenu::fullWindow (span.frames, perTick);
  12232. const auto isFull = current < 0 && clip.offset == 0 && clip.length >= full.length - 1;
  12233. regions.addItem (tr ("Full"), sample != nullptr, isFull, [setWindow, full] { setWindow (full); });
  12234. for (int r = 0; r < (int) windows.size(); ++r)
  12235. regions.addItem (tr ("Region {0}", { juce::String (r + 1) }), true, r == current, [setWindow, w = windows[(std::size_t) r]] { setWindow (w); });
  12236. menu.addSubMenu (label (e), regions);
  12237. }
  12238. else if (t == "Chop")
  12239. {
  12240. // FL's Chop › "Time based" group (FUN_01236260), then LYNX's chop to the grid
  12241. juce::PopupMenu chop;
  12242. auto chopBy = [this, targets] (std::int64_t grid) {
  12243. setSelection ({});
  12244. engine.editSong ([targets, grid] (Song& s) {
  12245. for (auto i : targets) // chopping adds clips at the end: indices below stay valid
  12246. noteedit::chopClip (s.playlist, i, grid);
  12247. });
  12248. sortClips();
  12249. };
  12250. chop.addSectionHeader (tr ("Time based"));
  12251. const auto bar = song.barTicks();
  12252. for (const auto& c : flclipmenu::timeBasedChops())
  12253. chop.addItem (tr (c.text), [chopBy, ticks = c.beatDivisor == 0 ? bar : (std::int64_t) ppq / c.beatDivisor] { chopBy (ticks); });
  12254. chop.addSeparator();
  12255. chop.addItem (tr ("Chop to grid"), [chopBy, grid = gridTicks()] { chopBy (grid); });
  12256. menu.addSubMenu (label (e), chop);
  12257. }
  12258. else if (t == "Make unique as sample") // (round 189g)
  12259. menu.addItem (label (e), [this, index] { makeClipUniqueAsSampleAsked (index, ! juce::ModifierKeys::currentModifiers.isShiftDown()); });
  12260. else if (t == "Edit sample") // (FL: the clip's channel sample into its editor, EEAUEditSampleMenuClick)
  12261. menu.addItem (label (e), sample != nullptr, false, [this, ch, index] { openAudioEditorForChannel (engine, ch, index); });
  12262. else if (t == "Extract stems from sample")
  12263. menu.addItem (label (e), sample != nullptr, false, [this, index] { extractStemsFromClip (engine, index, [this] { sortClips(); }); });
  12264. else if (t == "Deverb") // (round 190jv: LYNX's own Deverb in the audio editor; FL 2026 downloads a module here)
  12265. menu.addItem (label (e), sample != nullptr, false, [this, ch, index] { openAudioEditorDeverb (engine, ch, index); });
  12266. else if (t == "Detect tempo") // (live check 190ew PL-8: one item opening FL's Tempo detection dialog)
  12267. menu.addItem (label (e), sample != nullptr, false, [this, index, sample] { showDetectTempo (index, sample); });
  12268. else if (t == "Fit to tempo")
  12269. menu.addSubMenu (label (e), fitToTempoMenu (index, sample), sample != nullptr);
  12270. else if (t == "Automate")
  12271. {
  12272. // EEAUAutoMenu (round 190dx, core clipops::automateAudioClip): an automation clip of the clip channel's Levels
  12273. // adjustment pan / volume (round 190dz) where the audio clip is (same track, start and length)
  12274. juce::PopupMenu automate;
  12275. const auto add = [this, index, &automate] (const juce::String& text, clipops::AutomateWhat what) {
  12276. automate.addItem (text, [this, index, what] {
  12277. const auto target = clipops::automateTarget (engine.getSong(), index, what);
  12278. if (target.kind == AutomationTargetKind::none)
  12279. return;
  12280. const auto name = clipops::automateName (engine.getSong(), target, describeAutomationTarget (engine, target).toStdString());
  12281. int made = -1;
  12282. engine.editSong ([index, what, &name, &made] (Song& s) { made = clipops::automateAudioClip (s, index, what, name); });
  12283. sortClips();
  12284. // (live check 190ew PL-1: the new clip becomes the Playlist's current clip, as the picker shows)
  12285. if (made >= 0)
  12286. {
  12287. brush = { ClipKind::automation, made };
  12288. engine.sendChangeMessage();
  12289. }
  12290. });
  12291. };
  12292. add (theme::mnemonic (tr ("Panning"), 'P'), clipops::AutomateWhat::panning);
  12293. add (theme::mnemonic (tr ("Volume"), 'V'), clipops::AutomateWhat::volume); // (FL's default item)
  12294. menu.addSubMenu (label (e), automate);
  12295. }
  12296. else if (t == "Crossfade with")
  12297. {
  12298. // round 190gw (live check 190gu B3): one item per overlapping clip of another channel; the pick makes
  12299. // "<A> to <B> crossfade" on this clip's track over the overlap (FL's two Volume multiplier links)
  12300. juce::PopupMenu others;
  12301. for (const auto other : crossfadeOthers)
  12302. {
  12303. const auto oc = song.playlist[(std::size_t) other].channel;
  12304. const auto name = oc >= 0 && oc < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) oc].name.c_str()) : juce::String();
  12305. others.addItem (name, [this, index, other] {
  12306. int made = -1;
  12307. engine.editSong ([index, other, &made] (Song& s) { made = clipops::crossfadeWith (s, index, other); });
  12308. sortClips();
  12309. if (made >= 0) // (as Automate: the new clip becomes the Playlist's current clip)
  12310. {
  12311. brush = { ClipKind::automation, made };
  12312. engine.sendChangeMessage();
  12313. }
  12314. });
  12315. }
  12316. menu.addSubMenu (label (e), others, ! crossfadeOthers.empty());
  12317. }
  12318. else if (t == "Pitch-correct sample" || t == "Time-warp sample")
  12319. {
  12320. // round 190gw (live check 190gu B3): FL opens Newtone / Newtime on the Master with the clip's sample
  12321. const auto kind = t == "Pitch-correct sample" ? EffectKind::newtone : EffectKind::newtime;
  12322. menu.addItem (label (e), sample != nullptr, false, [this, kind, file = channel.samplePath] { openSampleInMasterEditor (engine, kind, file); });
  12323. }
  12324. else if (t == "Reset fades") // (FL: "Reset fade times to 0"; Tag 1 into the fade handle's reset, FUN_00d01bc0 ->
  12325. // FUN_00cfb460, as the handle's Reset fade in / out: the times and their tension)
  12326. menu.addItem (label (e), [this, targets] {
  12327. engine.editSong ([targets] (Song& s) {
  12328. for (auto i : targets)
  12329. if (i < (int) s.playlist.size())
  12330. {
  12331. auto& c = s.playlist[(std::size_t) i];
  12332. c.fadeIn = c.fadeOut = 0;
  12333. c.fadeInTension = c.fadeOutTension = 0.0f;
  12334. }
  12335. });
  12336. });
  12337. else if (t == "Fade in curve" || t == "Fade out curve") // (live check 190ew PL-7, core flclipmenu::fadeCurve)
  12338. menu.addSubMenu (label (e), fadeHandleMenu (index, t == "Fade in curve" ? 0 : 1, true));
  12339. else if (t == "Crossfade selected") // (round 189o: the same Create crossfade as the fade handle menu)
  12340. menu.addItem (label (e), [this, index, chosen = selection] {
  12341. engine.editSong ([index, chosen] (Song& s) { clipops::createCrossfades (s.playlist, index, 0, chosen); });
  12342. repaint();
  12343. });
  12344. }
  12345. // --- LYNX's own items (no FL counterpart), core flclipmenu::lynxExtras --------------------------------------------
  12346. // (round 190jv: a third column, so FL's two stay as FL draws them; JUCE breaks columns only where asked, and round
  12347. // 190je's tall-menu split (JUCE fix 40, lynxTallMenuBreakHook) leaves a menu with breaks alone)
  12348. menu.addColumnBreak();
  12349. menu.addSectionHeader (tr ("LYNX extras")); // (round 190gi: as the Clip View's menu, DetailView; FL's sections stay FL's)
  12350. // round 190ds (LYNX's own): the clip follows the project key, and its loop's key; round 190kx: in every layout (this
  12351. // column is LYNX's own), with "Detect from the audio" in Loop key and a one-click fit to the project's tempo
  12352. addKeyFollowItems (menu, index, targets);
  12353. if (sample != nullptr)
  12354. {
  12355. // the loop analysis' tempo when it knows the file (the Browser showed it, a drop analysed it) and finds a loop of
  12356. // whole beats, in the octave nearest the project's (clipops::fitBeats); else the same count as FL's Fit to tempo
  12357. auto beats = 0.0f;
  12358. if (loopInfo == nullptr)
  12359. loopInfo = loopinfo::Shared::get (engine); // (kept while the Playlist exists: the worker and its answers)
  12360. auto& info = loopInfo;
  12361. if (const auto known = info->known (channel.samplePath); known && known->isLoop() && sample->acidBeats <= 0.0f)
  12362. beats = clipops::fitBeats ((double) sample->frames() / sample->sampleRate, song.bpm, 0.0f, known->bpm);
  12363. else
  12364. info->request ({ channel.samplePath }); // (known the next time the menu opens)
  12365. if (beats <= 0.0f)
  12366. beats = tempodetect::fitBeatsOf (sample.get(), song.bpm);
  12367. if (beats > 0.0f)
  12368. {
  12369. const auto whole = std::abs (beats - std::round (beats)) < 0.005f;
  12370. const auto count = juce::String (beats, whole ? 0 : 2) + " " + (beats == 1.0f ? tr ("beat") : tr ("beats"));
  12371. const auto seconds = frames / juce::jmax (1.0, rate);
  12372. const auto from = seconds > 0.0 ? juce::String (beats * 60.0 / seconds, 1) : juce::String();
  12373. const auto fitted = channel.sampler.stretchBeats == beats && channel.sampler.keepPitch;
  12374. menu.addItem (tr ("Fit to the project tempo ({0}, from {1} BPM)", { count, from }), true, fitted,
  12375. [fitTo = clipFitter (index, sample), beats] { fitTo (beats, true); });
  12376. }
  12377. }
  12378. // comping (round 163): a take lane's clip onto its comp track (the group header above)
  12379. if (const auto comp = takes::compTrackOf (song, clip.track); comp >= 0)
  12380. {
  12381. // the loop region where it covers the clip (comping a phrase), else the whole clip
  12382. const auto useLoop = song.hasLoop() && song.loopStart < clip.end() && song.loopEnd > clip.start;
  12383. const auto from = useLoop ? std::max (song.loopStart, clip.start) : clip.start;
  12384. const auto to = useLoop ? std::min (song.loopEnd, clip.end()) : clip.end();
  12385. menu.addItem (useLoop ? tr ("Promote this take in the loop region to the comp track") : tr ("Promote this take to the comp track"), [this, index, comp, from, to] {
  12386. setSelection ({});
  12387. engine.editSong ([index, comp, from, to] (Song& s) { takes::promoteTake (s, index, comp, from, to); });
  12388. sortClips();
  12389. });
  12390. }
  12391. menu.addSubMenu (tr ("Color palette"), ui::colourMenu (channel.colour, setColour, mouse));
  12392. const auto splitAt = snap (xToTick (mouseX) + gridTicks() / 2.0, true);
  12393. menu.addItem (tr ("Split here"), splitAt > clip.start && splitAt < clip.end(), false, [this, index, splitAt] {
  12394. setSelection ({});
  12395. engine.editSong ([index, splitAt] (Song& s) {
  12396. if (index < (int) s.playlist.size() && splitAt > s.playlist[(std::size_t) index].start && splitAt < s.playlist[(std::size_t) index].end())
  12397. s.playlist.push_back (splitClip (s.playlist[(std::size_t) index], splitAt));
  12398. });
  12399. sortClips();
  12400. });
  12401. // round 190hp (slice B18, core/StripSilence.h): the clip cut where it stays quiet, the quiet parts left out
  12402. menu.addItem (tr ("Split at silence..."), canSplitAtSilence (index), false, [this, targets] {
  12403. juce::Component::SafePointer<PlaylistComponent> self (this);
  12404. auto* box = buildSplitSilenceDialog (this);
  12405. box->enterModalState (true, juce::ModalCallbackFunction::create ([self, box, targets] (int result) {
  12406. if (result != 1 || self == nullptr)
  12407. return;
  12408. splitSilenceOptions() = readSplitSilenceDialog (*box);
  12409. juce::String why;
  12410. self->splitClipsAtSilence (targets, splitSilenceOptions(), &why);
  12411. ui::postHint ({ why, {}, false, false }, 3000);
  12412. }),
  12413. true);
  12414. });
  12415. menu.addItem (tr ("Merge clips"), clipops::canMerge (song, targets), false, [this, targets] {
  12416. setSelection ({});
  12417. engine.editSong ([targets] (Song& s) { clipops::mergeClips (s, targets); });
  12418. sortClips();
  12419. });
  12420. menu.addItem (tr ("Reverse"), sample != nullptr, channel.sampler.reverse, [this, index, frames, rate] {
  12421. engine.editSong ([index, frames, rate] (Song& s) {
  12422. const auto c = s.playlist[(std::size_t) index].channel;
  12423. clipops::reverseAudio (s, index, clipops::fileTicks (s.channels[(std::size_t) c], frames, rate, s.bpm));
  12424. });
  12425. });
  12426. // Live's Convert Melody / Harmony / Drums to New MIDI Track, the FL way: a new pattern on new channels (round a2m189b)
  12427. {
  12428. juce::PopupMenu convert;
  12429. const std::pair<const char*, a2m::Mode> modes[] = { { TR_NOOP ("Melody to new pattern"), a2m::Mode::melody },
  12430. { TR_NOOP ("Harmony to new pattern"), a2m::Mode::harmony },
  12431. { TR_NOOP ("Drums to new pattern"), a2m::Mode::drums } };
  12432. for (const auto& [text, mode] : modes)
  12433. convert.addItem (tr (text), [this, index, m = mode] { convertClipToMidi (engine, index, m, [this] { sortClips(); }); });
  12434. menu.addSubMenu (tr ("Convert to MIDI"), convert, sample != nullptr);
  12435. }
  12436. // round 190lj: the same with its options (Basic Pitch polyphonic or one note at a time, sensitivities, shortest note,
  12437. // key range, pitch bends, quantize to the snap, the channel that plays them); in every layout (Simple too)
  12438. menu.addItem (tr ("Convert to MIDI (polyphonic)..."), sample != nullptr, false, [this, index] {
  12439. juce::Component::SafePointer<PlaylistComponent> self (this);
  12440. showConvertOptions (engine, this, gridTicks(), [self, index] (const a2m::ConvertOptions& options) {
  12441. if (self != nullptr)
  12442. convertClipToMidi (self->engine, index, options, [self] {
  12443. if (self != nullptr)
  12444. self->sortClips();
  12445. });
  12446. });
  12447. });
  12448. // round 190lk: the polyphonic note editor (ui/PolyEditor, core/PolyEdit.h): the channel's notes, chords included,
  12449. // edited one by one; the channel's clips play the edited render (an ARA-edited channel plays its plugin instead)
  12450. menu.addItem (tr ("Edit notes (polyphonic)..."), sample != nullptr && ! channel.ara.active(), false,
  12451. [this, ch] { PolyEditorWindows::open (engine, ch); });
  12452. // round 190pf (research190oe P12, P13): Smart Tempo (the project's tempo follows this free recording; Pattern and
  12453. // Simple) and the Chord lane's chords from this clip's notes (shown with the lane)
  12454. if (! liveStyle)
  12455. menu.addItem (tr ("Make the project tempo follow this clip..."), sample != nullptr, false, [this, index] { followClipTempo (index); });
  12456. if (chordLaneShown() && chordLane != nullptr)
  12457. menu.addItem (tr ("Detect chords to the Chord lane"), sample != nullptr, false, [this, index] { chordLane->detectFromAudio (index); });
  12458. addLiveTrackItems (engine, menu, index, targets, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] {
  12459. if (safe != nullptr)
  12460. {
  12461. safe->setSelection ({});
  12462. safe->sortClips();
  12463. }
  12464. });
  12465. // Live's Slice to New MIDI Track (round 190ec): a Drum Rack with a pad per slice and a pattern that replays them
  12466. menu.addItem (tr ("Slice to New MIDI Track..."), sample != nullptr && ! clipops::playsBackwards (channel, clip), false,
  12467. [this, index] { showSliceToNewTrackDialog (engine, *this, index, [this] { sortClips(); }); });
  12468. menu.addItem (tr ("Pitch... (semitones, cents, keep length)"), sample != nullptr, false, [this, ch] { showSamplePitchDialog (engine, ch); });
  12469. menu.addItem (tr ("Normalize"), [this, targets] { normalizeClips (targets); });
  12470. {
  12471. juce::PopupMenu gains;
  12472. for (auto db : { 6.0f, 3.0f, 0.0f, -3.0f, -6.0f, -12.0f })
  12473. {
  12474. const auto g = juce::Decibels::decibelsToGain (db);
  12475. gains.addItem ((db > 0 ? "+" : "") + juce::String (db, 0) + " dB", true, std::abs (clip.gain - g) < 0.01f, [this, targets, g] {
  12476. engine.editSong ([targets, g] (Song& s) {
  12477. for (auto i : targets)
  12478. if (i < (int) s.playlist.size() && s.playlist[(std::size_t) i].kind == ClipKind::audio)
  12479. s.playlist[(std::size_t) i].gain = g;
  12480. });
  12481. });
  12482. }
  12483. menu.addSubMenu (tr ("Clip volume"), gains);
  12484. }
  12485. // the clip's own envelopes (round 190gi, core/ClipEnvelope.h): the lane shown on the clip is edited there like an
  12486. // automation clip's curve ([RMB] adds a point, drag a point, the hollow handles bend a segment)
  12487. {
  12488. const auto* envelope = clipenv::of (song, clip);
  12489. const auto shown = envelope != nullptr ? envelope->shown : (std::uint8_t) 0;
  12490. juce::PopupMenu env;
  12491. auto showLane = [this, index] (std::uint8_t lane) {
  12492. engine.editSong ([index, lane] (Song& s) {
  12493. if (index < (int) s.playlist.size())
  12494. clipenv::show (s, s.playlist[(std::size_t) index], lane);
  12495. });
  12496. };
  12497. env.addItem (tr ("Show volume envelope"), true, shown == clipenv::volumeLane, [showLane, shown] { showLane (shown == clipenv::volumeLane ? 0 : clipenv::volumeLane); });
  12498. env.addItem (tr ("Show pan envelope"), true, shown == clipenv::panLane, [showLane, shown] { showLane (shown == clipenv::panLane ? 0 : clipenv::panLane); });
  12499. env.addItem (tr ("Hide envelope"), shown != 0, false, [showLane] { showLane (0); });
  12500. env.addSeparator();
  12501. for (const auto lane : { clipenv::volumeLane, clipenv::panLane })
  12502. {
  12503. const auto has = envelope != nullptr && ! clipenv::flat (clipenv::laneOf (*envelope, lane), clipenv::neutralOf (lane));
  12504. env.addItem (lane == clipenv::volumeLane ? tr ("Reset volume envelope") : tr ("Reset pan envelope"), has, false, [this, targets, lane] {
  12505. engine.editSong ([targets, lane] (Song& s) {
  12506. for (auto i : targets)
  12507. if (i < (int) s.playlist.size())
  12508. clipenv::reset (s, s.playlist[(std::size_t) i], lane);
  12509. });
  12510. });
  12511. }
  12512. menu.addSubMenu (tr ("Clip envelope"), env);
  12513. }
  12514. // round 190kc: Live's Extract Groove on an Arrangement audio clip (its attacks' timing and levels; Clip-launch layout)
  12515. if (layoutstyle::current() == layoutstyle::Style::clipLaunch && sample != nullptr)
  12516. menu.addItem (tr ("Extract Groove(s)"), [this, index, sample, name = juce::File (path).getFileNameWithoutExtension().toStdString()] {
  12517. engine.editSong ([&] (Song& s) {
  12518. if (index >= 0 && index < (int) s.playlist.size())
  12519. if (auto g = grooveaudio::extract (s, s.playlist[(std::size_t) index], *sample, GrooveBase::sixteenth, name); ! g.points.empty())
  12520. groove::add (s.grooves, std::move (g));
  12521. });
  12522. });
  12523. // warp from the Playlist (round 190gi, core/ClipWarp.h): the audio editor's Auto-warp and Quantize audio on this clip
  12524. const auto warpable = sample != nullptr && ! clipops::playsBackwards (channel, clip);
  12525. menu.addItem (tr ("Auto-warp"), warpable, false, [this, index, sample, file = juce::File (path).getFileNameWithoutExtension().toStdString()] {
  12526. int placed = 0;
  12527. engine.editSong ([&] (Song& s) { placed = clipwarp::autoWarp (s, index, *sample, file); });
  12528. ui::Hint done;
  12529. done.text = placed > 0 ? tr ("Auto-warp: {0} markers", { juce::String (placed) }) : tr ("Auto-warp found no beat to lock to");
  12530. ui::postHint (done, 2500);
  12531. repaint();
  12532. });
  12533. menu.addItem (tr ("Quantize audio"), warpable, false, [this, index, sample] {
  12534. int placed = 0;
  12535. engine.editSong ([&] (Song& s) { placed = clipwarp::quantize (s, index, *sample); });
  12536. ui::Hint done;
  12537. done.text = placed > 0 ? tr ("{0} warp markers placed", { juce::String (placed) }) : tr ("No attack to quantize here");
  12538. ui::postHint (done, 2500);
  12539. repaint();
  12540. });
  12541. // round 190kx: ARA 2 (Melodyne, RipX, VocAlign...) on the clip's channel (LYNX's own: FL Studio 2026 hosts no ARA)
  12542. menu.addSubMenu (tr ("Edit in ARA plugin"), aramenu::forClip (engine, index));
  12543. menu.addItem (tr ("Open in a new Sampler channel"), sample != nullptr, false, [this, ch] {
  12544. if (onOpenInSampler)
  12545. onOpenInSampler (ch);
  12546. });
  12547. menu.addItem (tr ("Show the file in Explorer"), juce::File (path).existsAsFile(), false, [path] { juce::File (path).revealToUser(); });
  12548. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", [this, targets] {
  12549. setSelection (targets);
  12550. copySelection();
  12551. deleteSelection();
  12552. });
  12553. menu.addItem (theme::mnemonic (tr ("Copy"), 'C') + "\tCtrl+C", [this, targets] {
  12554. setSelection (targets);
  12555. copySelection();
  12556. });
  12557. menu.addItem (theme::mnemonic (tr ("Paste here"), 'P') + "\tCtrl+V", canPasteClips(), false, [this, at = snap (xToTick (mouseX), true)] { pasteClips (at); });
  12558. return menu;
  12559. }
  12560. // The "Fit to tempo" / "Detect tempo" fit of an audio clip's file to a number of beats (keeping its pitch or not)
  12561. std::function<void (float, bool)> PlaylistComponent::clipFitter (int index, std::shared_ptr<const SampleData> sample)
  12562. {
  12563. const auto& song = engine.getSong();
  12564. const auto& channel = song.channels[(std::size_t) song.playlist[(std::size_t) index].channel];
  12565. // the frames the clip plays (its Trim; round 180d), as the drawing and the playback count them
  12566. const auto frames = sample != nullptr ? (double) clipops::clipSpan (channel, sample).frames : 0.0;
  12567. const auto rate = sample != nullptr ? sample->sampleRate : 44100.0;
  12568. return [this, index, frames, rate] (float toBeats, bool keepPitch) {
  12569. engine.editSong ([index, frames, rate, toBeats, keepPitch] (Song& s) {
  12570. const auto ch = s.playlist[(std::size_t) index].channel;
  12571. auto& channel = s.channels[(std::size_t) ch];
  12572. auto& sampler = channel.sampler;
  12573. const auto before = clipops::fileTicks (channel, frames, rate, s.bpm);
  12574. sampler.stretchBeats = toBeats;
  12575. // "Original speed" keeps a pitched clip's "keep length" (round 163)
  12576. sampler.keepPitch = keepPitch && (toBeats > 0.0f || sampler.pitch != 0.0f || channel.misc.fineTune != 0.0f);
  12577. // every clip of the file keeps showing the same audio: offsets and lengths scale with it
  12578. clipops::rescaleClipsOf (s, ch, before, clipops::fileTicks (channel, frames, rate, s.bpm));
  12579. });
  12580. sortClips();
  12581. };
  12582. }
  12583. // The audio clip menu's "Fit to tempo" submenu (round 190dz: out of buildClipMenu, unchanged)
  12584. juce::PopupMenu PlaylistComponent::fitToTempoMenu (int index, std::shared_ptr<const SampleData> sample)
  12585. {
  12586. const auto& song = engine.getSong();
  12587. const auto& channel = song.channels[(std::size_t) song.playlist[(std::size_t) index].channel];
  12588. // stretching the channel's file to a whole number of beats at the project tempo
  12589. juce::PopupMenu fit;
  12590. const auto beats = tempodetect::fitBeatsOf (sample.get(), song.bpm);
  12591. const auto fitTo = clipFitter (index, sample);
  12592. if (beats > 0.0f)
  12593. {
  12594. const auto whole = std::abs (beats - std::round (beats)) < 0.005f;
  12595. const auto label = juce::String (beats, whole ? 0 : 2) + " " + (beats == 1.0f ? tr ("beat") : tr ("beats"));
  12596. fit.addItem (tr ("Fit to tempo, keep pitch ({0})", { label }), true, channel.sampler.stretchBeats == beats && channel.sampler.keepPitch,
  12597. [fitTo, beats] { fitTo (beats, true); });
  12598. fit.addItem (tr ("Fit to tempo, resample ({0})", { label }), true, channel.sampler.stretchBeats == beats && ! channel.sampler.keepPitch,
  12599. [fitTo, beats] { fitTo (beats, false); });
  12600. fit.addItem (tr ("Half as long"), channel.sampler.stretchBeats > 0.0f, false,
  12601. [fitTo, b = channel.sampler.stretchBeats, kp = channel.sampler.keepPitch] { fitTo (juce::jmax (0.25f, b * 0.5f), kp); });
  12602. fit.addItem (tr ("Twice as long"), channel.sampler.stretchBeats > 0.0f, false,
  12603. [fitTo, b = channel.sampler.stretchBeats, kp = channel.sampler.keepPitch] { fitTo (juce::jmin (1024.0f, b * 2.0f), kp); });
  12604. fit.addSeparator();
  12605. }
  12606. // FL's TIME presets (r168s c_f20): the whole file lasts exactly this long
  12607. const auto barBeats = (float) song.barTicks() / (float) ppq; // (round 190fg: a bar in quarter notes)
  12608. for (const auto preset : clipops::timePresetBeats (song.meter()))
  12609. {
  12610. const auto bars = preset >= barBeats - 1.0e-4f ? preset / barBeats : 0.0f;
  12611. const auto label = bars > 0.0f ? (bars == 1.0f ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars, 0) }))
  12612. : (preset == 1.0f ? tr ("1 beat") : tr ("{0} beats", { juce::String (preset, 0) }));
  12613. fit.addItem (label, true, channel.sampler.stretchBeats == preset, [fitTo, preset, kp = channel.sampler.keepPitch] { fitTo (preset, kp); });
  12614. }
  12615. fit.addSeparator();
  12616. fit.addItem (tr ("Original speed (no stretch)"), true, channel.sampler.stretchBeats <= 0.0f, [fitTo, kp = channel.sampler.keepPitch] { fitTo (0.0f, kp); });
  12617. return fit;
  12618. }
  12619. // Round 190mr (DL-68; capture 190mr B1, live-crossfade-drag.png): Live's Arrangement makes a crossfade when a fade
  12620. // handle is dragged over the edge of the adjacent clip — the fade-out handle of a clip whose neighbour starts where it
  12621. // ends, dragged right, or the neighbour's fade-in handle dragged left. The clip goes on under its neighbour with audio
  12622. // from beyond its edge (none there: nothing happens, as in Live) and the overlap becomes a crossfade (both fades = the
  12623. // overlap, ClipOps createCrossfade). The Clip-launch layout only (Live's look); FL's handles stop at the clip's edge.
  12624. // Returns true while the drag is such a crossfade (the handle's own fade is then not changed).
  12625. bool PlaylistComponent::crossfadeDragOver (std::int64_t tick)
  12626. {
  12627. if (! theme::livelook::active() || dragClip < 0)
  12628. return false;
  12629. const auto& song = engine.getSong();
  12630. const auto out = drag == Drag::fadeOut;
  12631. if (crossPair < 0)
  12632. {
  12633. // the pair is found once per drag, when the handle first passes the clip's edge
  12634. const auto& c = song.playlist[(std::size_t) dragClip];
  12635. if (c.kind != ClipKind::audio || (out ? tick <= c.end() : tick >= c.start))
  12636. return false;
  12637. for (int i = 0; i < (int) song.playlist.size(); ++i)
  12638. {
  12639. const auto& o = song.playlist[(std::size_t) i];
  12640. if (i != dragClip && o.kind == ClipKind::audio && o.track == c.track && (out ? o.start == c.end() : o.end() == c.start))
  12641. {
  12642. crossPair = i;
  12643. crossOriginals = { out ? c : o, out ? o : c };
  12644. break;
  12645. }
  12646. }
  12647. if (crossPair < 0)
  12648. return false;
  12649. }
  12650. const auto& a = crossOriginals[0];
  12651. const auto& b = crossOriginals[1];
  12652. const auto boundary = b.start;
  12653. // how far the moving clip can go on: audio left in its file past its end (a), or before its start (b)
  12654. const auto room = [this, &song] (const Clip& clip, bool after) -> std::int64_t {
  12655. if (clip.channel < 0 || clip.channel >= (int) song.channels.size())
  12656. return 0;
  12657. const auto& channel = song.channels[(std::size_t) clip.channel];
  12658. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str()));
  12659. if (sample == nullptr || sample->frames() == 0 || sample->sampleRate <= 0.0 || clipops::playsBackwards (channel, clip))
  12660. return 0;
  12661. const auto span = clipops::clipSpan (channel, sample);
  12662. const auto perTick = clipops::framesPerTick (channel, clip, (double) span.frames, sample->sampleRate, song.bpm);
  12663. if (perTick <= 0.0)
  12664. return 0;
  12665. return after ? juce::jmax<std::int64_t> (0, (std::int64_t) ((double) span.frames / perTick) - clip.offset - clip.length)
  12666. : juce::jmax<std::int64_t> (0, clip.offset);
  12667. };
  12668. const auto wanted = out ? tick - boundary : boundary - tick;
  12669. const auto limit = juce::jmin (out ? room (a, true) : room (b, false), (out ? b.length : a.length) - 1);
  12670. const auto overlap = juce::jlimit<std::int64_t> (0, juce::jmax<std::int64_t> (0, limit), wanted);
  12671. const auto pair = crossPair, moving = dragClip;
  12672. engine.editSong ([this, pair, moving, out, overlap] (Song& s) {
  12673. if (moving >= (int) s.playlist.size() || pair >= (int) s.playlist.size())
  12674. return;
  12675. auto& m = s.playlist[(std::size_t) moving];
  12676. auto& n = s.playlist[(std::size_t) pair];
  12677. m = out ? crossOriginals[0] : crossOriginals[1];
  12678. n = out ? crossOriginals[1] : crossOriginals[0];
  12679. if (overlap <= 0)
  12680. return;
  12681. if (out)
  12682. m.length += overlap; // a goes on under b
  12683. else
  12684. {
  12685. m.start -= overlap; // b starts earlier, under a
  12686. m.offset -= overlap;
  12687. m.length += overlap;
  12688. }
  12689. clipops::createCrossfade (out ? m : n, out ? n : m);
  12690. });
  12691. // back to the clip's own edge: the drag is a plain fade again
  12692. if (overlap <= 0 && wanted <= 0)
  12693. crossPair = -1;
  12694. return overlap > 0 || wanted > 0;
  12695. }
  12696. // The audio clip menu's "Detect tempo" (round 190dz: out of buildClipMenu; round 190ey: FL's dialog)
  12697. void PlaylistComponent::showDetectTempo (int index, std::shared_ptr<const SampleData> sample)
  12698. {
  12699. // FL's "Detect tempo" (live check 190ew PL-8; LYNX's own detector, core/TempoDetect): one dialog, "Tempo detection -
  12700. // <clip>", whose choice becomes the sample's tempo: the clip's file fitted to that many beats (pitch kept), or no
  12701. // tempo (core/TempoDialog.h)
  12702. if (sample == nullptr || index < 0 || index >= (int) engine.getSong().playlist.size())
  12703. return;
  12704. ui::TempoDetectionRequest r;
  12705. {
  12706. const auto& song = engine.getSong();
  12707. const auto ch = song.playlist[(std::size_t) index].channel;
  12708. r.name = ch >= 0 && ch < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) ch].name.c_str()) : juce::String();
  12709. }
  12710. r.sample = sample;
  12711. r.projectBpm = engine.getSong().bpm;
  12712. r.hasTempoInfo = sample->acidBeats > 0.0f;
  12713. r.apply = [fitTo = clipFitter (index, sample)] (double beats) { fitTo ((float) beats, beats > 0.0); };
  12714. ui::showTempoDetectionDialog (std::move (r));
  12715. }
  12716. // --- Split at silence (round 190hp, slice B18; core/StripSilence.h) ------------------------------------------------------
  12717. stripsilence::Options& PlaylistComponent::splitSilenceOptions()
  12718. {
  12719. static stripsilence::Options last;
  12720. return last;
  12721. }
  12722. bool PlaylistComponent::canSplitAtSilence (int index)
  12723. {
  12724. const auto& song = engine.getSong();
  12725. if (index < 0 || index >= (int) song.playlist.size())
  12726. return false;
  12727. const auto& c = song.playlist[(std::size_t) index];
  12728. if (c.kind != ClipKind::audio || c.channel < 0 || c.channel >= (int) song.channels.size() || c.length < 2)
  12729. return false;
  12730. const auto& channel = song.channels[(std::size_t) c.channel];
  12731. // (warp markers bend the clip's time: its frames are not a straight line over its ticks)
  12732. if (channel.sampler.warp.size() >= 2)
  12733. return false;
  12734. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str()));
  12735. return sample != nullptr && sample->frames() > 0 && sample->sampleRate > 0.0;
  12736. }
  12737. int PlaylistComponent::splitClipsAtSilence (const std::vector<int>& targets, const stripsilence::Options& options, juce::String* why)
  12738. {
  12739. const auto& song = engine.getSong();
  12740. std::vector<std::pair<int, std::vector<stripsilence::Span>>> plans;
  12741. auto allQuiet = 0, nothing = 0;
  12742. for (auto i : targets)
  12743. {
  12744. if (! canSplitAtSilence (i))
  12745. continue;
  12746. const auto& c = song.playlist[(std::size_t) i];
  12747. const auto& channel = song.channels[(std::size_t) c.channel];
  12748. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str()));
  12749. // the frames the clip plays (as Normalize finds them: its trim, stretch, pitch and direction)
  12750. const auto span = clipops::clipSpan (channel, sample);
  12751. const auto total = (double) span.frames;
  12752. const auto perTick = clipops::framesPerTick (channel, c, total, sample->sampleRate, song.bpm);
  12753. if (! (perTick > 0.0))
  12754. continue;
  12755. const auto backwards = clipops::playsBackwards (channel, c);
  12756. auto from = juce::jlimit (0.0, total, (double) c.offset * perTick);
  12757. auto to = juce::jlimit (from, total, (double) (c.offset + c.length) * perTick);
  12758. if (backwards)
  12759. {
  12760. const auto f = total - to, t = total - from;
  12761. from = f;
  12762. to = t;
  12763. }
  12764. const auto kept = stripsilence::keptSpans (sample->leftData(), sample->isStereo() ? sample->rightData() : nullptr, (std::int64_t) sample->frames(),
  12765. sample->sampleRate, (std::int64_t) std::floor (from + (double) span.first),
  12766. (std::int64_t) std::ceil (to + (double) span.first), options);
  12767. if (kept.empty())
  12768. {
  12769. ++allQuiet;
  12770. continue;
  12771. }
  12772. // file frames -> ticks from the clip's start (a backwards clip reads its span from the end)
  12773. const auto tickOf = [&] (std::int64_t frame) {
  12774. const auto inSpan = (double) frame - (double) span.first;
  12775. return (backwards ? (total - inSpan) / perTick : inSpan / perTick) - (double) c.offset;
  12776. };
  12777. std::vector<stripsilence::Span> pieces;
  12778. for (const auto& k : kept)
  12779. {
  12780. auto a = tickOf (k.from), b = tickOf (k.to);
  12781. if (backwards)
  12782. std::swap (a, b);
  12783. pieces.push_back ({ std::max<std::int64_t> (0, (std::int64_t) std::floor (a)), std::min<std::int64_t> (c.length, (std::int64_t) std::ceil (b)) });
  12784. }
  12785. std::sort (pieces.begin(), pieces.end(), [] (const stripsilence::Span& x, const stripsilence::Span& y) { return x.from < y.from; });
  12786. if (pieces.size() == 1 && pieces[0].from <= 0 && pieces[0].to >= c.length)
  12787. {
  12788. ++nothing;
  12789. continue;
  12790. }
  12791. plans.push_back ({ i, std::move (pieces) });
  12792. }
  12793. if (plans.empty())
  12794. {
  12795. if (why != nullptr)
  12796. *why = allQuiet > 0 && nothing == 0 ? tr ("All of it is below the threshold: nothing was split") : tr ("No silence to strip at this threshold");
  12797. return 0;
  12798. }
  12799. std::vector<int> made;
  12800. setSelection ({});
  12801. engine.editSong ([&] (Song& s) {
  12802. for (const auto& [clip, pieces] : plans) // (pieces are appended: the indices of the other clips stay)
  12803. for (auto k : stripsilence::splitClip (s.playlist, clip, pieces))
  12804. made.push_back (k);
  12805. });
  12806. sortClips();
  12807. if (why != nullptr)
  12808. *why = tr ("Split at silence: {0} clip(s)", { juce::String ((int) made.size()) });
  12809. repaint();
  12810. return (int) made.size();
  12811. }
  12812. std::unique_ptr<juce::Component> PlaylistComponent::makeSplitSilenceDialogForSnapshot (int)
  12813. {
  12814. struct Holder final : juce::Component
  12815. {
  12816. std::unique_ptr<juce::AlertWindow> box;
  12817. };
  12818. auto holder = std::make_unique<Holder>();
  12819. holder->box.reset (buildSplitSilenceDialog (nullptr));
  12820. holder->addAndMakeVisible (*holder->box);
  12821. holder->box->setTopLeftPosition (0, 0);
  12822. holder->setSize (holder->box->getWidth(), holder->box->getHeight());
  12823. return holder;
  12824. }
  12825. void PlaylistComponent::normalizeClips (const std::vector<int>& targets, bool asGroup)
  12826. {
  12827. // FL's Normalize (round 189n, clipops::normalizeGain / groupNormalizeGain): the clip gain that brings the peak of the
  12828. // played part to 0 dB, each clip on its own (-96.1 ... +36 dB) or one gain for the whole group
  12829. const auto& song = engine.getSong();
  12830. std::vector<std::pair<int, float>> gainsFor;
  12831. for (auto i : targets)
  12832. {
  12833. if (i < 0 || i >= (int) song.playlist.size())
  12834. continue;
  12835. const auto& c = song.playlist[(std::size_t) i];
  12836. if (c.kind != ClipKind::audio || c.channel < 0 || c.channel >= (int) song.channels.size())
  12837. continue;
  12838. const auto& channel = song.channels[(std::size_t) c.channel];
  12839. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str()));
  12840. if (sample == nullptr || sample->frames() == 0)
  12841. continue;
  12842. const auto span = clipops::clipSpan (channel, sample); // what the clip plays of the file (round 180d)
  12843. const auto total = (double) span.frames;
  12844. const auto perTick = clipops::framesPerTick (channel, c, total, sample->sampleRate, song.bpm);
  12845. auto from = juce::jlimit (0.0, total, (double) c.offset * perTick);
  12846. auto to = juce::jlimit (from, total, (double) (c.offset + c.length) * perTick);
  12847. if (clipops::playsBackwards (channel, c)) // the clip's offset counts from the played span's end
  12848. {
  12849. const auto f = total - to, t = total - from;
  12850. from = f;
  12851. to = t;
  12852. }
  12853. from += (double) span.first;
  12854. to += (double) span.first;
  12855. float peak = 0.0f;
  12856. for (auto* data : { sample->leftData(), sample->rightData() })
  12857. if (data != nullptr)
  12858. for (auto f = (std::size_t) from; f < (std::size_t) to; ++f)
  12859. peak = juce::jmax (peak, std::abs (data[f]));
  12860. gainsFor.push_back ({ i, peak });
  12861. }
  12862. if (asGroup)
  12863. {
  12864. std::vector<float> peaks;
  12865. for (auto [i, peak] : gainsFor)
  12866. peaks.push_back (peak);
  12867. const auto g = clipops::groupNormalizeGain (peaks);
  12868. if (g == 0.0f)
  12869. return;
  12870. for (auto& entry : gainsFor)
  12871. entry.second = g;
  12872. }
  12873. else
  12874. for (auto& [i, peak] : gainsFor)
  12875. peak = clipops::normalizeGain (peak, song.playlist[(std::size_t) i].gain);
  12876. if (! gainsFor.empty())
  12877. engine.editSong ([gainsFor] (Song& s) {
  12878. for (auto [i, g] : gainsFor)
  12879. if (i < (int) s.playlist.size())
  12880. s.playlist[(std::size_t) i].gain = g;
  12881. });
  12882. }
  12883. void PlaylistComponent::visibilityChanged()
  12884. {
  12885. // hidden while a clip preview or the Listen tool is sounding (no mouse up will come here): stop it
  12886. if (! isShowing() && (drag == Drag::preview || drag == Drag::listen))
  12887. {
  12888. if (drag == Drag::preview)
  12889. stopPreview();
  12890. else
  12891. engine.stop();
  12892. drag = Drag::none;
  12893. }
  12894. }
  12895. void PlaylistComponent::startPreview (int clip, int x)
  12896. {
  12897. const auto& song = engine.getSong();
  12898. if (clip < 0 || clip >= (int) song.playlist.size())
  12899. return;
  12900. const auto c = song.playlist[(std::size_t) clip];
  12901. previewPositionBefore = engine.getTransport().positionTicks.load();
  12902. previewPatternBefore = -1;
  12903. previewRestoreSong = false;
  12904. drag = Drag::preview;
  12905. const auto at = juce::jlimit ((double) c.start, (double) c.end(), xToTick (x));
  12906. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  12907. {
  12908. // a pattern clip plays its pattern alone, from the clicked point
  12909. const auto length = (double) juce::jmax<std::int64_t> (1, song.patterns[(std::size_t) c.pattern].effectiveLength (song.meter()));
  12910. previewRestoreSong = song.mode == PlayMode::song;
  12911. previewPatternBefore = song.currentPattern;
  12912. engine.editSong ([p = c.pattern] (Song& s) {
  12913. s.mode = PlayMode::pattern;
  12914. s.currentPattern = p;
  12915. }, false);
  12916. engine.seek (std::fmod (at - (double) c.start + (double) c.offset, length));
  12917. }
  12918. else
  12919. {
  12920. if (song.mode != PlayMode::song)
  12921. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  12922. engine.seek (at);
  12923. }
  12924. engine.play();
  12925. setMouseCursor (editorCursor (gesture::Cursor::listen));
  12926. ui::postHint ({ tr ("Previewing the clip: release the mouse to stop"), {}, false, false }, 60000);
  12927. }
  12928. juce::PopupMenu PlaylistComponent::buildAddTrackMenu()
  12929. {
  12930. // FL's AddInstrumentMenu (round 190dx [FORM]): "Audio track": Add audio track (FL's default item); "Instrument
  12931. // track": More plugins..., a line, the generator list (FUN_01195420, the Channel rack's Insert list)
  12932. juce::PopupMenu menu;
  12933. menu.addSectionHeader (tr ("Audio track"));
  12934. menu.addItem (tr ("Add audio track"), [this] { addAudioTrackNow(); });
  12935. menu.addSectionHeader (tr ("Instrument track"));
  12936. menu.addItem (tr ("More plugins..."), [this] { morePluginsForTrack (-1); });
  12937. menu.addSeparator();
  12938. quickpick::addGeneratorMenu (menu, engine, [this] (ChannelDef c) { instrumentForTrack (-1, std::move (c)); }, nullptr, nullptr, this);
  12939. quickpick::addFolderViewItems (menu, engine);
  12940. return menu;
  12941. }
  12942. int PlaylistComponent::addAudioTrackNow()
  12943. {
  12944. int track = -1;
  12945. engine.editSong ([&track] (Song& s) { track = trackmodes::addAudioTrack (s); });
  12946. if (track < 0)
  12947. {
  12948. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't create new audio track"),
  12949. tr ("There are no available mixer tracks."));
  12950. return -1;
  12951. }
  12952. selectTrack (track); // FL: the new track alone is selected, scrolled into view
  12953. repaint();
  12954. return track;
  12955. }
  12956. void PlaylistComponent::instrumentForTrack (int track, ChannelDef generator)
  12957. {
  12958. const auto& song = engine.getSong();
  12959. const auto kind = generator.instrument;
  12960. int channel = -1;
  12961. // FL (EEPLTrackMorePlugMenuClick): on an instrument track the chosen generator replaces its channel's
  12962. if (track >= 0 && track < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) track].mode == PlaylistTrackMode::instrument
  12963. && song.playlistTracks[(std::size_t) track].channel >= 0 && song.playlistTracks[(std::size_t) track].channel < (int) song.channels.size())
  12964. {
  12965. channel = song.playlistTracks[(std::size_t) track].channel;
  12966. bool ok = false;
  12967. engine.editSong ([channel, &generator, &ok] (Song& s) { ok = replaceGenerator (s, channel, std::move (generator)); });
  12968. if (! ok)
  12969. return;
  12970. }
  12971. else
  12972. {
  12973. if (kind == InstrumentKind::audioClip || kind == InstrumentKind::controller)
  12974. {
  12975. // FL's error (LineAssignInstrTrackMenuClick, round 190dx)
  12976. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  12977. tr ("This generator can't be used as an instrument track."));
  12978. return;
  12979. }
  12980. engine.editSong ([&] (Song& s) { channel = trackmodes::addInstrumentTrack (s, std::move (generator), track); });
  12981. if (channel < 0)
  12982. {
  12983. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't create new instrument track"),
  12984. tr ("There are no available mixer tracks."));
  12985. return;
  12986. }
  12987. const auto tracks = trackmodes::instrumentTracksOf (engine.getSong(), channel);
  12988. if (! tracks.empty())
  12989. selectTrack (tracks.front());
  12990. }
  12991. repaint();
  12992. if (onGeneratorAdded)
  12993. onGeneratorAdded (channel, kind);
  12994. }
  12995. void PlaylistComponent::morePluginsForTrack (int track)
  12996. {
  12997. // FL's More plugins...: its plugin dialog for generators (FUN_010dc760); LYNX's plugin picker
  12998. juce::Component::SafePointer<PlaylistComponent> safe (this);
  12999. showPluginPicker (
  13000. engine, true,
  13001. [safe, track] (PluginRef ref) {
  13002. if (safe == nullptr)
  13003. return;
  13004. ChannelDef c;
  13005. c.name = ref.name;
  13006. c.instrument = InstrumentKind::plugin;
  13007. c.plugin = ref;
  13008. safe->instrumentForTrack (track, std::move (c));
  13009. },
  13010. [safe, track] (ChannelDef c) {
  13011. if (safe != nullptr)
  13012. safe->instrumentForTrack (track, std::move (c));
  13013. });
  13014. }
  13015. void PlaylistComponent::previewClipAudio (int clip)
  13016. {
  13017. // FL plays the clip through its channel as the clip plays it (offset, pitch, stretch; FUN_01239e40 → FUN_00ffa0a0).
  13018. // LYNX: the clip's own audio as its channel's instrument renders it (renderClipAudio), at the clip's and the
  13019. // channel's volume, through the preview output (the insert's effects are not heard)
  13020. const auto& song = engine.getSong();
  13021. if (clip < 0 || clip >= (int) song.playlist.size() || song.playlist[(std::size_t) clip].kind != ClipKind::audio)
  13022. return;
  13023. const auto& c = song.playlist[(std::size_t) clip];
  13024. if (c.channel < 0 || c.channel >= (int) song.channels.size())
  13025. return;
  13026. // Round 190ey (live check 190ew PL-3): FL plays it through the channel's mixer insert (its effects and meter), to the
  13027. // clip's end; transport start / stop ends it. An audio clip channel plays it so (the song's own note for the clip)
  13028. const auto& channel = song.channels[(std::size_t) c.channel];
  13029. if (channel.instrument == InstrumentKind::audioClip && engine.previewClipThroughChannel ((std::size_t) clip))
  13030. return;
  13031. // (else, as before: with the channel's Levels adjustment volume, round 190dz: FL's channel gain includes it)
  13032. const auto gain = c.gain * channelGain (channel.volume) * levelAdjustGain (channel.misc.levels.volume);
  13033. auto audio = engine.renderClipAudio ((std::size_t) clip);
  13034. if (audio.left.empty())
  13035. return;
  13036. auto sample = std::make_shared<SampleData>();
  13037. sample->sampleRate = audio.sampleRate;
  13038. sample->left = std::move (audio.left);
  13039. sample->right = std::move (audio.right);
  13040. engine.previewSample (std::move (sample), false, gain);
  13041. }
  13042. void PlaylistComponent::stopPreview()
  13043. {
  13044. engine.stop();
  13045. if (previewPatternBefore >= 0)
  13046. engine.editSong ([this] (Song& s) {
  13047. if (previewPatternBefore < (int) s.patterns.size())
  13048. s.currentPattern = previewPatternBefore;
  13049. if (previewRestoreSong)
  13050. s.mode = PlayMode::song;
  13051. }, false);
  13052. engine.seek (previewPositionBefore);
  13053. previewPatternBefore = -1;
  13054. ui::clearPostedHint();
  13055. }
  13056. void PlaylistComponent::setRipple (bool on)
  13057. {
  13058. ripple = on;
  13059. repaint();
  13060. }
  13061. void PlaylistComponent::rippleDeleteSelection()
  13062. {
  13063. if (selection.empty())
  13064. return;
  13065. auto doomed = selection;
  13066. setSelection ({});
  13067. engine.editSong ([&doomed] (Song& s) { noteedit::rippleDelete (s.playlist, doomed); });
  13068. }
  13069. void PlaylistComponent::zoomAroundCentre (double factor)
  13070. {
  13071. // round 190qe (UX-A2): the keys zoom around the playhead while it plays on screen, else the selection's centre on
  13072. // screen, else the view's centre (as before); the step glides with Animations on (UX-A3). Issue #276 (round 190qr,
  13073. // the LYNX extra "Zoom around the song position"): the song position when it is in view, before all of those
  13074. settleViewGlide();
  13075. const auto grid = gridArea();
  13076. const auto anchor = zoomanchor::anchorX (zoomanchor::atSongPosition(), keyZoomAnchorPx() + grid.getX(), tickToX ((double) songPositionTick()),
  13077. (double) grid.getX(), (double) grid.getRight())
  13078. - grid.getX();
  13079. auto target = currentView();
  13080. target.pixelsPerUnit = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick * factor);
  13081. target.scroll = zoomanchor::scrollFor (scrollTicks, pixelsPerTick, target.pixelsPerUnit, anchor);
  13082. showView (clampedView (target));
  13083. }
  13084. void PlaylistComponent::zoomToBars (int bars)
  13085. {
  13086. const auto bar = (double) engine.getSong().barTicks();
  13087. const auto from = std::floor (scrollTicks / bar) * bar;
  13088. zoomToTicks (from, from + bars * bar);
  13089. }
  13090. void PlaylistComponent::zoomAll()
  13091. {
  13092. zoomToTicks (0.0, (double) engine.getSong().songLength());
  13093. }
  13094. void PlaylistComponent::zoomToSelection()
  13095. {
  13096. const auto& song = engine.getSong();
  13097. // round 190qe (D2-PL8): the view it leaves goes on the view stack; the same key again (the view still the one it
  13098. // zoomed to) goes back to it
  13099. settleViewGlide();
  13100. const auto before = currentView();
  13101. auto target = before;
  13102. auto range = [this, &target] (double from, double to) {
  13103. if (to - from >= 1.0)
  13104. {
  13105. target.pixelsPerUnit = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, gridArea().getWidth() / (to - from));
  13106. target.scroll = juce::jmax (0.0, from);
  13107. }
  13108. };
  13109. if (song.hasLoop() && selection.empty())
  13110. range ((double) song.loopStart, (double) song.loopEnd);
  13111. else if (selection.empty())
  13112. range (0.0, (double) song.songLength());
  13113. else
  13114. {
  13115. std::int64_t from = INT64_MAX, to = 0;
  13116. int top = 1 << 20;
  13117. for (auto i : selection)
  13118. if (i >= 0 && i < (int) song.playlist.size())
  13119. {
  13120. from = juce::jmin (from, song.playlist[(std::size_t) i].start);
  13121. to = juce::jmax (to, song.playlist[(std::size_t) i].end());
  13122. top = juce::jmin (top, song.playlist[(std::size_t) i].track);
  13123. }
  13124. range ((double) from, (double) to);
  13125. if (top < (1 << 20))
  13126. target.scrollY = juce::jmax (0, trackToY (top) - tracksTop() + scrollY);
  13127. }
  13128. // (round 190ro, D-2: pressed again, FL's view stays; LYNX's extra goes back)
  13129. const auto lynxKeys = zoomanchor::lynxKeysNow (layoutstyle::current() == layoutstyle::Style::pattern);
  13130. showView (lynxKeys ? viewStack.toggle (before, clampedView (target)) : viewStack.push (before, clampedView (target)));
  13131. }
  13132. // The view as the scroll bars would leave it (the song's range, the tracks' height): the stack compares views exactly
  13133. viewstack::View PlaylistComponent::clampedView (const viewstack::View& v)
  13134. {
  13135. const auto saved = currentView();
  13136. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, v.pixelsPerUnit);
  13137. scrollTicks = juce::jmax (0.0, v.scroll);
  13138. scrollY = juce::jmax (0, (int) std::lround (v.scrollY));
  13139. updateScrollBars();
  13140. const auto clamped = currentView();
  13141. pixelsPerTick = saved.pixelsPerUnit;
  13142. scrollTicks = saved.scroll;
  13143. scrollY = (int) saved.scrollY;
  13144. updateScrollBars();
  13145. return clamped;
  13146. }
  13147. // A glide still running lands at once (another zoom, a click, the wheel start from where it was going)
  13148. void PlaylistComponent::settleViewGlide()
  13149. {
  13150. if (! viewGlide.running)
  13151. return;
  13152. viewGlide.running = false;
  13153. applyView (viewGlide.to);
  13154. }
  13155. void PlaylistComponent::centreOnPlayhead()
  13156. {
  13157. const auto tick = engine.songPlayheadTicks();
  13158. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick / 2.0);
  13159. updateScrollBars();
  13160. repaint();
  13161. }
  13162. // --- round 190qe (TOP-NEXT R1): edge scroll, view stack, zoom glide, selection history ---------------------------------
  13163. // The drags that scroll the view at the arrangement's edges: a clip moved or resized, a selection box, a brush stroke (FL
  13164. // scrolls for each; round 190qc). Not a drag out of the Playlist (the Clip-launch grid takes it then).
  13165. bool PlaylistComponent::edgeScrollsX() const
  13166. {
  13167. return drag == Drag::move || drag == Drag::resize || drag == Drag::trimLeft || drag == Drag::select || drag == Drag::paint;
  13168. }
  13169. bool PlaylistComponent::edgeScrollsY() const
  13170. {
  13171. return drag == Drag::move || drag == Drag::select || drag == Drag::paint;
  13172. }
  13173. // One frame of the edge scroll: the pointer (still, or where the last drag event left it) past an edge scrolls the view
  13174. // by FL's speed (Pattern) or the Live-like one, in whole physical px; the dragged item is laid out again for the
  13175. // pointer, whose place in the song moved with the view. Esc holds it until the pointer comes back in; the release ends it.
  13176. bool PlaylistComponent::edgeScrollFrame (double nowMs)
  13177. {
  13178. const auto* dnd = juce::DragAndDropContainer::findParentDragContainerFor (this);
  13179. if (! edgeDragEvent.has_value() || ! (edgeScrollsX() || edgeScrollsY()) || ! (isMouseButtonDown() || edgescroll::buttonHeldForTests) || (dnd != nullptr && dnd->isDragAndDropActive()))
  13180. {
  13181. edgeScroller.stop();
  13182. return false;
  13183. }
  13184. if (juce::KeyPress::isKeyCurrentlyDown (juce::KeyPress::escapeKey))
  13185. edgeScroller.hold();
  13186. const auto grid = gridArea();
  13187. const auto law = layoutstyle::current() == layoutstyle::Style::pattern ? edgescroll::Law::fl : edgescroll::Law::smooth;
  13188. const auto quantum = (double) edgescroll::wholeQuantum (juce::Component::getApproximateScaleFactorForComponent (this));
  13189. const auto at = edgeDragEvent->position;
  13190. const auto step = edgeScroller.update (nowMs, at.x, at.y, grid.getX(), grid.getY(), grid.getRight(), grid.getBottom(), edgeScrollsX(),
  13191. edgeScrollsY(), law, quantum);
  13192. if (step.dx == 0.0 && step.dy == 0.0)
  13193. return step.running;
  13194. const auto oldTicks = scrollTicks;
  13195. const auto oldY = scrollY;
  13196. if (step.dx != 0.0)
  13197. scrollTicks = juce::jmax (0.0, scrollTicks + step.dx / pixelsPerTick); // (it stops at the song's start, as FL's)
  13198. if (step.dy != 0.0)
  13199. scrollY = juce::jmax (0, scrollY + (int) step.dy);
  13200. updateScrollBars();
  13201. if (scrollTicks != oldTicks || scrollY != oldY)
  13202. {
  13203. repaintScrolled();
  13204. const auto event = *edgeDragEvent;
  13205. mouseDrag (event); // (the dragged clip / box / stroke follows the song under the still pointer)
  13206. }
  13207. return step.running;
  13208. }
  13209. bool PlaylistComponent::feelFrame (double nowMs)
  13210. {
  13211. auto active = edgeScrollFrame (nowMs);
  13212. if (viewGlide.running)
  13213. {
  13214. if (viewGlide.done (nowMs))
  13215. {
  13216. viewGlide.running = false;
  13217. applyView (viewGlide.to);
  13218. }
  13219. else
  13220. applyView (viewGlide.at (nowMs));
  13221. active = true;
  13222. }
  13223. return active;
  13224. }
  13225. viewstack::View PlaylistComponent::currentView() const
  13226. {
  13227. return { scrollTicks, pixelsPerTick, (double) scrollY };
  13228. }
  13229. void PlaylistComponent::applyView (const viewstack::View& v)
  13230. {
  13231. const auto zoomed = v.pixelsPerUnit != pixelsPerTick;
  13232. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, v.pixelsPerUnit);
  13233. scrollTicks = juce::jmax (0.0, v.scroll);
  13234. scrollY = juce::jmax (0, (int) std::lround (v.scrollY));
  13235. updateScrollBars();
  13236. if (zoomed)
  13237. repaintZoomed();
  13238. else
  13239. repaintScrolled();
  13240. }
  13241. // UX-A3: the zoom keys, fit and zoom-to-selection glide over 150 ms (ease-out) while Animations are on; off: at once
  13242. void PlaylistComponent::showView (const viewstack::View& target)
  13243. {
  13244. if (ui::motion::enabled() && (! platform::testMode() || glide::inTests) && ui::showingOrShot (*this))
  13245. {
  13246. viewGlide.start (currentView(), target, juce::Time::getMillisecondCounterHiRes(), (double) gridArea().getWidth());
  13247. if (viewGlide.running)
  13248. {
  13249. frames.wake();
  13250. return;
  13251. }
  13252. }
  13253. viewGlide.running = false;
  13254. applyView (target);
  13255. }
  13256. // UX-A2: the zoom keys' anchor (px from the grid's left): the playhead while playing and on screen, else the centre of the
  13257. // selected clips when on screen, else the view's centre
  13258. double PlaylistComponent::keyZoomAnchorPx() const
  13259. {
  13260. const auto grid = gridArea();
  13261. // round 190ro (D-2): FL's anchor unless the LYNX extra "editing.zoomKeysLynx" is on (always outside the Pattern layout)
  13262. if (! zoomanchor::lynxKeysNow (layoutstyle::current() == layoutstyle::Style::pattern))
  13263. {
  13264. const auto mouse = getMouseXYRelative();
  13265. return zoomanchor::flKeyAnchorPx (isMouseOver (true) && grid.contains (mouse) ? std::optional<double> ((double) (mouse.x - grid.getX())) : std::nullopt,
  13266. (double) grid.getWidth());
  13267. }
  13268. const auto& song = engine.getSong();
  13269. const auto playing = engine.getTransport().playing.load() && song.mode == PlayMode::song;
  13270. std::optional<double> playhead, selected;
  13271. if (playing)
  13272. playhead = tickToX (engine.songPlayheadTicks()) - grid.getX();
  13273. if (! selection.empty())
  13274. {
  13275. std::int64_t from = INT64_MAX, to = 0;
  13276. for (auto i : selection)
  13277. if (i >= 0 && i < (int) song.playlist.size())
  13278. {
  13279. from = juce::jmin (from, song.playlist[(std::size_t) i].start);
  13280. to = juce::jmax (to, song.playlist[(std::size_t) i].end());
  13281. }
  13282. if (to > from)
  13283. selected = tickToX (0.5 * (double) (from + to)) - grid.getX();
  13284. }
  13285. return zoomanchor::anchorPx (zoomanchor::Source::keys, 0.0, grid.getWidth(), playing, playhead, selected);
  13286. }
  13287. std::vector<PlaylistComponent::ClipKey> PlaylistComponent::clipKeysInOrder() const
  13288. {
  13289. const auto& playlist = engine.getSong().playlist;
  13290. std::vector<ClipKey> keys;
  13291. keys.reserve (playlist.size());
  13292. for (const auto& c : playlist)
  13293. keys.push_back ({ c.track, (int) c.kind, c.kind == ClipKind::audio ? c.channel : c.kind == ClipKind::automation ? c.automation : c.pattern,
  13294. c.start, c.length });
  13295. return keys;
  13296. }
  13297. std::vector<PlaylistComponent::ClipKey> PlaylistComponent::clipKeys (const std::vector<int>& indices) const
  13298. {
  13299. const auto& playlist = engine.getSong().playlist;
  13300. std::vector<ClipKey> keys;
  13301. for (auto i : indices)
  13302. if (i >= 0 && i < (int) playlist.size())
  13303. {
  13304. const auto& c = playlist[(std::size_t) i];
  13305. keys.push_back ({ c.track, (int) c.kind, c.kind == ClipKind::audio ? c.channel : c.kind == ClipKind::automation ? c.automation : c.pattern,
  13306. c.start, c.length });
  13307. }
  13308. std::sort (keys.begin(), keys.end());
  13309. return keys;
  13310. }
  13311. // D2-PL9: Edit › "Restore selection" — the selection a click replaced or cleared (the last 8, newest first); the clips
  13312. // are found again by their track, place and source, so edits in between don't pick other clips
  13313. void PlaylistComponent::restoreSelection()
  13314. {
  13315. const auto restored = selectionHistory.restore (clipKeys (selection));
  13316. if (! restored.has_value())
  13317. {
  13318. ui::postHint ({ tr ("No earlier selection to restore"), {}, false, false }, 2000);
  13319. return;
  13320. }
  13321. const auto& playlist = engine.getSong().playlist;
  13322. std::vector<int> indices;
  13323. for (int i = 0; i < (int) playlist.size(); ++i)
  13324. if (const auto key = clipKeys ({ i }); ! key.empty() && std::binary_search (restored->begin(), restored->end(), key.front()))
  13325. indices.push_back (i);
  13326. const juce::ScopedValueSetter<bool> restoring (selectionHistory.restoring, true);
  13327. setSelection (indices);
  13328. repaint();
  13329. }
  13330. // D2-PL8: "Previous view" — back to the view the last "Zoom to the selection" left
  13331. void PlaylistComponent::previousView()
  13332. {
  13333. if (const auto before = viewStack.back())
  13334. showView (*before);
  13335. }
  13336. bool PlaylistComponent::runAction (const std::string& id)
  13337. {
  13338. auto is = [&id] (const char* name) { return id == name; };
  13339. // issue #327 (round 190sj): the F1 sheet's editing keys, key-map actions now (Manage shortcuts lists them)
  13340. if (is ("playlist.selectAll")) { selectAllWithTime(); return true; }
  13341. if (is ("playlist.copy")) { copySelection(); return true; }
  13342. if (is ("playlist.cut")) { copySelection(); deleteSelection(); return true; }
  13343. if (is ("playlist.paste")) { pasteClips(); return true; }
  13344. if (is ("playlist.duplicate")) { duplicateSelection (false); return true; }
  13345. // round 190qu (Discord 11-24): the selected automation clips into their tracks' lanes, and the time selection of the
  13346. // selected track's lanes as automation clips (no default keys: FL and Live have none)
  13347. if (is ("playlist.selectedClipsToLanes"))
  13348. {
  13349. if (! autolanes::shown() || selection.empty())
  13350. {
  13351. ui::postHint ({ tr ("Select automation clips first (with Automation lanes on)"), {}, false, false }, 3000);
  13352. return true;
  13353. }
  13354. int moved = 0;
  13355. const auto chosen = selection;
  13356. setSelection ({});
  13357. engine.editSong ([&moved, chosen] (Song& s) { moved = laneview::clipsIntoLanes (s, chosen); });
  13358. ui::postHint ({ tr ("{0} automation clips moved into their tracks' lanes (Edit › Undo takes it back)", { juce::String (moved) }), {} }, 3000);
  13359. return true;
  13360. }
  13361. if (is ("playlist.laneRangeToClip"))
  13362. {
  13363. const auto& song = engine.getSong();
  13364. auto tracks = sortedTrackSelection();
  13365. if (tracks.empty() && currentTrack >= 0)
  13366. tracks.push_back (currentTrack);
  13367. if (! song.hasLoop() || tracks.empty())
  13368. {
  13369. ui::postHint ({ tr ("Make a time selection and select a track with automation lanes first"), {}, false, false }, 3000);
  13370. return true;
  13371. }
  13372. std::vector<int> made;
  13373. engine.editSong ([&made, tracks] (Song& s) {
  13374. for (const auto t : tracks)
  13375. if (t >= 0 && t < (int) s.playlistTracks.size())
  13376. for (int l = 0; l < (int) s.playlistTracks[(std::size_t) t].lanes.size(); ++l)
  13377. if (const auto c = laneview::laneRangeToClip (s, t, l, s.loopStart, s.loopEnd); c >= 0)
  13378. made.push_back (c);
  13379. });
  13380. setSelection (made);
  13381. return true;
  13382. }
  13383. if (is ("playlist.changeIcon")) // issue #220 (round 190ng): F3, the icon picker (search box first) of the selected tracks
  13384. {
  13385. auto targets = sortedTrackSelection();
  13386. if (targets.empty()) // (else the tracks of the selected clips)
  13387. {
  13388. for (const auto i : selection)
  13389. if (i >= 0 && i < (int) engine.getSong().playlist.size())
  13390. targets.push_back (engine.getSong().playlist[(std::size_t) i].track);
  13391. std::sort (targets.begin(), targets.end());
  13392. targets.erase (std::unique (targets.begin(), targets.end()), targets.end());
  13393. }
  13394. if (targets.empty())
  13395. {
  13396. ui::postHint ({ tr ("Select a track first (click its header), then F3 picks its icon"), {}, false, false }, 3000);
  13397. return true;
  13398. }
  13399. const auto& tracks = engine.getSong().playlistTracks;
  13400. const auto current = targets.front() < (int) tracks.size() ? tracks[(std::size_t) targets.front()].icon : 0;
  13401. const auto mouse = juce::Desktop::getMousePosition();
  13402. ui::showTrackIconPicker ({ mouse.x, mouse.y, 1, 1 }, current, [this, targets] (int icon) {
  13403. engine.editSong ([targets, icon] (Song& s) {
  13404. for (const auto t : targets)
  13405. {
  13406. if ((int) s.playlistTracks.size() <= t)
  13407. s.playlistTracks.resize ((std::size_t) t + 1);
  13408. s.playlistTracks[(std::size_t) t].icon = icon;
  13409. }
  13410. });
  13411. });
  13412. }
  13413. else if (is ("playlist.zoomIn")) zoomAroundCentre (1.25);
  13414. else if (is ("playlist.zoomOut")) zoomAroundCentre (1.0 / 1.25);
  13415. else if (is ("playlist.zoom1")) zoomToBars (1);
  13416. else if (is ("playlist.zoom2")) zoomToBars (4);
  13417. else if (is ("playlist.zoom3")) zoomToBars (16);
  13418. else if (is ("playlist.zoomAll")) zoomAll();
  13419. else if (is ("playlist.zoomSelection")) zoomToSelection();
  13420. else if (is ("playlist.previousView")) previousView(); // round 190qe (D2-PL8)
  13421. else if (is ("playlist.restoreSelection")) restoreSelection(); // round 190qe (D2-PL9)
  13422. else if (is ("playlist.centrePlayhead")) centreOnPlayhead();
  13423. else if (is ("playlist.rippleDelete")) rippleDeleteSelection();
  13424. else if (is ("playlist.ripple")) setRipple (! ripple);
  13425. else if (is ("playlist.autoCrossfades")) engine.editSong ([] (Song& s) { s.autoCrossfades = ! s.autoCrossfades; });
  13426. else if (is ("playlist.linkTracks")) switchLinkTracks (engine, ! engine.getSong().linkTracksToMixer); // rounds 190gz, 190ib
  13427. else if (is ("playlist.trackInserts")) // round 190ht (issue #154): a view option, not the project's
  13428. {
  13429. showTrackInserts = ! showTrackInserts;
  13430. updateHeaderWidth();
  13431. repaint();
  13432. if (onViewOptionChanged)
  13433. onViewOptionChanged();
  13434. }
  13435. else if (is ("playlist.patternBlocks")) togglePatternBlocks();
  13436. else if (is ("playlist.showHiddenTracks")) // round 190op (P4): a view option, not the project's
  13437. {
  13438. showHiddenTracks = ! showHiddenTracks;
  13439. refreshTrackLayout();
  13440. updateScrollBars();
  13441. repaint();
  13442. if (onViewOptionChanged)
  13443. onViewOptionChanged();
  13444. }
  13445. else if (is ("playlist.hideUnusedTracks")) // round 190op (P4): one undo step
  13446. {
  13447. int hidden = 0;
  13448. engine.editSong ([&hidden] (Song& s) { hidden = trackstates::hideUnused (s); });
  13449. ui::postHint ({ tr ("{0} unused tracks hidden (Playlist › Show hidden tracks shows them)", { juce::String (hidden) }), {}, false, false }, 3000);
  13450. setSelection ({});
  13451. refreshTrackLayout();
  13452. updateScrollBars();
  13453. repaint();
  13454. }
  13455. else if (is ("playlist.automationLanes")) toggleAutomationLanes();
  13456. else if (is ("playlist.blocksToClips")) turnBlocksIntoClips();
  13457. else if (is ("playlist.follow")) EditorGlobals::get().setFollowing (false, ! EditorGlobals::get().isFollowing (false));
  13458. else if (is ("playlist.selectTimeAround")) selectTimeAroundSelection();
  13459. else if (is ("playlist.swipeSelectionToComp")) swipeTimeSelectionToComp (currentTrack);
  13460. else if (is ("playlist.timePrevious")) moveTimeSelection (-1);
  13461. else if (is ("playlist.timeNext")) moveTimeSelection (1);
  13462. else if (is ("playlist.nextTransient")) moveToTransient (1, false); // round 190on (P8)
  13463. else if (is ("playlist.prevTransient")) moveToTransient (-1, false);
  13464. else if (is ("playlist.extendToNextTransient")) moveToTransient (1, true);
  13465. else if (is ("playlist.extendToPrevTransient")) moveToTransient (-1, true);
  13466. else if (is ("playlist.markerAdd")) addMarkerByKey();
  13467. else if (is ("playlist.markerAuto")) addAutoMarker();
  13468. else if (is ("playlist.markerSignature")) addSignatureChangeByKey();
  13469. else if (is ("playlist.markerLoop")) placeLoopMarker();
  13470. else if (is ("playlist.pitchClipsDown")) pitchSelectedAudioClips (-1);
  13471. else if (is ("playlist.pitchClipsUp")) pitchSelectedAudioClips (1);
  13472. else if (is ("playlist.reverseClips")) reverseSelectedAudioClips();
  13473. else if (is ("playlist.quantizeStarts")) quantizeClips (1.0);
  13474. else if (is ("playlist.quantizeHalf")) quantizeClips (0.5);
  13475. else if (is ("playlist.performanceMode")) togglePerformanceMode();
  13476. else if (is ("playlist.zoomPerformance")) zoomOnPerformanceClips();
  13477. else if (is ("playlist.perfClipProgress")) { showClipProgress = ! showClipProgress; repaint(); }
  13478. else if (is ("playlist.perfTrackProgress")) { showTrackProgress = ! showTrackProgress; repaint(); }
  13479. else if (is ("playlist.muteClips") || is ("playlist.unmuteClips"))
  13480. {
  13481. // FL limits it to the time selection when there is one
  13482. const auto& song = engine.getSong();
  13483. const auto from = song.hasLoop() ? song.loopStart : (std::int64_t) 0;
  13484. const auto to = song.hasLoop() ? song.loopEnd : std::numeric_limits<std::int64_t>::max();
  13485. auto mute = is ("playlist.muteClips");
  13486. // issue #249 (round 190oq, LYNX extra, off = FL's Alt+M that only mutes): pressed again, it unmutes
  13487. if (mute && mutekeys::toggles() && clipops::allClipsMuted (song, selection, from, to))
  13488. mute = false;
  13489. engine.editSong ([chosen = selection, mute, from, to] (Song& s) { clipops::setClipsMuted (s, chosen, mute, from, to); });
  13490. }
  13491. else if (is ("playlist.mergePatternClips")) mergePatternClipsByKey();
  13492. else if (is ("playlist.mergeSimilarClips")) mergeSimilarClipsByKey();
  13493. else if (is ("playlist.mergeAutomationClips")) mergeAutomationClipsByKey();
  13494. else if (is ("playlist.cloneTracks")) cloneTracksWithDialog (! selectedTracks.empty() ? selectedTracks : std::vector<int> { juce::jmax (0, currentTrack) });
  13495. else if (is ("playlist.muteTracks")) // issue #249 (round 190qo): the selected tracks' LEDs, all muted -> all unmuted
  13496. {
  13497. const auto chosen = sortedTrackSelection();
  13498. const auto& song = engine.getSong();
  13499. const auto allMuted = ! chosen.empty() && std::all_of (chosen.begin(), chosen.end(), [&song] (int t) { return song.isTrackMuted (t); });
  13500. engine.editSong ([chosen, allMuted] (Song& s) {
  13501. for (const auto t : chosen)
  13502. {
  13503. if (t < 0)
  13504. continue;
  13505. if ((int) s.playlistTracks.size() <= t)
  13506. s.playlistTracks.resize ((std::size_t) t + 1);
  13507. s.playlistTracks[(std::size_t) t].muted = ! allMuted;
  13508. }
  13509. });
  13510. repaint();
  13511. }
  13512. else if (is ("playlist.soloTrack")) // issue #249 (round 190qo): FL's right-click / Ctrl+click on the track's LED
  13513. {
  13514. if (const auto track = currentTrack >= 0 ? currentTrack : (selectedTracks.empty() ? -1 : selectedTracks.front()); track >= 0)
  13515. engine.editSong ([track, count = numTracks()] (Song& s) {
  13516. noteedit::soloTrack (s, track, count, &flsettings::trackSoloMemory(), flsettings::options().restoreStateAfterSolo.load());
  13517. });
  13518. repaint();
  13519. }
  13520. else if (is ("playlist.makeUnique")) makeSelectionUnique();
  13521. else if (is ("playlist.stretchMode")) setStretchOnResize (! EditorGlobals::get().stretchOnResize);
  13522. else if (is ("playlist.createVariants"))
  13523. {
  13524. EditorGlobals::get().createVariants = ! EditorGlobals::get().createVariants;
  13525. if (EditorGlobals::get().onOptionsChanged)
  13526. EditorGlobals::get().onOptionsChanged();
  13527. }
  13528. else if (is ("playlist.lockAllToContent")) lockAllTracks (true);
  13529. else if (is ("playlist.unlockAllFromContent")) lockAllTracks (false);
  13530. else if (is ("playlist.resetEmptyTracks")) resetEmptyTracksAsked();
  13531. else if (is ("playlist.collapseAllGroups")) engine.editSong ([] (Song& s) { pltracks::setAllGroupsCollapsed (s, true); });
  13532. else if (is ("playlist.expandAllGroups")) engine.editSong ([] (Song& s) { pltracks::setAllGroupsCollapsed (s, false); });
  13533. else if (is ("playlist.shiftLeft")) shiftSelectedClips (-1, 0);
  13534. else if (is ("playlist.shiftRight")) shiftSelectedClips (1, 0);
  13535. else if (is ("playlist.shiftUp")) shiftSelectedClips (0, -1);
  13536. else if (is ("playlist.shiftDown")) shiftSelectedClips (0, 1);
  13537. else if (is ("playlist.nudgeLeft")) shiftSelectedClips (-1, 0, true);
  13538. else if (is ("playlist.nudgeRight")) shiftSelectedClips (1, 0, true);
  13539. else if (is ("playlist.sliceInsertSpace")) sliceInsertTimeSelection();
  13540. else if (is ("playlist.trimSpace")) trimTimeSelection();
  13541. else if (is ("playlist.splitAtPlayhead")) splitAtPlayhead();
  13542. else if (is ("playlist.loopSwitch")) setLoopSwitch (! engine.getSong().loopPlays());
  13543. else if (is ("playlist.loopHalve") || is ("playlist.loopDouble"))
  13544. {
  13545. if (engine.getSong().hasLoop())
  13546. engine.editSong ([factor = is ("playlist.loopHalve") ? 0.5 : 2.0] (Song& s) { arrange::scaleLoop (s, factor); }, false);
  13547. }
  13548. else if (is ("playlist.duplicateTime")) timeCommand (0);
  13549. else if (is ("playlist.duplicateLinked")) duplicateSelection (true); // (round 190ne)
  13550. else if (is ("playlist.cutTime")) timeCommand (1);
  13551. else if (is ("playlist.copyTime")) timeCommand (2);
  13552. else if (is ("playlist.pasteTime")) timeCommand (3);
  13553. else if (is ("playlist.cropClips")) timeCommand (4);
  13554. else if (is ("playlist.automationFollowsClips"))
  13555. {
  13556. auto& g = EditorGlobals::get();
  13557. g.automationFollowsClips = automationFollows() ? 0 : 1;
  13558. if (g.onOptionsChanged)
  13559. g.onOptionsChanged();
  13560. }
  13561. else if (is ("playlist.deselect"))
  13562. {
  13563. setSelection ({}); // (FL's EEDeselAction, FUN_00eb1a90: the clips and the time selection)
  13564. rulerMark = -1;
  13565. if (engine.getSong().hasLoop())
  13566. engine.editSong ([] (Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  13567. }
  13568. else if (is ("playlist.selectBySource")) selectBySelectedSource();
  13569. else if (is ("playlist.invertSelection")) setSelection (clipops::invertedSelection ((int) engine.getSong().playlist.size(), selection));
  13570. else if (is ("playlist.leftResizing") || is ("playlist.wheelNudging") || is ("playlist.manualFades") || is ("playlist.snapFadeHandles")
  13571. || is ("playlist.magicLasso"))
  13572. {
  13573. auto& g = EditorGlobals::get();
  13574. auto& flag = is ("playlist.leftResizing") ? g.leftResizing : is ("playlist.wheelNudging") ? g.wheelNudging
  13575. : is ("playlist.manualFades") ? g.manualFades : is ("playlist.snapFadeHandles") ? g.snapFadeHandles : g.magicLasso;
  13576. flag = ! flag;
  13577. lassoPath.clear();
  13578. if (g.onOptionsChanged)
  13579. g.onOptionsChanged();
  13580. }
  13581. else if (is ("playlist.makeUniqueAsSample")) makeSelectionUniqueAsSample();
  13582. else if (is ("playlist.purgeUnusedAudio"))
  13583. {
  13584. setSelection ({});
  13585. engine.editSong ([] (Song& s) { pltracks::purgeUnusedAudioClips (s); });
  13586. sortClips();
  13587. }
  13588. else
  13589. return false;
  13590. return true;
  13591. }
  13592. namespace
  13593. {
  13594. // FL's Clone window (FUN_012edbe0 [DECOMP]: TaskDialog "Clone" / "What do you want to clone along with the track?",
  13595. // six check boxes, the first four ticked; "Grouped tracks" ticked when a group header is selected)
  13596. class CloneTracksWindow final : public juce::AlertWindow
  13597. {
  13598. public:
  13599. explicit CloneTracksWindow (bool groupHeaderSelected)
  13600. : juce::AlertWindow (tr ("Clone"), tr ("What do you want to clone along with the track?"), juce::MessageBoxIconType::QuestionIcon)
  13601. {
  13602. const std::pair<juce::ToggleButton*, const char*> boxes[] = {
  13603. { &patterns, TR_NOOP ("Patterns") }, { &audio, TR_NOOP ("Audio clips") }, { &automations, TR_NOOP ("Automations") },
  13604. { &effects, TR_NOOP ("Effects") }, { &routing, TR_NOOP ("Mixer track routing") }, { &grouped, TR_NOOP ("Grouped tracks") }
  13605. };
  13606. for (const auto& [box, text] : boxes)
  13607. {
  13608. box->setButtonText (tr (text));
  13609. box->setSize (300, 24);
  13610. addCustomComponent (box);
  13611. }
  13612. for (auto* b : { &patterns, &audio, &automations, &effects })
  13613. b->setToggleState (true, juce::dontSendNotification);
  13614. grouped.setToggleState (groupHeaderSelected, juce::dontSendNotification);
  13615. addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  13616. addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  13617. }
  13618. pltracks::CloneOptions options() const
  13619. {
  13620. pltracks::CloneOptions o;
  13621. o.patterns = patterns.getToggleState();
  13622. o.audioClips = audio.getToggleState();
  13623. o.automations = automations.getToggleState();
  13624. o.effects = effects.getToggleState();
  13625. o.routing = routing.getToggleState();
  13626. o.groupedTracks = grouped.getToggleState();
  13627. return o;
  13628. }
  13629. private:
  13630. juce::ToggleButton patterns, audio, automations, effects, routing, grouped;
  13631. };
  13632. } // namespace
  13633. std::unique_ptr<juce::AlertWindow> PlaylistComponent::makeCloneTracksDialog (bool groupHeaderSelected)
  13634. {
  13635. return std::make_unique<CloneTracksWindow> (groupHeaderSelected);
  13636. }
  13637. void PlaylistComponent::cloneTracksWithDialog (std::vector<int> tracks)
  13638. {
  13639. const auto& song = engine.getSong();
  13640. tracks.erase (std::remove_if (tracks.begin(), tracks.end(), [] (int t) { return t < 0; }), tracks.end());
  13641. if (tracks.empty())
  13642. return;
  13643. // FL: at most 250 at once; all empty → "Nothing to clone"
  13644. if (tracks.size() > 250)
  13645. {
  13646. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  13647. tr ("It isn't possible to clone more than {0} playlist tracks at once. Please select fewer tracks and try again.",
  13648. { juce::String (250) }));
  13649. return;
  13650. }
  13651. const auto header = std::any_of (tracks.begin(), tracks.end(), [&song] (int t) { return noteedit::isGroupHeader (song, t); });
  13652. {
  13653. auto probe = song;
  13654. if (pltracks::cloneTracks (probe, tracks, {}) < 0)
  13655. {
  13656. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Nothing to clone"),
  13657. tr ("All selected playlist tracks are empty. Since empty tracks can't be cloned, there is nothing to do."));
  13658. return;
  13659. }
  13660. }
  13661. auto* window = new CloneTracksWindow (header);
  13662. juce::Component::SafePointer<PlaylistComponent> safe (this);
  13663. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, window, tracks] (int result) {
  13664. if (result != 1 || safe == nullptr)
  13665. return;
  13666. const auto options = window->options();
  13667. auto run = [safe, tracks, options] {
  13668. if (safe == nullptr)
  13669. return;
  13670. safe->setSelection ({});
  13671. safe->engine.editSong ([tracks, options] (Song& s) {
  13672. pltracks::cloneTracks (s, pltracks::tracksToClone (s, tracks, options.groupedTracks), options);
  13673. });
  13674. safe->sortClips();
  13675. safe->refreshTrackLayout();
  13676. safe->repaint();
  13677. };
  13678. // FL asks before cloning more than four tracks
  13679. if (tracks.size() > 4)
  13680. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("This may take a while"),
  13681. tr ("Are you sure you want to clone {0} playlist tracks at once? Cloning multiple tracks may take a long time.",
  13682. { juce::String ((int) tracks.size()) }),
  13683. tr ("Yes"), tr ("No"), nullptr,
  13684. juce::ModalCallbackFunction::create ([run] (int r) { if (r != 0) run(); }));
  13685. else
  13686. run();
  13687. }),
  13688. true);
  13689. }
  13690. void PlaylistComponent::mergePatternClipsByKey()
  13691. {
  13692. const auto& song = engine.getSong();
  13693. const auto clips = pltracks::mergeCandidates (song, selection);
  13694. // FUN_01302d30: a selection of nothing but automation clips goes to FL's automation merge
  13695. if (! selection.empty() && std::all_of (selection.begin(), selection.end(), [&song] (int i) {
  13696. return i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::automation;
  13697. }))
  13698. {
  13699. mergeAutomationClipsByKey();
  13700. return;
  13701. }
  13702. // FL merges only pattern clips; a selection of other kinds is refused, an unselected playlist uses its pattern clips
  13703. std::vector<int> patterns;
  13704. for (const auto i : clips)
  13705. if (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::pattern)
  13706. patterns.push_back (i);
  13707. if (! selection.empty() && patterns.size() != clips.size())
  13708. {
  13709. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't merge"),
  13710. tr ("The selection contains different clip types, can't merge."));
  13711. return;
  13712. }
  13713. if (patterns.size() < 2)
  13714. {
  13715. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  13716. tr ("Could not find enough valid pattern clips or instances to merge."));
  13717. return;
  13718. }
  13719. int added = -1;
  13720. setSelection ({});
  13721. engine.editSong ([patterns, &added] (Song& s) { pltracks::mergePatternClips (s, patterns, &added); });
  13722. sortClips();
  13723. }
  13724. void PlaylistComponent::mergeSimilarClipsByKey()
  13725. {
  13726. const auto clips = pltracks::mergeCandidates (engine.getSong(), selection);
  13727. {
  13728. // the same refusal as FUN_012dc060's: fewer than two unmuted pattern clips
  13729. const auto& song = engine.getSong();
  13730. const auto usable = std::count_if (clips.begin(), clips.end(), [&song] (int i) {
  13731. return i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::pattern
  13732. && ! song.playlist[(std::size_t) i].muted;
  13733. });
  13734. if (usable < 2)
  13735. {
  13736. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  13737. tr ("Could not find enough valid pattern clips or instances to merge."));
  13738. return;
  13739. }
  13740. }
  13741. setSelection ({});
  13742. engine.editSong ([clips] (Song& s) { pltracks::mergeSimilarPatternClips (s, clips); });
  13743. sortClips();
  13744. }
  13745. void PlaylistComponent::mergeAutomationClipsByKey()
  13746. {
  13747. const auto chosen = selection;
  13748. const auto check = pltracks::checkAutomationMerge (engine.getSong(), chosen);
  13749. if (check == pltracks::AutomationMergeCheck::tooFew || check == pltracks::AutomationMergeCheck::notAutomation)
  13750. {
  13751. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't merge"),
  13752. check == pltracks::AutomationMergeCheck::tooFew ? tr ("Please select at least two automation clips.")
  13753. : tr ("The selection may only contain automation clips."));
  13754. return;
  13755. }
  13756. juce::Component::SafePointer<PlaylistComponent> safe (this);
  13757. const auto lossy = check != pltracks::AutomationMergeCheck::ok;
  13758. // the clips as they are now: the tool window isn't modal, so a later edit cancels the merge
  13759. std::vector<Clip> before;
  13760. for (const auto i : chosen)
  13761. before.push_back (engine.getSong().playlist[(std::size_t) i]);
  13762. const auto unchanged = [chosen, before] (const Song& song) {
  13763. for (std::size_t k = 0; k < chosen.size(); ++k)
  13764. if (chosen[k] >= (int) song.playlist.size() || ! (song.playlist[(std::size_t) chosen[k]] == before[k]))
  13765. return false;
  13766. return true;
  13767. };
  13768. const auto merge = [safe, chosen, lossy, unchanged] (pltracks::AutomationLinks links) {
  13769. if (safe == nullptr)
  13770. return;
  13771. if (! lossy)
  13772. {
  13773. safe->setSelection ({});
  13774. safe->engine.editSong ([chosen, links] (Song& s) { pltracks::mergeAutomationClips (s, chosen, links); });
  13775. safe->sortClips();
  13776. return;
  13777. }
  13778. // FUN_012ff0d0: FL's events-to-automation tool comes after the questions; Cancel there leaves everything as it was
  13779. auto samples = std::make_shared<PatternEvents> (pltracks::automationMergeSamples (safe->engine.getSong(), chosen));
  13780. openConvertToAutomationPanel ((int) samples->events.size(), 99.8,
  13781. [samples] (float sensitivity) { return (int) eventedit::toAutomationPoints (*samples, sensitivity).size(); },
  13782. [safe, chosen, links, unchanged] (float sensitivity) {
  13783. if (safe == nullptr || ! unchanged (safe->engine.getSong()))
  13784. return;
  13785. safe->setSelection ({});
  13786. safe->engine.editSong ([chosen, links, sensitivity] (Song& s) { pltracks::mergeAutomationClipsLossy (s, chosen, links, sensitivity); });
  13787. safe->sortClips();
  13788. });
  13789. };
  13790. // FL asks about the links last, and only about a real conflict
  13791. const auto askLinks = [safe, chosen, merge] {
  13792. if (safe == nullptr)
  13793. return;
  13794. if (! pltracks::automationLinksConflict (safe->engine.getSong(), chosen))
  13795. {
  13796. merge (pltracks::AutomationLinks::keepFirst);
  13797. return;
  13798. }
  13799. auto* window = new juce::AlertWindow (tr ("Target links conflict"),
  13800. tr ("The clips in the selection aren't all linked to the same parameters, what do you want to do?"),
  13801. juce::MessageBoxIconType::QuestionIcon);
  13802. window->addButton (tr ("Keep links of the first selected clip"), 1);
  13803. window->addButton (tr ("Merge all links"), 2);
  13804. window->addButton (tr ("Delete all links"), 3, juce::KeyPress (juce::KeyPress::returnKey)); // FL's default button
  13805. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  13806. window->enterModalState (true, juce::ModalCallbackFunction::create ([merge] (int result) {
  13807. if (result == 1) merge (pltracks::AutomationLinks::keepFirst);
  13808. else if (result == 2) merge (pltracks::AutomationLinks::mergeAll);
  13809. else if (result == 3) merge (pltracks::AutomationLinks::deleteAll);
  13810. }),
  13811. true);
  13812. };
  13813. if (! lossy)
  13814. {
  13815. askLinks();
  13816. return;
  13817. }
  13818. juce::AlertWindow::showYesNoCancelBox (
  13819. juce::MessageBoxIconType::QuestionIcon, tr ("Can't perform lossless merge"),
  13820. check == pltracks::AutomationMergeCheck::overlapping
  13821. ? tr ("The selection contains overlapping clips. Perform lossy merge?")
  13822. : tr ("The selection contains at least one clip that doesn't have control points at both the start and end of its region. Perform lossy merge?"),
  13823. tr ("Yes"), tr ("No"), {}, nullptr,
  13824. juce::ModalCallbackFunction::create ([askLinks] (int result) { if (result == 1) askLinks(); }));
  13825. }
  13826. void PlaylistComponent::makeSelectionUnique()
  13827. {
  13828. if (selection.empty())
  13829. return;
  13830. auto run = [this, chosen = selection] {
  13831. engine.editSong ([chosen] (Song& s) {
  13832. std::vector<int> patterns, audio;
  13833. for (const auto i : chosen)
  13834. if (i >= 0 && i < (int) s.playlist.size())
  13835. {
  13836. const auto kind = s.playlist[(std::size_t) i].kind;
  13837. (kind == ClipKind::audio ? audio : patterns).push_back (i);
  13838. }
  13839. polish::makeClipsUnique (s, patterns);
  13840. // each audio source of the selection gets its own channel copy
  13841. std::vector<int> channels;
  13842. for (const auto i : audio)
  13843. if (const auto ch = s.playlist[(std::size_t) i].channel; std::find (channels.begin(), channels.end(), ch) == channels.end())
  13844. channels.push_back (ch);
  13845. for (const auto ch : channels)
  13846. {
  13847. std::vector<int> group;
  13848. for (const auto i : audio)
  13849. if (s.playlist[(std::size_t) i].channel == ch)
  13850. group.push_back (i);
  13851. clipops::makeAudioUnique (s, group);
  13852. }
  13853. });
  13854. };
  13855. // FL (FUN_0123d640): asks from 20 selected clips on
  13856. if (selection.size() >= 20)
  13857. {
  13858. juce::Component::SafePointer<PlaylistComponent> safe (this);
  13859. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("Make all selected clips unique?"),
  13860. tr ("Are you sure you want to make all {0} selected clips unique?", { juce::String ((int) selection.size()) }),
  13861. tr ("Yes"), tr ("No"), nullptr,
  13862. juce::ModalCallbackFunction::create ([safe, run] (int r) { if (r != 0 && safe != nullptr) run(); }));
  13863. return;
  13864. }
  13865. run();
  13866. }
  13867. namespace
  13868. {
  13869. // "Make unique as sample" off the message thread (round 190ri: 628 clips wrote for almost three minutes with the window frozen):
  13870. // progress and Cancel; the song changes in one undo step at the end, and not at all when cancelled
  13871. class UniqueSampleThread final : public juce::ThreadWithProgressWindow
  13872. {
  13873. public:
  13874. UniqueSampleThread (AudioEngine& e, uniquesamples::Plan p)
  13875. : juce::ThreadWithProgressWindow (tr ("Make unique as sample"), true, true), engine (e), plan (std::move (p))
  13876. {
  13877. setStatusMessage (tr ("{0} clips", { juce::String ((int) plan.parts.size()) }));
  13878. }
  13879. void run() override
  13880. {
  13881. ok = uniquesamples::render (plan, [this] (double p) {
  13882. setProgress (p);
  13883. return ! threadShouldExit();
  13884. });
  13885. }
  13886. void threadComplete (bool) override
  13887. {
  13888. if (ok)
  13889. finish (engine, plan);
  13890. juce::MessageManager::callAsync ([this] { delete this; });
  13891. }
  13892. static void finish (AudioEngine& e, const uniquesamples::Plan& p)
  13893. {
  13894. for (const auto& part : p.parts)
  13895. if (part.written)
  13896. e.getSampleLibrary().forget (part.file.getFullPathName()); // (a file that was replaced)
  13897. if (std::any_of (p.parts.begin(), p.parts.end(), [] (const uniquesamples::Part& part) { return part.written; }))
  13898. e.editSong ([&p] (Song& s) { uniquesamples::apply (s, p); });
  13899. }
  13900. private:
  13901. AudioEngine& engine;
  13902. uniquesamples::Plan plan;
  13903. bool ok = false;
  13904. };
  13905. } // namespace
  13906. void PlaylistComponent::makeSelectionUniqueAsSample()
  13907. {
  13908. // FL's Edit › Make unique as sample (EEMakeUniqueAsSampleAction, Tag 1 of FUN_0123d640 -> FUN_0123dc00): every selected
  13909. // audio clip, one file each, with no file dialog (engine/UniqueSamples.h; live check round 190ri). The clip's own pitch,
  13910. // stretch and reverse are rendered into the file and reset on the clip (round 189l), so it sounds the same.
  13911. makeUniqueAsSample (selection, {});
  13912. }
  13913. void PlaylistComponent::makeUniqueAsSample (const std::vector<int>& clips, const juce::File& file)
  13914. {
  13915. auto plan = uniquesamples::makePlan (engine.getSong(), engine.getTransport().sampleRate.load(), clips);
  13916. if (plan.parts.empty())
  13917. return;
  13918. if (plan.parts.size() == 1)
  13919. plan.parts.front().file = file;
  13920. std::int64_t ticks = 0;
  13921. for (const auto& p : plan.parts)
  13922. ticks += p.was.length;
  13923. if (plan.parts.size() <= 4 && (double) ticks * 60.0 / (juce::jmax (1.0, plan.song.bpm) * ppq) < 20.0) // (a moment: no window)
  13924. {
  13925. if (uniquesamples::render (plan, [] (double) { return true; }))
  13926. UniqueSampleThread::finish (engine, plan);
  13927. return;
  13928. }
  13929. (new UniqueSampleThread (engine, std::move (plan)))->launchThread();
  13930. }
  13931. void PlaylistComponent::makeClipUniqueAsSampleAsked (int clip, bool ask)
  13932. {
  13933. // the clip menu's item (FL 2026 live, round 190ri): the clicked clip alone, its file asked for ("Save sample selection",
  13934. // the next "<sample> - Part_<n>" offered); Shift skips the question (FL's manual)
  13935. const auto plan = uniquesamples::makePlan (engine.getSong(), engine.getTransport().sampleRate.load(), { clip });
  13936. if (plan.parts.empty())
  13937. return;
  13938. if (! ask)
  13939. return makeUniqueAsSample ({ clip }, {});
  13940. const auto& p = plan.parts.front();
  13941. int n = 1;
  13942. fileChooser = ui::makeFileChooser (tr ("Save sample selection"), uniquesamples::nextFree (p.folder, uniquesamples::baseName (p.source), n), "*.wav");
  13943. ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  13944. [safe = juce::Component::SafePointer<PlaylistComponent> (this), clip, was = p.was] (const juce::FileChooser& fc) {
  13945. const auto file = fc.getResult();
  13946. if (safe == nullptr || file == juce::File() || clip >= (int) safe->engine.getSong().playlist.size())
  13947. return;
  13948. const auto& now = safe->engine.getSong().playlist[(std::size_t) clip];
  13949. if (now.kind == was.kind && now.channel == was.channel && now.start == was.start && now.track == was.track)
  13950. safe->makeUniqueAsSample ({ clip }, file.hasFileExtension ("wav") ? file : file.withFileExtension ("wav"));
  13951. });
  13952. }
  13953. void PlaylistComponent::lockAllTracks (bool lock)
  13954. {
  13955. // FL (FUN_011c2190): "Resize tracks?|Also resize all playlist tracks to their minimum / default size?" Yes / No / Cancel
  13956. juce::Component::SafePointer<PlaylistComponent> safe (this);
  13957. juce::AlertWindow::showYesNoCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("Resize tracks?"),
  13958. lock ? tr ("Also resize all playlist tracks to their minimum size?")
  13959. : tr ("Also resize all playlist tracks to their default size?"),
  13960. tr ("Yes"), tr ("No"), tr ("Cancel"), nullptr,
  13961. juce::ModalCallbackFunction::create ([safe, lock] (int result) {
  13962. if (result == 0 || safe == nullptr) // 1 = yes, 2 = no, 0 = cancel
  13963. return;
  13964. const auto count = safe->numTracks();
  13965. safe->engine.editSong ([count, lock, resize = result == 1] (Song& s) { pltracks::lockAll (s, count, lock, resize); });
  13966. safe->refreshTrackLayout();
  13967. safe->updateScrollBars();
  13968. safe->repaint();
  13969. }));
  13970. }
  13971. void PlaylistComponent::resetEmptyTracksAsked()
  13972. {
  13973. juce::Component::SafePointer<PlaylistComponent> safe (this);
  13974. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("Reset empty tracks?"),
  13975. tr ("Reset all empty playlist tracks in the current arrangement?"), tr ("OK"), tr ("Cancel"), nullptr,
  13976. juce::ModalCallbackFunction::create ([safe] (int result) {
  13977. if (result == 0 || safe == nullptr)
  13978. return;
  13979. safe->engine.editSong ([] (Song& s) { pltracks::resetEmptyTracks (s); });
  13980. safe->refreshTrackLayout();
  13981. safe->repaint();
  13982. }));
  13983. }
  13984. void PlaylistComponent::setStretchOnResize (bool on)
  13985. {
  13986. EditorGlobals::get().stretchOnResize = on;
  13987. stretchButton.setToggleState (on, juce::dontSendNotification);
  13988. ui::postHint ({ tr ("Stretch audio when resizing audio clips"), on ? tr ("On") : tr ("Off"), false, false });
  13989. repaint();
  13990. }
  13991. std::int64_t PlaylistComponent::songPositionTick() const
  13992. {
  13993. return (std::int64_t) engine.songPlayheadTicks();
  13994. }
  13995. void PlaylistComponent::addMarkerByKey()
  13996. {
  13997. // FL (FUN_01229d20): the song position when it is in view, else the bar line nearest the view's left edge; the
  13998. // time selection's start wins over both. Then the name dialog.
  13999. const auto& song = engine.getSong();
  14000. const auto left = (std::int64_t) std::max (0.0, scrollTicks);
  14001. const auto right = (std::int64_t) (scrollTicks + gridArea().getWidth() / pixelsPerTick);
  14002. auto tick = songPositionTick();
  14003. if (tick < left || tick > right)
  14004. {
  14005. const auto bar = song.barAt (left);
  14006. tick = left - bar.tick > bar.length / 2 ? bar.tick + bar.length : bar.tick;
  14007. }
  14008. if (song.hasLoop())
  14009. tick = song.loopStart;
  14010. editMarkerName (tick, -1);
  14011. }
  14012. void PlaylistComponent::addAutoMarker()
  14013. {
  14014. // FL (FUN_00e546a0 with FUN_00e43fa0 (snap)): the song position on the grid
  14015. const auto tick = snap ((double) songPositionTick(), true);
  14016. for (const auto& m : engine.getSong().markers())
  14017. if (m.tick == tick)
  14018. return; // FL keeps the marker that is there (and no undo step)
  14019. engine.editSong ([tick] (Song& s) { markers::addAuto (s, tick); });
  14020. }
  14021. void PlaylistComponent::addSignatureChangeByKey()
  14022. {
  14023. // FL (FUN_0122bd20): the time selection (start, and its end gets the old signature back), else the song position
  14024. const auto& song = engine.getSong();
  14025. const auto from = song.hasLoop() ? song.loopStart : snap ((double) songPositionTick(), true);
  14026. const auto to = song.hasLoop() ? song.loopEnd : (std::int64_t) -1;
  14027. const auto current = markers::signatureAt (song, from);
  14028. auto* window = new juce::AlertWindow (tr ("Add time signature change..."), {}, juce::MessageBoxIconType::NoIcon, this);
  14029. juce::StringArray numerators, denominators;
  14030. for (int n = 1; n <= 32; ++n)
  14031. numerators.add (juce::String (n));
  14032. for (int d : { 1, 2, 4, 8, 16, 32 })
  14033. denominators.add (juce::String (d));
  14034. window->addComboBox ("numerator", numerators, tr ("Numerator"));
  14035. window->addComboBox ("denominator", denominators, tr ("Denominator"));
  14036. window->getComboBoxComponent ("numerator")->setText (juce::String (current.first), juce::dontSendNotification);
  14037. window->getComboBoxComponent ("denominator")->setText (juce::String (current.second), juce::dontSendNotification);
  14038. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  14039. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  14040. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, from, to, window] (int result) {
  14041. if (result != 1)
  14042. return;
  14043. const auto n = window->getComboBoxComponent ("numerator")->getText().getIntValue();
  14044. const auto d = window->getComboBoxComponent ("denominator")->getText().getIntValue();
  14045. engine.editSong ([from, to, n, d] (Song& s) { markers::addSignatureChange (s, from, to, n, d); });
  14046. }),
  14047. true);
  14048. }
  14049. void PlaylistComponent::selectTimeAroundSelection()
  14050. {
  14051. // FL (FUN_00eb1b90 → FUN_00e4ea50): the time selection spans the selected clips, or the view when none is
  14052. // selected; the same span again clears it
  14053. const auto& song = engine.getSong();
  14054. std::int64_t from = -1, to = -1;
  14055. for (auto i : selection)
  14056. if (i >= 0 && i < (int) song.playlist.size())
  14057. {
  14058. const auto& c = song.playlist[(std::size_t) i];
  14059. from = from < 0 ? c.start : std::min (from, c.start);
  14060. to = std::max (to, c.end());
  14061. }
  14062. if (from < 0)
  14063. {
  14064. from = (std::int64_t) std::llround (std::max (0.0, scrollTicks));
  14065. to = (std::int64_t) std::llround (std::max (0.0, scrollTicks) + gridArea().getWidth() / pixelsPerTick);
  14066. }
  14067. const auto same = song.hasLoop() && song.loopStart == from && song.loopEnd == to;
  14068. engine.editSong ([from, to, same] (Song& s) {
  14069. s.loopStart = same ? 0 : from;
  14070. s.loopEnd = same ? 0 : to;
  14071. }, false);
  14072. repaint();
  14073. }
  14074. void PlaylistComponent::moveTimeSelection (int direction)
  14075. {
  14076. // FL (FUN_00e43ea0, the action's Tag ±1): the time selection moves by its own length (not before the song's
  14077. // start) and the song position goes to its start
  14078. const auto& song = engine.getSong();
  14079. if (! song.hasLoop())
  14080. return;
  14081. const auto length = song.loopEnd - song.loopStart;
  14082. const auto from = song.loopStart + direction * length;
  14083. const auto songMode = song.mode == PlayMode::song;
  14084. if (from < 0)
  14085. return;
  14086. engine.editSong ([from, length] (Song& s) {
  14087. s.loopStart = from;
  14088. s.loopEnd = from + length;
  14089. }, false);
  14090. if (! songMode)
  14091. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  14092. engine.jumpTo ((double) from);
  14093. playheadTick = (double) from;
  14094. // keep it in view
  14095. const auto visible = gridArea().getWidth() / pixelsPerTick;
  14096. if ((double) from < scrollTicks || (double) (from + length) > scrollTicks + visible)
  14097. {
  14098. scrollTicks = std::max (0.0, (double) from - visible * 0.1);
  14099. updateScrollBars();
  14100. }
  14101. repaint();
  14102. }
  14103. // round 190on (research190oe P8, core/TransientNav.h): Tab to transient. The song position (or, with `extend`, the time
  14104. // selection's edge) goes to the next / previous attack of the selected audio clips (none selected: of every audio clip);
  14105. // a clip with no attack stops at its edges. The attacks are found once per sample (clipwarp::attacks, the audio editor's).
  14106. std::vector<double> PlaylistComponent::clipAttacks (int index)
  14107. {
  14108. const auto& song = engine.getSong();
  14109. if (index < 0 || index >= (int) song.playlist.size())
  14110. return {};
  14111. const auto& clip = song.playlist[(std::size_t) index];
  14112. if (clip.channel < 0 || clip.channel >= (int) song.channels.size())
  14113. return {};
  14114. const auto path = juce::String::fromUTF8 (song.channels[(std::size_t) clip.channel].samplePath.c_str());
  14115. const auto sample = engine.getSampleLibrary().load (path);
  14116. if (sample == nullptr)
  14117. return {};
  14118. auto& cached = transientCache[path.toStdString()];
  14119. if (cached.first.lock() != sample)
  14120. cached = { sample, clipwarp::attacks (*sample) };
  14121. return cached.second;
  14122. }
  14123. bool PlaylistComponent::moveToTransient (int direction, bool extend)
  14124. {
  14125. const auto& song = engine.getSong();
  14126. std::vector<int> clips;
  14127. for (const auto i : selection)
  14128. if (i >= 0 && i < (int) song.playlist.size() && song.playlist[(std::size_t) i].kind == ClipKind::audio)
  14129. clips.push_back (i);
  14130. if (clips.empty())
  14131. for (int i = 0; i < (int) song.playlist.size(); ++i)
  14132. if (song.playlist[(std::size_t) i].kind == ClipKind::audio)
  14133. clips.push_back (i);
  14134. const auto stops = transientnav::stops (song, clips, [this] (int i) { return clipAttacks (i); });
  14135. if (stops.empty())
  14136. {
  14137. ui::postHint ({ tr ("No audio clip to go through: transients are found in audio clips"), {}, false, false }, 3000);
  14138. return false;
  14139. }
  14140. // (stopped: the position this view shows — a jump reaches the engine's transport with its next audio block)
  14141. const auto playing = engine.getTransport().playing.load();
  14142. const auto position = (std::int64_t) std::llround (std::max (0.0, ! playing && playheadTick >= 0.0 ? playheadTick : engine.songPlayheadTicks()));
  14143. std::int64_t shown = position;
  14144. if (extend)
  14145. {
  14146. const transientnav::Range now = song.hasLoop() ? transientnav::Range { song.loopStart, song.loopEnd } : transientnav::Range {};
  14147. const auto next = transientnav::extend (now, position, stops, direction);
  14148. if (next == now)
  14149. return true;
  14150. engine.editSong ([next] (Song& s) {
  14151. s.loopStart = next.from;
  14152. s.loopEnd = next.to;
  14153. s.mode = PlayMode::song;
  14154. }, false);
  14155. shown = direction > 0 ? next.to : next.from;
  14156. }
  14157. else
  14158. {
  14159. const auto to = transientnav::step (stops, position, direction);
  14160. if (! to)
  14161. return true;
  14162. if (song.mode != PlayMode::song)
  14163. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  14164. engine.jumpTo ((double) *to);
  14165. playheadTick = (double) *to;
  14166. shown = *to;
  14167. }
  14168. // keep it in view
  14169. const auto visible = gridArea().getWidth() / pixelsPerTick;
  14170. if ((double) shown < scrollTicks || (double) shown > scrollTicks + visible)
  14171. {
  14172. scrollTicks = std::max (0.0, (double) shown - visible * 0.25);
  14173. updateScrollBars();
  14174. }
  14175. repaint();
  14176. return true;
  14177. }
  14178. void PlaylistComponent::placeLoopMarker()
  14179. {
  14180. // FL (FUN_0122bb80): the bar line nearest the view's left edge, or the time selection's start
  14181. const auto& song = engine.getSong();
  14182. const auto left = (std::int64_t) std::max (0.0, scrollTicks);
  14183. const auto bar = song.barAt (left);
  14184. auto tick = left - bar.tick > bar.length / 2 ? bar.tick + bar.length : bar.tick;
  14185. if (song.hasLoop())
  14186. tick = song.loopStart;
  14187. engine.editSong ([tick] (Song& s) { markers::placeSongLoop (s, tick); });
  14188. }
  14189. void PlaylistComponent::pitchSelectedAudioClips (int semitones)
  14190. {
  14191. // FL (FUN_00e2d7b0): only the selected clips that are audio clips; nothing selected, nothing changes
  14192. const auto targets = selection;
  14193. engine.editSong ([targets, semitones] (Song& s) { clipops::pitchAudioClips (s, targets, semitones); });
  14194. repaint();
  14195. }
  14196. void PlaylistComponent::reverseSelectedAudioClips()
  14197. {
  14198. const auto targets = selection;
  14199. // each clip's file length in ticks at its own speed, read here (the sample library is not for the edit lambda)
  14200. std::vector<std::int64_t> ticks;
  14201. {
  14202. const auto& song = engine.getSong();
  14203. for (auto i : targets)
  14204. {
  14205. std::int64_t t = 0;
  14206. if (i >= 0 && i < (int) song.playlist.size())
  14207. if (const auto& c = song.playlist[(std::size_t) i]; c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  14208. {
  14209. const auto& channel = song.channels[(std::size_t) c.channel];
  14210. if (const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str())); sample != nullptr)
  14211. t = clipops::fileTicks (channel, c, (double) clipops::clipSpan (channel, sample).frames, sample->sampleRate, song.bpm);
  14212. }
  14213. ticks.push_back (t);
  14214. }
  14215. }
  14216. engine.editSong ([targets, ticks] (Song& s) {
  14217. clipops::reverseAudioClips (s, targets, [&] (int clip) {
  14218. for (std::size_t k = 0; k < targets.size(); ++k)
  14219. if (targets[k] == clip)
  14220. return ticks[k];
  14221. return (std::int64_t) 0;
  14222. });
  14223. });
  14224. repaint();
  14225. }
  14226. void PlaylistComponent::quantizeClips (double strength)
  14227. {
  14228. std::vector<int> targets = selection;
  14229. if (targets.empty())
  14230. for (int i = 0; i < (int) engine.getSong().playlist.size(); ++i)
  14231. targets.push_back (i);
  14232. if (targets.empty())
  14233. return;
  14234. const auto grid = gridTicks();
  14235. engine.editSong ([&targets, grid, strength] (Song& s) { transportedit::quantizeClipStarts (s.playlist, targets, grid, strength); });
  14236. sortClips();
  14237. }
  14238. void PlaylistComponent::deleteSelection()
  14239. {
  14240. if (selection.empty())
  14241. return;
  14242. auto doomed = selection;
  14243. fadeOut (doomed); // (issue #250)
  14244. setSelection ({});
  14245. engine.editSong ([&doomed] (Song& s) {
  14246. std::sort (doomed.rbegin(), doomed.rend());
  14247. for (auto i : doomed)
  14248. if (i >= 0 && i < (int) s.playlist.size())
  14249. s.playlist.erase (s.playlist.begin() + i);
  14250. });
  14251. }
  14252. void PlaylistComponent::copySelection()
  14253. {
  14254. // round 190rw (Q1): FL 2026 keeps its clipboard when Ctrl+C finds nothing selected (checked live: Ctrl+C, Ctrl+D,
  14255. // Ctrl+C, Ctrl+V pastes the first copy); LYNX's key emptied it
  14256. if (selection.empty())
  14257. return;
  14258. clipboard.clear();
  14259. ++clipboardStamp;
  14260. rangeClipboardNewest() = false; // (round 190pa: Ctrl+V pastes clips again)
  14261. for (auto i : selection)
  14262. clipboard.push_back (engine.getSong().playlist[(std::size_t) i]);
  14263. // round 190ne: the track clips travel with the clipboard (a cut deletes a track clip with its last clip)
  14264. clipboardPatterns = trackclips::carry (engine.getSong(), clipboard);
  14265. publishCopiedClips (engine); // (issue #232: and to another LYNX SHARE window)
  14266. }
  14267. void PlaylistComponent::publishCopiedClips (AudioEngine& engine)
  14268. {
  14269. if (! windowclip::enabled() || clipboard.empty())
  14270. return;
  14271. crossclipboard::Payload copy;
  14272. copy.kind = crossclipboard::Kind::clips;
  14273. std::vector<int> sources;
  14274. copy.fragment = crosspaste::clipsFragment (engine.getSong(), clipboard, clipboardPatterns, &sources);
  14275. for (std::size_t i = 0; i < sources.size() && i < copy.fragment.channels.size(); ++i)
  14276. windowclip::captureChannel (engine, sources[i], copy.fragment.channels[i]);
  14277. windowclip::publish (std::move (copy));
  14278. }
  14279. bool PlaylistComponent::canPasteClips()
  14280. {
  14281. return ! clipboard.empty() || windowclip::hasIncoming (crossclipboard::Kind::clips);
  14282. }
  14283. void PlaylistComponent::pasteClips (std::int64_t at)
  14284. {
  14285. // issue #232 (round 190nz): clips copied in another LYNX SHARE window come with what they play (core/CrossPaste.h)
  14286. const auto incoming = windowclip::incoming (crossclipboard::Kind::clips);
  14287. const auto& source = incoming ? incoming->fragment.playlist : clipboard;
  14288. if (source.empty())
  14289. return;
  14290. // pastes at `at` (the clip menu's "Paste here"), else where the layout puts it (issue #211, round 190mq,
  14291. // core/PastePlace.h: FL's rule in the Pattern layout, Live's insert marker in Clip-launch, the playhead in Simple),
  14292. // keeping tracks and spacing
  14293. const auto& song = engine.getSong();
  14294. pasteplace::Where w;
  14295. w.first = source.front().start;
  14296. for (const auto& c : source)
  14297. w.first = juce::jmin (w.first, c.start);
  14298. w.viewFrom = (std::int64_t) std::max (0.0, scrollTicks);
  14299. w.viewTo = (std::int64_t) xToTick (gridArea().getRight());
  14300. if (song.hasLoop())
  14301. w.selection = song.loopStart;
  14302. w.rulerMark = rulerMark;
  14303. w.grid = gridTicks();
  14304. w.position = snap ((double) songPositionTick(), true); // (Live's insert marker / BandLab's playhead)
  14305. const auto first = w.first;
  14306. const auto target = at >= 0 ? at
  14307. : pasteplace::start (pasteplace::ruleFor (layoutstyle::current()), w, [&song] (std::int64_t tick) {
  14308. const auto bar = song.barAt (tick);
  14309. return pasteplace::Bar { bar.tick, juce::jmax<std::int64_t> (1, bar.length) };
  14310. });
  14311. std::vector<int> added;
  14312. engine.editSong ([&added, &incoming, target, first] (Song& s) {
  14313. std::vector<Clip> pasted;
  14314. if (incoming)
  14315. pasted = crosspaste::importClips (s, incoming->fragment); // (one undo step with the paste)
  14316. else
  14317. {
  14318. pasted = clipboard;
  14319. trackclips::materialize (s, pasted, clipboardPatterns); // (round 190ne: a pasted track clip is a unique copy)
  14320. }
  14321. for (auto c : pasted)
  14322. {
  14323. if (c.kind == ClipKind::pattern && c.pattern >= (int) s.patterns.size())
  14324. continue;
  14325. if (c.kind == ClipKind::audio && c.channel >= (int) s.channels.size())
  14326. continue;
  14327. if (c.kind == ClipKind::automation && c.automation >= (int) s.automations.size())
  14328. continue;
  14329. c.start = c.start - first + target;
  14330. added.push_back ((int) s.playlist.size());
  14331. s.playlist.push_back (c);
  14332. }
  14333. });
  14334. setSelection (added);
  14335. sortClips (added);
  14336. if (incoming)
  14337. ui::postHint ({ windowclip::pastedFrom (*incoming) }, 2500);
  14338. }
  14339. void PlaylistComponent::duplicateSelection (bool linked)
  14340. {
  14341. const auto& song = engine.getSong();
  14342. // with a time selection: repeats it right after itself (the selected clips that start inside it, or
  14343. // all the clips that do), and the time selection moves on so the next Ctrl+B continues
  14344. if (song.hasLoop())
  14345. {
  14346. const auto from = song.loopStart, to = song.loopEnd;
  14347. std::vector<int> sources;
  14348. for (auto i : selection)
  14349. if (song.playlist[(std::size_t) i].start >= from && song.playlist[(std::size_t) i].start < to)
  14350. sources.push_back (i);
  14351. std::vector<int> added;
  14352. engine.editSong ([&] (Song& s) {
  14353. added = noteedit::repeatTime (s.playlist, from, to, sources);
  14354. if (! linked) // (round 190ne: copies of track clips are unique unless asked for linked ones)
  14355. trackclips::makeCopiesUnique (s, added);
  14356. s.loopStart = to;
  14357. s.loopEnd = to + (to - from);
  14358. });
  14359. setSelection (added);
  14360. sortClips (added);
  14361. return;
  14362. }
  14363. if (selection.empty())
  14364. return;
  14365. const auto bar = song.barTicks();
  14366. std::int64_t from = INT64_MAX, to = 0;
  14367. for (auto i : selection)
  14368. {
  14369. from = juce::jmin (from, song.playlist[(std::size_t) i].start);
  14370. to = juce::jmax (to, song.playlist[(std::size_t) i].end());
  14371. }
  14372. const auto offset = juce::jmax (bar, (to - from + bar - 1) / bar * bar); // like FL's Ctrl+B
  14373. const auto source = selection;
  14374. std::vector<int> added;
  14375. engine.editSong ([&added, &source, offset, linked] (Song& s) {
  14376. for (auto i : source)
  14377. {
  14378. auto c = s.playlist[(std::size_t) i];
  14379. c.start += offset;
  14380. added.push_back ((int) s.playlist.size());
  14381. s.playlist.push_back (c);
  14382. }
  14383. if (! linked) // (round 190ne: copies of track clips are unique unless asked for linked ones)
  14384. trackclips::makeCopiesUnique (s, added);
  14385. });
  14386. setSelection (added);
  14387. sortClips (added);
  14388. }
  14389. bool PlaylistComponent::keyForTests (const juce::KeyPress& key)
  14390. {
  14391. if (handleKey (key))
  14392. return true;
  14393. static const keys::KeyMap defaults;
  14394. const auto id = defaults.find (chordFromKeyPress (key), keys::Context::playlist, false);
  14395. return ! id.empty() && runAction (id);
  14396. }
  14397. bool PlaylistComponent::handleKey (const juce::KeyPress& key)
  14398. {
  14399. // round 190im (R15): a key that changed the song is an edit by hand: Follow pauses (when that option is on)
  14400. const juce::ScopeGuard followEdit { [this, before = engine.getPublishCount()] {
  14401. EditorGlobals::get().pauseFollowIfEdited (EditorGlobals::FollowView::playlist, before, engine.getPublishCount());
  14402. } };
  14403. const auto mods = key.getModifiers();
  14404. const auto cmd = mods.isCommandDown();
  14405. const auto code = key.getKeyCode();
  14406. const auto letter = keys::letterOfKeyCode (code); // (0 for F-keys, numpad, arrows: issue #12)
  14407. if (pointKeyPressed (key)) // issue #207 (round 190lw): Delete / Esc / Ctrl+C / X / V on selected points
  14408. return true;
  14409. if (rangeKeyPressed (key)) // round 190pa (P14): the keys of a range on chosen tracks (only while there is one)
  14410. return true;
  14411. // (issue #219, round 190ng: Backspace's snap on / off is the key map's playlist.snapToggle / pianoRoll.snapToggle now, so it
  14412. // can be given another key)
  14413. // round 190im (R12): Live's Split (Ctrl+E), only in the Clip-launch layout (core/SessionKeys.h; elsewhere Ctrl+E
  14414. // stays FL's Step edit): the selected clips are cut at the time selection's edges, or at the playhead without one
  14415. if (cmd && ! mods.isShiftDown() && ! mods.isAltDown() && letter == 'E' && sessionkeys::defaultKeyActs (sessionkeys::Command::splitClips)
  14416. && ! selection.empty())
  14417. {
  14418. splitSelectionForLive();
  14419. return true;
  14420. }
  14421. // Ctrl+Ins / Ctrl+Del: insert / remove the time selection's length across all tracks
  14422. if (cmd && ! mods.isShiftDown() && ! mods.isAltDown() && code == juce::KeyPress::insertKey) // (Ctrl+Shift+Ins: pattern.insert; Ctrl+Alt+Ins: playlist.sliceInsertSpace)
  14423. {
  14424. insertTimeSelection();
  14425. return true;
  14426. }
  14427. if (cmd && ! mods.isShiftDown() && code == juce::KeyPress::deleteKey) // (Ctrl+Shift+Del: pattern.delete)
  14428. {
  14429. deleteTimeSelection();
  14430. return true;
  14431. }
  14432. // Live (manual 9.x Audio Clip Fades, details DL-67, round 190ld): Delete over a fade handle returns that fade to its
  14433. // 4 ms default, in the Clip-launch layout only (elsewhere Delete deletes as FL's)
  14434. if (code == juce::KeyPress::deleteKey && ! mods.isAnyModifierKeyDown() && layoutstyle::current() == layoutstyle::Style::clipLaunch
  14435. && (hover.fade == 1 || hover.fade == 2) && hover.clip >= 0 && hover.clip < (int) engine.getSong().playlist.size()
  14436. && engine.getSong().playlist[(std::size_t) hover.clip].kind == ClipKind::audio)
  14437. {
  14438. const auto ticks = juce::jmax<std::int64_t> (1, juce::roundToInt (0.004 * juce::jmax (1.0, engine.getSong().bpm) / 60.0 * (double) ppq));
  14439. engine.editSong ([index = hover.clip, in = hover.fade == 1, ticks] (Song& s) {
  14440. auto& c = s.playlist[(std::size_t) index];
  14441. (in ? c.fadeIn : c.fadeOut) = juce::jmin (ticks, c.length);
  14442. });
  14443. repaint();
  14444. return true;
  14445. }
  14446. if (code == juce::KeyPress::deleteKey && ! mods.isShiftDown())
  14447. {
  14448. if (ripple)
  14449. rippleDeleteSelection();
  14450. else
  14451. deleteSelection();
  14452. return true;
  14453. }
  14454. if (code == juce::KeyPress::escapeKey)
  14455. {
  14456. // (issue #217, round 190ng: an Esc with nothing selected is left to the main window, which closes the Playlist as FL)
  14457. if (selection.empty())
  14458. return false;
  14459. setSelection ({});
  14460. return true;
  14461. }
  14462. // (issue #327, round 190sj: Ctrl+A / C / X / V / B are the key map's playlist.selectAll / copy / cut / paste / duplicate now;
  14463. // Ctrl+Alt+B is playlist.duplicateLinked)
  14464. // (the tool letters are key map actions now: runKeyAction, issue #12)
  14465. return false;
  14466. }
  14467. bool PlaylistComponent::runKeyAction (const std::string& id)
  14468. {
  14469. for (const auto& t : editTools())
  14470. if (t.tool != EditTool::drumPaint && id == "playlist.tool." + std::string (editToolId (t.tool)))
  14471. {
  14472. tools.setTool (t.tool);
  14473. return true;
  14474. }
  14475. return false;
  14476. }
  14477. void PlaylistComponent::refreshToolKeys (const std::function<juce::String (const std::string&)>& keyOf)
  14478. {
  14479. tools.refreshKeys ([&keyOf] (EditTool t) { return keyOf ("playlist.tool." + std::string (editToolId (t))); });
  14480. }
  14481. void PlaylistComponent::mouseMove (const juce::MouseEvent& e)
  14482. {
  14483. updateHover (e.getPosition(), e.mods);
  14484. feedMagicLasso (e.getPosition(), false);
  14485. }
  14486. void PlaylistComponent::feedMagicLasso (juce::Point<int> p, bool buttonDown)
  14487. {
  14488. if (! EditorGlobals::get().magicLasso)
  14489. return;
  14490. const auto grid = gridArea();
  14491. // (FL clamps the point into the clip area, FUN_00e6f840)
  14492. const auto at = grid.getConstrainedPoint (p);
  14493. const auto loop = lassoPath.move ({ (double) at.x, (double) at.y }, juce::Time::getMillisecondCounter(), buttonDown || ! grid.contains (p));
  14494. if (loop.empty())
  14495. return;
  14496. const auto& song = engine.getSong();
  14497. std::vector<int> enclosed;
  14498. std::vector<bool> enclosedSelected;
  14499. for (int i = 0; i < (int) song.playlist.size(); ++i)
  14500. {
  14501. const auto r = clipBounds (i);
  14502. if (! r.intersects (grid) || song.playlist[(std::size_t) i].gridSlot >= 0)
  14503. continue;
  14504. if (magiclasso::rectInsidePolygon (loop, magiclasso::innerRect ({ (double) r.getX(), (double) r.getY(), (double) r.getRight(), (double) r.getBottom() })))
  14505. {
  14506. enclosed.push_back (i);
  14507. enclosedSelected.push_back (std::find (selection.begin(), selection.end(), i) != selection.end());
  14508. }
  14509. }
  14510. const auto shift = juce::ModifierKeys::currentModifiers.isShiftDown();
  14511. switch (magiclasso::decide (enclosed, shift, (int) selection.size(), enclosedSelected))
  14512. {
  14513. case magiclasso::Result::select:
  14514. {
  14515. auto chosen = selection;
  14516. for (auto i : enclosed)
  14517. if (std::find (chosen.begin(), chosen.end(), i) == chosen.end())
  14518. chosen.push_back (i);
  14519. setSelection (chosen);
  14520. lassoPath.clear();
  14521. break;
  14522. }
  14523. case magiclasso::Result::zoomToSelection:
  14524. {
  14525. std::int64_t from = std::numeric_limits<std::int64_t>::max(), to = 0;
  14526. for (auto i : selection)
  14527. {
  14528. from = std::min (from, song.playlist[(std::size_t) i].start);
  14529. to = std::max (to, song.playlist[(std::size_t) i].end());
  14530. }
  14531. if (to > from)
  14532. zoomToTicks ((double) from, (double) to);
  14533. // (FL 2026 also fits the used tracks into the view's height: shot g35)
  14534. auto last = -1;
  14535. for (const auto& c : song.playlist)
  14536. last = std::max (last, c.track);
  14537. if (last >= 0 && last + 1 < (int) trackTops.size() && trackTops[(std::size_t) last + 1] > 0)
  14538. {
  14539. setTrackZoom (trackZoom * (double) gridArea().getHeight() / (double) trackTops[(std::size_t) last + 1], tracksTop());
  14540. scrollY = 0;
  14541. updateScrollBars();
  14542. repaint();
  14543. }
  14544. lassoPath.clear();
  14545. break;
  14546. }
  14547. case magiclasso::Result::nothing:
  14548. break;
  14549. }
  14550. }
  14551. void PlaylistComponent::mouseExit (const juce::MouseEvent&)
  14552. {
  14553. lastMouse = { -1, -1 };
  14554. if (! (hover == Hover {}))
  14555. {
  14556. hover = {};
  14557. repaint();
  14558. }
  14559. }
  14560. void PlaylistComponent::modifierKeysChanged (const juce::ModifierKeys& mods)
  14561. {
  14562. if (drag == Drag::none && lastMouse.x >= 0)
  14563. updateCursor (mods);
  14564. }
  14565. juce::Rectangle<int> PlaylistComponent::clipBounds (int index) const
  14566. {
  14567. const auto& c = engine.getSong().playlist[(std::size_t) index];
  14568. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  14569. return clipRectAt (x0, x1, (float) trackToY (c.track), heightOf (c.track)).getSmallestIntegerContainer();
  14570. }
  14571. juce::Rectangle<int> PlaylistComponent::clipMenuButton (int index) const
  14572. {
  14573. const auto r = clipBounds (index);
  14574. if (r.getWidth() < 40)
  14575. return {};
  14576. return { r.getX() + 2, r.getY() + 1, 13, (int) clipTitleHeight - 2 };
  14577. }
  14578. int PlaylistComponent::trackClipUseCount (int pattern) const
  14579. {
  14580. // round 190ne: how many clips play a track clip (core/TrackClips.h uses()), counted once per published song
  14581. if (const auto stamp = engine.getPublishCount(); stamp != trackClipUsesStamp)
  14582. {
  14583. trackClipUsesStamp = stamp;
  14584. trackClipUses = trackclips::count (engine.getSong()) > 0 ? trackclips::uses (engine.getSong()) : std::vector<int> {};
  14585. }
  14586. return pattern >= 0 && pattern < (int) trackClipUses.size() ? trackClipUses[(std::size_t) pattern] : 0;
  14587. }
  14588. PlaylistComponent::Hover PlaylistComponent::hoverAt (juce::Point<int> p) const
  14589. {
  14590. Hover h;
  14591. if (p.x < headerWidth && p.y >= tracksTop() && p.y < gridArea().getBottom())
  14592. {
  14593. h.header = true;
  14594. h.track = yToTrack (p.y);
  14595. h.divider = dividerAt (p);
  14596. const auto folded = noteedit::isFoldedAway (engine.getSong(), h.track);
  14597. h.led = ! folded && h.divider < 0 && ! liveTakeLane (h.track) && trackLed (h.track).expanded (3).contains (p); // (round 190oo, CS-20)
  14598. h.arrow = ! folded && h.divider < 0 && trackArrow (h.track).contains (p);
  14599. h.arm = ! folded && h.divider < 0 && trackArm (h.track).expanded (2).contains (p);
  14600. h.input = ! folded && h.divider < 0 && trackInput (h.track).expanded (2).contains (p);
  14601. if ((simpleHeaders || simpleInsert (h.track) > 0) && ! folded && h.divider < 0) // (round 190gz: linked headers too)
  14602. {
  14603. h.solo = trackSolo (h.track).contains (p);
  14604. h.volume = trackVolume (h.track).expanded (0, 4).contains (p);
  14605. h.pan = trackPan (h.track).expanded (2).contains (p);
  14606. h.fx = trackFx (h.track).contains (p);
  14607. h.shared = trackSharedMark (h.track).contains (p); // round 190oo (CS-24)
  14608. h.insertItem = insertsItemAt (h.track, p); // issue #154
  14609. h.insertLed = h.insertItem >= 0 && p.x < trackInserts (h.track).getX() + trackinserts::ledWidth + 1;
  14610. }
  14611. h.audition = ! folded && h.divider < 0 && trackAudition (h.track).expanded (2).contains (p);
  14612. if (simpleHeaders) // round 190jc: the round "+" in the drop lane's header; nothing under the real tracks
  14613. {
  14614. if (h.track == dropLaneTrack())
  14615. {
  14616. Hover add;
  14617. add.header = true;
  14618. add.track = h.track;
  14619. add.addTrack = simpleAddButton().contains (p);
  14620. return add;
  14621. }
  14622. if (h.track >= paintedRows())
  14623. return {};
  14624. }
  14625. return h;
  14626. }
  14627. if (! gridArea().contains (p))
  14628. return h;
  14629. h.track = yToTrack (p.y);
  14630. bool rightEdge = false, leftEdge = false;
  14631. h.clip = clipAt (p.x, p.y, rightEdge, leftEdge);
  14632. if (h.clip < 0)
  14633. return h;
  14634. const auto& c = engine.getSong().playlist[(std::size_t) h.clip];
  14635. h.target = rightEdge ? gesture::Target::rightEdge : leftEdge ? gesture::Target::leftEdge : gesture::Target::item;
  14636. if (clipMenuButton (h.clip).contains (p))
  14637. h.target = gesture::Target::clipMenu;
  14638. else if (regionLoopHandle (h.clip).expanded (2.0f).contains (p.toFloat())) // round 190jr
  14639. h.target = gesture::Target::rightEdge;
  14640. else if (const auto handle = fadeHandleAt (h.clip, p); handle != 0)
  14641. {
  14642. h.target = gesture::Target::fadeHandle;
  14643. h.fade = handle;
  14644. }
  14645. else if (const auto circle = fadeTensionAt (h.clip, p); circle != 0) // round 190jz (issue #194)
  14646. {
  14647. h.target = gesture::Target::fadeTension;
  14648. h.fade = circle + 2;
  14649. }
  14650. else if (gainHandle (h.clip).expanded (2.0f).contains (p.toFloat()))
  14651. h.target = gesture::Target::gainHandle;
  14652. else if ((c.kind == ClipKind::automation || c.kind == ClipKind::audio) && automationPointAt (h.clip, p) >= 0) // (190gi: envelopes)
  14653. h.target = gesture::Target::autoPoint;
  14654. else if ((c.kind == ClipKind::automation || c.kind == ClipKind::audio) && automationHandleAt (h.clip, p) >= 0)
  14655. h.target = gesture::Target::autoTension;
  14656. else if ((c.kind == ClipKind::automation || c.kind == ClipKind::audio) && isOnAutomationCurve (h.clip, p))
  14657. h.target = gesture::Target::autoCurve;
  14658. return h;
  14659. }
  14660. void PlaylistComponent::updateHover (juce::Point<int> p, juce::ModifierKeys mods)
  14661. {
  14662. lastMouse = p;
  14663. const auto h = hoverAt (p);
  14664. if (! (h == hover))
  14665. {
  14666. // repaint the old and new track rows (header and lane)
  14667. for (auto t : { hover.track, h.track })
  14668. if (t >= 0)
  14669. repaint (0, trackToY (t) - 4, getWidth(), heightOf (t) + 8);
  14670. hover = h;
  14671. // the two comping gestures say what they do (round 177c)
  14672. if (hover.audition)
  14673. ui::postHint ({ tr ("Audition this take: it plays instead of the comp"), {}, false, false });
  14674. else if (! hover.header && hover.track >= 0 && hover.target == gesture::Target::item)
  14675. if (const auto group = comp::groupOf (engine.getSong(), hover.track); group.isLane (hover.track) && comp::isComp (engine.getSong(), group.comp))
  14676. ui::postHint ({ tr ("Drag across this take to send that range to the comp. Drag its title to move it"), {}, false, false });
  14677. }
  14678. // round 177b: the lanes' arrow and "+A" light under the mouse
  14679. if (const auto onLaneButton = h.track >= 0 && p.x < headerWidth && (trackAddLane (h.track).contains (p) || trackLaneArrow (h.track).contains (p));
  14680. onLaneButton != laneButtonHover)
  14681. {
  14682. laneButtonHover = onLaneButton;
  14683. repaint (0, trackToY (h.track), headerWidth, heightOf (h.track));
  14684. }
  14685. if (const auto onZoom = trackZoomHandle().contains (p); onZoom != trackZoomHover)
  14686. {
  14687. trackZoomHover = onZoom;
  14688. repaint (trackZoomHandle());
  14689. }
  14690. if (const auto onGrip = onHeaderGrip (p); onGrip != headerGripLit) // round 190jq (issue #164): the edge lights
  14691. {
  14692. headerGripLit = onGrip;
  14693. repaint (headerWidth - 4, rulerTop, 8, getHeight() - rulerTop);
  14694. }
  14695. if (drag == Drag::none)
  14696. updateCursor (mods);
  14697. }
  14698. void PlaylistComponent::updateCursor (juce::ModifierKeys mods)
  14699. {
  14700. const auto p = lastMouse;
  14701. auto cursor = gesture::Cursor::normal;
  14702. if (onHeaderGrip (p)) // round 190jq (issue #164)
  14703. {
  14704. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  14705. return;
  14706. }
  14707. if ((hover.header && hover.divider >= 0 && ! pltracks::isSizeLocked (engine.getSong(), hover.divider)) || trackZoomHandle().contains (p))
  14708. {
  14709. setMouseCursor (juce::MouseCursor::UpDownResizeCursor); // (a locked row's band: a click unlocks it, no resize)
  14710. return;
  14711. }
  14712. // issue #207 (round 190lw): Alt held over an automation clip's curve, Ctrl over an automation lane: the pen
  14713. if (const auto spot = curveSpotAt (p); spot.valid() && penModifier (spot.track >= 0, mods) && ! (spot.track >= 0 && drawmode::isOn())
  14714. && (tools.getTool() == EditTool::pencil || tools.getTool() == EditTool::brush || tools.getTool() == EditTool::lasso))
  14715. {
  14716. setMouseCursor (editorCursor (gesture::Cursor::draw));
  14717. return;
  14718. }
  14719. if (const auto lane = laneAt (p); lane.track >= 0) // round 177b
  14720. {
  14721. if (p.x >= headerWidth && drawmode::isOn()) // round 190ef: Draw Mode's pencil
  14722. setMouseCursor (editorCursor (gesture::Cursor::draw));
  14723. else
  14724. setMouseCursor (p.x >= headerWidth && lanePointAt (lane.track, lane.lane, p) >= 0 ? juce::MouseCursor::DraggingHandCursor
  14725. : juce::MouseCursor::NormalCursor);
  14726. return;
  14727. }
  14728. if (hover.header)
  14729. cursor = hover.led || hover.arrow || hover.arm || hover.input || hover.audition || hover.solo || hover.volume || hover.pan
  14730. || hover.fx ? gesture::Cursor::point : gesture::Cursor::normal;
  14731. else if (gridArea().contains (p))
  14732. {
  14733. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  14734. const auto tool = tools.getTool();
  14735. cursor = gesture::cursorFor (gesture::leftAction (tool, hover.target, m, true), tool);
  14736. // round 190jq: the pointer-click switch and an automation clip lane: the pointer over empty space
  14737. if (hover.clip < 0 && ! m.ctrl && ! m.shift && (tool == EditTool::pencil || tool == EditTool::brush)
  14738. && (pointerclick::on || projection.isChild (hover.track)))
  14739. cursor = gesture::Cursor::normal;
  14740. }
  14741. else if (p.y >= rulerTop && p.y < headerHeight && p.x >= headerWidth)
  14742. cursor = flmods::ctrl (mods) ? gesture::Cursor::select : gesture::Cursor::point;
  14743. setMouseCursor (editorCursor (cursor));
  14744. }
  14745. ui::Hint PlaylistComponent::hintAt (juce::Point<int> p)
  14746. {
  14747. ui::Hint hint;
  14748. const auto mods = juce::ModifierKeys::currentModifiers;
  14749. const auto& song = engine.getSong();
  14750. const auto h = hoverAt (p);
  14751. auto trackName = [&song] (int t) {
  14752. return t < (int) song.playlistTracks.size() && ! song.playlistTracks[(std::size_t) t].name.empty()
  14753. ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str())
  14754. : tr ("Track {0}", { juce::String (t + 1) });
  14755. };
  14756. // issue #207 (round 190lw): the pen's modifier held over a curve
  14757. if (const auto spot = curveSpotAt (p); spot.valid() && penModifier (spot.track >= 0, mods))
  14758. {
  14759. hint.text = tr ("Pen: drag draws the curve freehand, thinned when you let go [Select tool] drag selects points [Del] deletes them [Ctrl+C/V] copy, paste");
  14760. return hint;
  14761. }
  14762. if (const auto lane = laneAt (p); lane.track >= 0) // round 177b
  14763. {
  14764. const auto a = laneAutomation (lane.track, lane.lane);
  14765. hint.text = p.x < headerWidth ? tr ("Automation lane: [RMB] lane menu [2xLMB] edit the points")
  14766. : drawmode::isOn() ? tr ("Automation lane, Draw Mode: [LMB] drag draws steps at the grid width [Alt] freehand [RMB] deletes a point")
  14767. : tr ("Automation lane: [LMB] add or drag a point [RMB] deletes a point [Alt] drag bends the line [Shift] adds on the line");
  14768. hint.hasMenu = true;
  14769. if (a >= 0)
  14770. {
  14771. const auto& automation = song.automations[(std::size_t) a];
  14772. hint.value = juce::String::fromUTF8 (automation.name.c_str());
  14773. if (p.x >= headerWidth)
  14774. hint.value << " " << automationPointValueText (automation.target, automation.valueAt (juce::jmax (0.0, xToTick (p.x))));
  14775. }
  14776. return hint;
  14777. }
  14778. if (p.x < headerWidth && p.y >= headerHeight)
  14779. {
  14780. const auto track = yToTrack (p.y);
  14781. if (trackLaneArrow (track).expanded (2).contains (p))
  14782. return { tr ("Show / hide this track's automation lanes"), {} };
  14783. if (trackAddLane (track).contains (p))
  14784. return { tr ("Add an automation lane under this track"), {} };
  14785. }
  14786. if (onHeaderGrip (p)) // round 190jq (issue #164)
  14787. return { tr ("Track header width: [LMB] drag [2xLMB] FL's width"), juce::String (headerWidth) + " px" };
  14788. if (trackZoomHandle().contains (p))
  14789. {
  14790. hint.text = tr ("Track height (vertical zoom): [LMB] drag up / down [Alt][Wheel] over the Playlist [2xLMB] 100%");
  14791. hint.value = juce::String (juce::roundToInt (trackZoom * 100.0)) + "%";
  14792. return hint;
  14793. }
  14794. if (h.header && h.addTrack) // round 190jc: the round "+" under the Simple tracks
  14795. return { tr ("Add a track: voice, instrument, drums, sampler, guitar or bass, or import files"), {} };
  14796. // round 190rc: a Simple header's instrument icon opens the instrument's window
  14797. if (h.header && simpleHeaders && onToggleChannelWindow && h.track >= 0)
  14798. if (const auto it = simpleIconBoxes.find (h.track); it != simpleIconBoxes.end() && it->second.expanded (2).contains (p)
  14799. && simpleInstrumentChannel (h.track) >= 0)
  14800. return { tr ("Instrument: [LMB] open or close its window"), {} };
  14801. if (h.header && h.divider >= 0)
  14802. {
  14803. hint.text = tr ("Track size: [LMB] drag resizes this track (selected: every selected track) [Shift][LMB] drag: all tracks [Alt][LMB] or [MMB] default size [2xLMB] lock / unlock the size");
  14804. hint.value = juce::String (heightOf (h.divider)) + " px";
  14805. return hint;
  14806. }
  14807. if (h.header && h.insertItem != -1) // issue #154: the linked header's insert effects list
  14808. {
  14809. const auto& m = song.mixer[(std::size_t) simpleInsert (h.track)];
  14810. if (h.insertItem == trackinserts::addRow)
  14811. {
  14812. hint.text = tr ("Track effects: [LMB] add an effect to its mixer track [MMB] or double-click: search for one (drop one from the Browser here too)");
  14813. hint.value = m.name.empty() ? tr ("Insert {0}", { juce::String (simpleInsert (h.track)) }) : juce::String::fromUTF8 (m.name.c_str());
  14814. }
  14815. else
  14816. {
  14817. hint.text = h.insertLed ? tr ("Track effect: [LMB] on / off (bypass)")
  14818. : tr ("Track effect: [LMB] open / close its window drag: move it ([Ctrl] copy; onto another track: move it there) [RMB] its menu");
  14819. hint.value = quickpick::slotName (engine, m.effects[(std::size_t) h.insertItem]);
  14820. hint.hasMenu = ! h.insertLed;
  14821. }
  14822. return hint;
  14823. }
  14824. // round 190oo (CS-24): the "shared" mark: the insert this header acts on also plays other tracks (their names)
  14825. if (h.header && h.shared)
  14826. {
  14827. const auto& target = headerTarget (h.track);
  14828. juce::StringArray others;
  14829. for (const auto u : target.others)
  14830. if (others.size() < 4)
  14831. others.add (trackName (u));
  14832. if (target.sharedWith > others.size())
  14833. others.add ("...");
  14834. hint.text = tr ("Shared mixer track: volume, pan, solo and effects here act on every track it plays; M mutes only this track");
  14835. hint.value = tr ("Also plays {0}", { others.joinIntoString (", ") });
  14836. return hint;
  14837. }
  14838. if (const auto insert = headerInsert (h.track);
  14839. h.header && insert > 0 && (h.solo || h.volume || h.pan || h.fx || (h.led && (! simpleHeaders || headerTarget (h.track).own))))
  14840. {
  14841. // the Simple headers (round 184a): their controls are the track's mixer track's (round 190oo, CS-24: an FL track's
  14842. // M is its Playlist mute, described with the plain header below)
  14843. const auto& m = song.mixer[(std::size_t) insert];
  14844. hint.text = h.led ? (simpleHeaders ? tr ("Track: [LMB] mute / unmute its mixer track")
  14845. : tr ("Linked track: [LMB] mute / unmute its mixer track [Ctrl][LMB] or [RMB] solo the Playlist track"))
  14846. : h.solo ? tr ("Track: [LMB] solo its mixer track")
  14847. : h.volume ? tr ("Track volume: [LMB] click or drag [Shift] fine [2xLMB] 0 dB")
  14848. : h.pan ? tr ("Track pan: [LMB] drag up / down [Shift] fine [2xLMB] centre")
  14849. : tr ("Track effects: [LMB] open the effects of its mixer track");
  14850. // issue #265 (round 190qj): a linked track whose clips also play through other inserts says so
  14851. if (! simpleHeaders && (h.led || h.volume || h.pan))
  14852. if (const auto others = autolink::otherInsertsOnTrack (song, h.track, insert); ! others.empty())
  14853. {
  14854. juce::StringArray names;
  14855. for (const auto o : others)
  14856. names.add (o == 0 ? tr ("Master") : juce::String (o));
  14857. hint.text += " " + tr ("(some clips here play through other mixer tracks: {0}; M mutes this Playlist track too)", { names.joinIntoString (", ") });
  14858. }
  14859. if (h.volume)
  14860. hint.value = juce::String (juce::Decibels::gainToDecibels (m.volume / unityFader), 1) + " dB";
  14861. else if (h.pan)
  14862. hint.value = juce::String (juce::roundToInt (m.pan * 100.0f));
  14863. else if (h.fx && ! m.chainPreset.empty()) // round 190dg: the track's chain preset, as the dock names it
  14864. hint.value = juce::String::fromUTF8 (m.chainPreset.c_str())
  14865. + (chains::unchanged (song, insert) ? juce::String() : " " + tr ("(edited)"));
  14866. else
  14867. hint.value = trackName (h.track);
  14868. return hint;
  14869. }
  14870. if (h.header)
  14871. {
  14872. hint.text = h.arm ? tr ("Audio track: [LMB] arm / disarm recording (its mixer track)")
  14873. : h.input ? tr ("Audio track: [LMB] audio input source and monitoring (its mixer track)")
  14874. : h.led && ! noteedit::groupMuteSet (song, h.track).empty() // round 190jf: FL's group mute / solo
  14875. ? tr ("Track: [LMB] mute / unmute [Ctrl][LMB] or [RMB] solo [Shift][LMB] lock its state [Alt][LMB] mute the group [Alt][RMB] solo the group")
  14876. : h.led ? tr ("Track: [LMB] mute / unmute [Ctrl][LMB] or [RMB] solo [Shift][LMB] lock its state")
  14877. : h.arrow ? tr ("Track group: [LMB] collapse / expand the grouped tracks")
  14878. : tr ("Track: [LMB] select [Ctrl][LMB] add / remove [Ctrl] drag: tracks with their clips [Shift][LMB] range [RMB] menu [2xLMB] open the clip source [Shift][Wheel] move up / down [Alt] drag: move into / out of a group");
  14879. hint.value = trackName (h.track);
  14880. if (h.led && h.track < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) h.track].soloLock) // round 190ld
  14881. hint.value << " " << tr ("(state locked)");
  14882. if (const auto mode = trackmodes::describe (song, h.track); ! mode.empty()) // FL's "(Instrument track)" / "(Audio track, ...)"
  14883. {
  14884. hint.value += " " + (mode.rfind ("(Audio", 0) == 0 ? tr ("(Audio track, linked to mixer track {0})", { juce::String (song.playlistTracks[(std::size_t) h.track].mixerTrack) })
  14885. : tr ("(Instrument track)"));
  14886. // round 190ne (core/TrackClips.h): LYNX's own track clips and bus tracks
  14887. if (trackclips::owns (song, h.track))
  14888. hint.value += " " + tr ("(its clips own their notes: the pencil draws a new clip, copies are unique)");
  14889. else if (const auto sources = trackclips::busSources (song, h.track); sources > 0)
  14890. hint.value += " " + tr ("(bus: {0} mixer track(s) send into it; \"+A\" adds its volume and pan lanes)", { juce::String (sources) });
  14891. }
  14892. else if (linkedHeaders()) // issue #170 (round 190ib): a track that only repeats a track above it
  14893. {
  14894. if (const auto repeats = autolink::repeatedTracks (song); h.track >= 0 && h.track < (int) repeats.size() && repeats[(std::size_t) h.track] >= 0)
  14895. hint.value += " " + tr ("(repeats Track {0}'s instruments: plays through insert {0})", { juce::String (repeats[(std::size_t) h.track] + 1) });
  14896. }
  14897. else if (routingHints && ! simpleHeaders && ! h.led && ! noteedit::isGroupHeader (song, h.track)) // round 190rs (G-01, LYNX extra): where an unassigned track is heard (a group header holds no clips of its own)
  14898. {
  14899. if (const auto route = routeHintFor (song, h.track); route.isNotEmpty())
  14900. hint.value += " " + route;
  14901. }
  14902. hint.hasMenu = ! h.led && ! h.arrow && ! h.arm && ! h.input;
  14903. return hint;
  14904. }
  14905. if (p.y >= rulerTop && p.y < headerHeight && p.x >= headerWidth)
  14906. {
  14907. // over a marker's tag: its action, and that a click jumps there (FL)
  14908. if (const auto m = markerTagAt (p.x, p.y); m >= 0)
  14909. {
  14910. const auto& marker = song.markers()[(std::size_t) m];
  14911. hint.text = tr ("Marker: [LMB] jump to it (while playing: at the next Quantize song jumps step) [LMB] drag: move it [Ctrl][LMB] select up to the next marker [RMB] action, rename, delete");
  14912. hint.value = markerLabel (marker);
  14913. if (const auto* action = markers::actionName (marker.isSignature() ? Marker::timeSignature : marker.action); *action != 0)
  14914. hint.value += " (" + tr (action) + ")";
  14915. hint.hasMenu = true;
  14916. return hint;
  14917. }
  14918. hint.text = tr ("Ruler: [LMB] song position [RMB] or [Ctrl][LMB] or [2xLMB] drag: time selection (loop) [Shift][LMB] drag: move it [Ctrl][RMB] drag or [Ctrl][Wheel] or a pinch: zoom [RMB] click: menu [Alt] no snap");
  14919. hint.hasMenu = true;
  14920. return hint;
  14921. }
  14922. if (! gridArea().contains (p))
  14923. return hint;
  14924. const gesture::Mods m { mods.isShiftDown(), flmods::ctrl (mods), mods.isAltDown() };
  14925. hint.text = actionHint (gesture::leftAction (tools.getTool(), h.target, m, true), true);
  14926. // round 190jq: the pointer-click switch, and an automation clip lane (nothing is placed there)
  14927. // round 190mk (DL-70): Live's status bar names the insert marker while the pointer is over the lanes
  14928. if (h.clip < 0 && insertMarkLine.isVisible() && insertMarkTrack >= 0 && liveArrangeLook())
  14929. return { insertMarkText(), {} };
  14930. if (h.clip < 0 && ! m.ctrl && ! m.shift && (tools.getTool() == EditTool::pencil || tools.getTool() == EditTool::brush))
  14931. {
  14932. if (projection.isChild (h.track))
  14933. hint.text = tr ("Automation lane: [LMB] song position [LMB] drag: select (its clips: drag left / right)");
  14934. // round 190qp (Discord, 0.1.31: "not sure how to make a MIDI clip"): the Simple layout's instrument tracks say how
  14935. else if (simpleHeaders && brush.kind == ClipKind::pattern && h.track >= 0 && h.track < (int) song.playlistTracks.size()
  14936. && song.playlistTracks[(std::size_t) h.track].mode == PlaylistTrackMode::instrument)
  14937. hint.text = tr ("MIDI clip: [LMB] click or drag draws one on this track [2xLMB] on a clip: edit its notes below");
  14938. else if ((trackclips::owns (song, h.track) && brush.kind == ClipKind::pattern) || trackclips::pencilMakesNewClip (song, h.track)) // round 190ne (190qu)
  14939. hint.text = tr ("Track clips: [LMB] draw a new empty clip [Shift] drag a clip: a unique copy [Shift+L] drag: a linked copy [Ctrl+Alt+B] linked copies");
  14940. else if (pointerclick::on)
  14941. hint.text = tr ("Pointer click: [LMB] song position and deselect [LMB] drag: select [2xLMB] place the clip");
  14942. }
  14943. if (h.clip >= 0)
  14944. {
  14945. const auto onHeader = p.y < clipBounds (h.clip).getY() + (int) clipTitleHeight;
  14946. if (h.target == gesture::Target::gainHandle)
  14947. hint.text = actionHint (gesture::Action::clipGain, true);
  14948. else if (h.target == gesture::Target::fadeHandle) // round 190jz: FL's "Fade in: 0'00.000'' (auto) Hold Alt to snap"
  14949. {
  14950. const auto& c = song.playlist[(std::size_t) h.clip];
  14951. const auto side = fadeHandleAt (h.clip, p) - 1;
  14952. hint.text = (side == 0 ? tr ("Fade in: {0}", { fadeLengthText (c.effectiveFadeIn()) }) : tr ("Fade out: {0}", { fadeLengthText (c.effectiveFadeOut()) }))
  14953. + (clipops::manualFade (c, side) ? juce::String() : " " + tr ("(auto)")) + " "
  14954. + (EditorGlobals::get().snapFadeHandles ? tr ("Hold Alt for no snap") : tr ("Hold Alt to snap"));
  14955. hint.hasMenu = true;
  14956. return hint;
  14957. }
  14958. else if (h.target == gesture::Target::fadeTension) // FL: "Tension: 0%"
  14959. {
  14960. const auto& c = song.playlist[(std::size_t) h.clip];
  14961. const auto side = fadeTensionAt (h.clip, p) - 1;
  14962. hint.text = tr ("Tension: {0}%", { juce::String (juce::roundToInt (clipops::fadeTensionHandle (side == 0 ? c.fadeInTension : c.fadeOutTension) * 100.0)) });
  14963. hint.hasMenu = true;
  14964. return hint;
  14965. }
  14966. else if (h.target == gesture::Target::clipMenu)
  14967. hint.text = song.playlist[(std::size_t) h.clip].kind == ClipKind::audio
  14968. ? tr ("Clip menu: [LMB] or [RMB] opens it (pitch, fit to tempo, reverse, chop, make unique...)")
  14969. : tr ("Clip menu: [LMB] or [RMB] opens it (make unique, rename and colour, chop, select source...)");
  14970. else if (onHeader && ! m.ctrl)
  14971. hint.text << " " << tr ("The icon at the top left opens the clip menu (make unique, rename...)");
  14972. else if (h.target == gesture::Target::item && ! m.ctrl && automationEditable (h.clip)
  14973. && automationBody (song.playlist[(std::size_t) h.clip]).contains (p.toFloat())) // round 165
  14974. hint.text << " " << tr ("[RMB] adds a point here (hold and drag to place it) [Shift][RMB] on the curve");
  14975. else if (h.target == gesture::Target::item && ! m.ctrl && warpStripSeconds (h.clip, p) > 0.0) // round 190gi
  14976. hint.text << " " << tr ("Warp flags: drag one to move it, double-click here adds one [Alt]+drag moves a marker's line anywhere on the clip");
  14977. else if (h.target == gesture::Target::item && ! m.ctrl)
  14978. hint.text << " " << tr ("[Shift][V] + drag: a unique copy [Alt][RMB] hold: hear it");
  14979. const auto& c = song.playlist[(std::size_t) h.clip];
  14980. hint.hasMenu = true;
  14981. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  14982. hint.value = juce::String::fromUTF8 (song.patterns[(std::size_t) c.pattern].name.c_str());
  14983. else if (c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  14984. hint.value = h.target == gesture::Target::gainHandle ? tr ("Gain: {0}", { gainText (c.gain) })
  14985. : juce::String::fromUTF8 (song.channels[(std::size_t) c.channel].name.c_str());
  14986. else if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size())
  14987. {
  14988. const auto& automation = song.automations[(std::size_t) c.automation];
  14989. hint.value = juce::String::fromUTF8 (automation.name.c_str());
  14990. // round 190im (DE-119): over the curve the value at the mouse, as the automation lanes show it
  14991. if (automationEditable (h.clip) && automationBody (c).contains (p.toFloat()))
  14992. hint.value << " " << curveValueText (h.clip, curveValueAt (h.clip, (double) c.offset + xToTick (p.x) - (double) c.start));
  14993. }
  14994. }
  14995. else
  14996. hint.value = trackName (h.track);
  14997. return hint;
  14998. }
  14999. void PlaylistComponent::mouseDoubleClick (const juce::MouseEvent& e)
  15000. {
  15001. if (laneAt (e.getPosition()).track >= 0) // round 177b: lanes handle their clicks in mouseDown
  15002. return;
  15003. // round 190jq: the header grip's double click (FL's width) and a pointer-click double click that placed a clip (it
  15004. // does not open the clip as well) are done in mouseDown
  15005. if (onHeaderGrip (e.getPosition()) || placedByDoubleClick)
  15006. {
  15007. placedByDoubleClick = false;
  15008. return;
  15009. }
  15010. if (trackZoomHandle().contains (e.getPosition())) // the vertical zoom handle: back to 100%
  15011. {
  15012. setTrackZoom (1.0, tracksTop());
  15013. return;
  15014. }
  15015. // a double click on a header's resize band flips "Lock to this size" (FL; done by the second press in mouseDown)
  15016. if (dividerAt (e.getPosition()) >= 0)
  15017. return;
  15018. if (e.x < headerWidth && e.y >= tracksTop() && trackInserts (yToTrack (e.y)).contains (e.getPosition()))
  15019. return; // (issue #154: the effects list takes single clicks only)
  15020. // double-click a track header: open the source of the track's first clip (FL); empty tracks: rename
  15021. if (e.x < headerWidth && e.y >= tracksTop() && e.y < gridArea().getBottom() && e.mods.isLeftButtonDown())
  15022. {
  15023. const auto track = yToTrack (e.y);
  15024. if (trackLed (track).expanded (3).contains (e.getPosition()) || trackArrow (track).contains (e.getPosition())
  15025. || trackArm (track).expanded (2).contains (e.getPosition()) || trackInput (track).expanded (2).contains (e.getPosition()))
  15026. return;
  15027. if (const auto insert = headerInsert (track); insert > 0) // (round 190oo CS-24: an FL track's borrowed insert too)
  15028. {
  15029. // the Simple headers: a double-click resets the volume (to 0 dB) or the pan (centre); on the name it renames.
  15030. // The linked headers (round 190gz): the same on volume / pan; elsewhere FL's double-click
  15031. const auto p = e.getPosition();
  15032. if (trackVolume (track).expanded (0, 4).contains (p))
  15033. {
  15034. engine.editSong ([insert] (Song& s) { s.mixer[(std::size_t) insert].volume = unityFader; });
  15035. return;
  15036. }
  15037. if (trackPan (track).expanded (2).contains (p))
  15038. {
  15039. engine.editSong ([insert] (Song& s) { s.mixer[(std::size_t) insert].pan = 0.0f; });
  15040. return;
  15041. }
  15042. if (trackSolo (track).contains (p) || trackFx (track).contains (p))
  15043. return;
  15044. if (simpleHeaders && simpleInsert (track) > 0) // (an FL track's name keeps FL's double-click: its clip's source)
  15045. {
  15046. renameTrack (track);
  15047. return;
  15048. }
  15049. }
  15050. const auto& playlist = engine.getSong().playlist;
  15051. int first = -1;
  15052. for (int i = 0; i < (int) playlist.size(); ++i)
  15053. if (playlist[(std::size_t) i].track == track && (first < 0 || playlist[(std::size_t) i].start < playlist[(std::size_t) first].start))
  15054. first = i;
  15055. if (first >= 0)
  15056. openClipSource (first, e.mods.isAltDown());
  15057. else
  15058. renameTrack (track);
  15059. return;
  15060. }
  15061. bool edge = false;
  15062. const auto hit = gridArea().contains (e.getPosition()) ? clipAt (e.x, e.y, edge) : -1;
  15063. if (hit < 0)
  15064. return;
  15065. // round 190gi: on the warp flag strip of a warped clip a double-click adds a warp marker (nothing moves until it is
  15066. // dragged); everywhere else FL's double-click (the channel settings; Alt: the clip properties)
  15067. if (! e.mods.isAltDown())
  15068. if (const auto seconds = warpStripSeconds (hit, e.getPosition()); seconds > 0.0)
  15069. {
  15070. const auto file = clipFileSeconds (hit);
  15071. engine.editSong ([hit, seconds, file] (Song& s) { clipwarp::addMarker (s, hit, seconds, file); });
  15072. repaint();
  15073. return;
  15074. }
  15075. openClipSource (hit, e.mods.isAltDown());
  15076. }
  15077. void PlaylistComponent::openClipSource (int hit, bool other)
  15078. {
  15079. if (hit < 0 || hit >= (int) engine.getSong().playlist.size())
  15080. return;
  15081. const auto clip = engine.getSong().playlist[(std::size_t) hit];
  15082. if (clip.kind == ClipKind::pattern && clip.pattern != engine.getSong().currentPattern
  15083. && clip.pattern < (int) engine.getSong().patterns.size())
  15084. engine.editSong ([p = clip.pattern] (Song& s) { s.currentPattern = p; }, false);
  15085. if (clip.kind == ClipKind::automation)
  15086. openAutomationEditor (engine, clip.automation);
  15087. else if (clip.kind == ClipKind::audio) // round 170h2: was nothing (the hint said "opens")
  15088. {
  15089. // FL's "Double-click on audio clips" (Manage shortcuts, ShortcutEditorForm AudioClipsPanel): the channel
  15090. // settings, Alt = the clip properties (LYNX's Alt+double-click since round 153)
  15091. if (other)
  15092. showClipProperties (engine, hit, { hit }, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] {
  15093. if (safe != nullptr)
  15094. safe->sortClips();
  15095. });
  15096. else if (clip.channel >= 0 && clip.channel < (int) engine.getSong().channels.size())
  15097. openChannelSettings (engine, clip.channel);
  15098. }
  15099. else if (clip.kind == ClipKind::pattern)
  15100. {
  15101. // round 190qp (Discord, 0.1.31): in Track-only mode and the Simple layout a clip on an instrument track opens its
  15102. // instrument's notes, empty or not (Alt: the other editor, as below). The Pattern layout keeps FL's rule.
  15103. if (! other && (trackonly::active() || simpleHeaders))
  15104. if (const auto channel = trackonly::pianoRollChannelOf (engine.getSong(), hit); channel >= 0)
  15105. {
  15106. engine.setSelectedChannel (channel);
  15107. if (onOpenTrackClipNotes)
  15108. onOpenTrackClipNotes (clip.track);
  15109. else if (onOpenPianoRoll)
  15110. onOpenPianoRoll();
  15111. return;
  15112. }
  15113. auto pianoRoll = editPatternsIn == 2
  15114. || (editPatternsIn == 0 && clip.pattern < (int) engine.getSong().patterns.size()
  15115. && hasPianoRollNotes (engine.getSong().patterns[(std::size_t) clip.pattern]));
  15116. if (other)
  15117. pianoRoll = ! pianoRoll;
  15118. if (pianoRoll && onOpenPianoRoll)
  15119. onOpenPianoRoll();
  15120. else if (! pianoRoll && onOpenPattern)
  15121. onOpenPattern();
  15122. }
  15123. }
  15124. bool PlaylistComponent::isInterestedInFileDrag (const juce::StringArray& files)
  15125. {
  15126. for (const auto& f : files)
  15127. if (SampleLibrary::isSampleFile (juce::File (f)) || videotracks::isVideoFile (juce::File (f))
  15128. || (simpleHeaders && onSimpleFilesDropped && (juce::File (f).hasFileExtension ("mid;midi") || juce::File (f).isDirectory()))
  15129. || (! simpleHeaders && workflowextras::isMidiFile (f) && mididrop::playlistTakes (layoutstyle::current() == layoutstyle::Style::clipLaunch)))
  15130. return true; // (round 190fo: a folder of stems and MIDI files, Simple workflow)
  15131. return false;
  15132. }
  15133. namespace
  15134. {
  15135. // An audio clip of `file` at `start` on `track` (one undo step); `reuse`: an existing audio-clip channel of the same
  15136. // file plays it instead of a new one. False when the file can't be read.
  15137. bool addAudioClip (AudioEngine& engine, const juce::File& file, std::int64_t start, int track, bool reuse, bool loopsKeepTime = false)
  15138. {
  15139. if (! SampleLibrary::isSampleFile (file))
  15140. return false;
  15141. const auto data = engine.getSampleLibrary().load (file.getFullPathName());
  15142. if (data == nullptr)
  15143. return false;
  15144. // audio length converted to ticks at the current BPM
  15145. const auto seconds = (double) data->frames() / data->sampleRate;
  15146. auto length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * engine.getSong().bpm / 60.0 * ppq));
  15147. const auto path = file.getFullPathName().toStdString();
  15148. const auto name = file.getFileNameWithoutExtension().toStdString();
  15149. // the Simple workflow (round 190p): a loop made for a tempo lasts its beats at the project's tempo, at its own pitch
  15150. const auto loopBeats = loopsKeepTime ? simpletracks::loopBeats (file.getFileName().toStdString(), seconds, data->acidBeats, engine.getSong().meter())
  15151. : 0.0f;
  15152. if (loopBeats > 0.0f)
  15153. length = juce::jmax<std::int64_t> (1, (std::int64_t) std::llround ((double) loopBeats * ppq));
  15154. engine.editSong ([=] (Song& s) {
  15155. int channel = -1;
  15156. if (reuse)
  15157. for (int c = 0; c < (int) s.channels.size(); ++c)
  15158. if (s.channels[(std::size_t) c].instrument == InstrumentKind::audioClip && s.channels[(std::size_t) c].samplePath == path)
  15159. channel = c;
  15160. if (channel < 0)
  15161. {
  15162. ChannelDef c;
  15163. c.name = name;
  15164. c.instrument = InstrumentKind::audioClip;
  15165. c.sampler.declickMode = audioClipDeclickMode; // FL's AudioTrack.fst
  15166. c.samplePath = path;
  15167. // dropped on an audio track: the new channel plays through its mixer track (FL [DECOMP FUN_012f2a10])
  15168. const auto linked = trackmodes::armableInsert (s, track);
  15169. c.mixerTrack = linked > 0 ? linked : s.claimFreeInsert();
  15170. if (loopBeats > 0.0f)
  15171. {
  15172. c.sampler.stretchBeats = loopBeats;
  15173. c.sampler.keepPitch = true;
  15174. }
  15175. s.channels.push_back (c);
  15176. channel = (int) s.channels.size() - 1;
  15177. }
  15178. Clip clip;
  15179. clip.kind = ClipKind::audio;
  15180. clip.channel = channel;
  15181. clip.track = track;
  15182. clip.start = start;
  15183. clip.length = length;
  15184. clip.flFadeFlags = newClipFadeFlags();
  15185. s.playlist.push_back (clip);
  15186. trackmodes::followAudioTracks (s, { (int) s.playlist.size() - 1 }); // (a reused channel)
  15187. s.mode = PlayMode::song;
  15188. });
  15189. return true;
  15190. }
  15191. } // namespace
  15192. void PlaylistComponent::filesDropped (const juce::StringArray& files, int x, int y)
  15193. {
  15194. // round 190rw (Q1): several files dropped at once are one undo step, not one per file
  15195. const AudioEngine::UndoGesture dropStarts (engine, AudioEngine::UndoGesture::begin);
  15196. const struct DropEnds
  15197. {
  15198. AudioEngine& e;
  15199. ~DropEnds() { const AudioEngine::UndoGesture ends (e, AudioEngine::UndoGesture::end); }
  15200. } dropEnds { engine };
  15201. setDropLaneHot (false);
  15202. clearDropGhost();
  15203. // round 190iu (issue #191.2, ui/WorkflowExtras.h): MIDI files become pattern clips where they are dropped (on a header:
  15204. // at the song start); the other files go on as below
  15205. if (! simpleHeaders && workflowextras::anyMidiFile (files) && y >= tracksTop() && y < gridArea().getBottom()
  15206. && mididrop::playlistTakes (layoutstyle::current() == layoutstyle::Style::clipLaunch))
  15207. {
  15208. const auto at = x < headerWidth ? std::int64_t (0) : juce::jmax<std::int64_t> (0, snap (xToTick (x), true));
  15209. workflowextras::dropMidiOnPlaylist (engine, files, juce::jmax (0, yToTrack (y)), at, layoutstyle::current() == layoutstyle::Style::clipLaunch);
  15210. juce::StringArray rest;
  15211. for (const auto& f : files)
  15212. if (! workflowextras::isMidiFile (f))
  15213. rest.add (f);
  15214. if (rest.isEmpty())
  15215. return;
  15216. filesDropped (rest, x, y);
  15217. return;
  15218. }
  15219. // on a track header (round 189e): FL's Edit › Drop audio on track headers, on an unassigned track
  15220. if (x < headerWidth && y >= tracksTop() && y < gridArea().getBottom())
  15221. if (const auto track = yToTrack (y); track >= 0 && (track >= (int) engine.getSong().playlistTracks.size()
  15222. || engine.getSong().playlistTracks[(std::size_t) track].mode == PlaylistTrackMode::unassigned))
  15223. {
  15224. dropOnTrackHeader (files, track);
  15225. return;
  15226. }
  15227. auto start = juce::jmax<std::int64_t> (0, snap (xToTick (x), true));
  15228. auto track = yToTrack (y);
  15229. // the Simple workflow (round 184a): files dropped on the lane under the tracks (or on any track that isn't one of
  15230. // its tracks), and MIDI files anywhere, become new tracks of their own
  15231. if (simpleHeaders && onSimpleFilesDropped)
  15232. {
  15233. const auto midi = std::any_of (files.begin(), files.end(), [] (const juce::String& f) {
  15234. return juce::File (f).hasFileExtension ("mid;midi") || juce::File (f).isDirectory(); // (round 190fo: a folder of stems)
  15235. });
  15236. if (midi || ! simpletracks::kindOf (engine.getSong(), track).has_value())
  15237. {
  15238. onSimpleFilesDropped (files, x >= headerWidth ? start : 0);
  15239. return;
  15240. }
  15241. // round 190jj (BandLab): audio on a track of notes is refused, as its red ghost said ("Region not supported by
  15242. // this track"); it was placed there as an audio clip the track's instrument never plays
  15243. if (x >= headerWidth && simpleDropRefusal (track, ClipKind::audio).isNotEmpty())
  15244. return;
  15245. }
  15246. // issue #325 (round 190sg, FL 2026 checked live): one sample dropped on an audio clip replaces its channel's sample
  15247. // (every clip of that channel plays it; the channel, its insert and effects stay); on a pattern clip nothing happens
  15248. if (files.size() == 1)
  15249. {
  15250. auto nothing = false;
  15251. if (const auto target = sampleDropTarget ({ x, y }, juce::File (files[0]), nothing); target >= 0)
  15252. {
  15253. replaceSampleOnDrop (target, juce::File (files[0]));
  15254. return;
  15255. }
  15256. if (nothing)
  15257. return;
  15258. }
  15259. for (const auto& f : files)
  15260. if (videotracks::isVideoFile (juce::File (f)))
  15261. // a video dropped on the clip tracks: a video clip on a video track, where it was dropped (round 174d)
  15262. videotracks::importVideo (engine, juce::File (f), engine.getSong().secondsForTicks (start));
  15263. else if (addAudioClip (engine, juce::File (f), start, track, false, simpleHeaders)) // (Simple: a loop keeps time)
  15264. ++track; // multiple files: one below the other
  15265. }
  15266. void PlaylistComponent::addAudioClipAtPlayhead (const juce::File& file)
  15267. {
  15268. const auto& song = engine.getSong();
  15269. const auto start = song.mode == PlayMode::song ? juce::jmax<std::int64_t> (0, snap ((std::int64_t) engine.getTransport().positionTicks.load(), false))
  15270. : std::int64_t (0);
  15271. // the first track with nothing at the start
  15272. int track = 0;
  15273. for (;; ++track)
  15274. {
  15275. const auto busy = std::any_of (song.playlist.begin(), song.playlist.end(), [&] (const Clip& c) {
  15276. return c.track == track && c.start <= start && c.end() > start;
  15277. });
  15278. if (! busy)
  15279. break;
  15280. }
  15281. addAudioClip (engine, file, start, track, true);
  15282. }
  15283. int PlaylistComponent::sampleDropTarget (juce::Point<int> p, const juce::File& file, bool& nothing) const
  15284. {
  15285. nothing = false;
  15286. // FL's Pattern layout only (Live and BandLab place a new clip where it is dropped: Clip-launch and Simple keep that);
  15287. // Shift adds a clip there as FL does; a file FL's Playlist takes as a sample, not a video
  15288. if (simpleHeaders || layoutstyle::current() != layoutstyle::Style::pattern || p.x < headerWidth || p.y < tracksTop()
  15289. || p.y >= gridArea().getBottom() || p.x >= gridArea().getRight() || ! SampleLibrary::isSampleFile (file)
  15290. || videotracks::isVideoFile (file) || shiftDropForCheck || juce::ModifierKeys::getCurrentModifiersRealtime().isShiftDown())
  15291. return -1;
  15292. bool right = false;
  15293. const auto index = clipAt (p.x, p.y, right);
  15294. const auto& song = engine.getSong();
  15295. if (index < 0 || index >= (int) song.playlist.size())
  15296. return -1;
  15297. const auto& clip = song.playlist[(std::size_t) index];
  15298. if (clip.kind == ClipKind::pattern)
  15299. {
  15300. nothing = true; // (FL: the drop finds no channel behind a pattern clip and stops, FLEngine FUN_00e73950)
  15301. return -1;
  15302. }
  15303. const auto channel = clip.channel;
  15304. if (clip.kind != ClipKind::audio || channel < 0 || channel >= (int) song.channels.size()
  15305. || song.channels[(std::size_t) channel].instrument != InstrumentKind::audioClip)
  15306. return -1;
  15307. return index;
  15308. }
  15309. bool PlaylistComponent::replaceSampleOnDrop (int clip, const juce::File& file)
  15310. {
  15311. const auto& song = engine.getSong();
  15312. if (clip < 0 || clip >= (int) song.playlist.size())
  15313. return false;
  15314. const auto data = engine.getSampleLibrary().load (file.getFullPathName());
  15315. if (data == nullptr)
  15316. {
  15317. ui::postNotice ({ tr ("Could not read {0}", { file.getFileName() }), {} });
  15318. return false;
  15319. }
  15320. // the clip lengths the old and the new file give (as a drop makes them: at the song's tempo, the channel's stretch)
  15321. const auto ticksOf = [&song] (double seconds) { return juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * song.bpm / 60.0 * ppq)); };
  15322. const auto& channel = song.channels[(std::size_t) song.playlist[(std::size_t) clip].channel];
  15323. std::int64_t oldTicks = 0;
  15324. if (channel.sampler.stretchBeats > 0.0f)
  15325. oldTicks = (std::int64_t) std::llround ((double) channel.sampler.stretchBeats * ppq);
  15326. else if (auto old = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str())); old != nullptr && old->sampleRate > 0)
  15327. oldTicks = ticksOf ((double) old->frames() / old->sampleRate);
  15328. const auto newTicks = data->sampleRate > 0 ? ticksOf ((double) data->frames() / data->sampleRate) : (std::int64_t) 0;
  15329. auto done = false;
  15330. engine.editSong ([&] (Song& s) {
  15331. done = audioclips::replaceClipSample (s, clip, file.getFullPathName().toStdString(), file.getFileNameWithoutExtension().toStdString(),
  15332. oldTicks, newTicks, flsettings::options().autoNameChannels.load());
  15333. });
  15334. repaint();
  15335. return done;
  15336. }
  15337. bool PlaylistComponent::sampleDropGhost (juce::Point<int> p, const juce::File& file, std::vector<Clip>& ghost)
  15338. {
  15339. auto nothing = false;
  15340. const auto target = sampleDropTarget (p, file, nothing);
  15341. const auto& song = engine.getSong();
  15342. if (target >= 0)
  15343. {
  15344. // the ghost marks every clip of the channel (they all change), not the place of a new clip
  15345. const auto channel = song.playlist[(std::size_t) target].channel;
  15346. for (const auto& c : song.playlist)
  15347. if (c.kind == ClipKind::audio && c.channel == channel)
  15348. ghost.push_back (c);
  15349. ui::postHint ({ tr ("Replaces the sample of {0} with {1}: its clips, insert and effects stay [Shift] new clip",
  15350. { juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()), file.getFileNameWithoutExtension() }), {} });
  15351. return true;
  15352. }
  15353. if (nothing)
  15354. {
  15355. ui::postHint ({ tr ("A sample dropped on a pattern clip does nothing, as in FL Studio [Shift] new clip"), {} });
  15356. return true;
  15357. }
  15358. return false;
  15359. }
  15360. void PlaylistComponent::glideBy (double ticks, double pixels, bool immediate)
  15361. {
  15362. if (! gliding)
  15363. {
  15364. glideX.jumpTo (scrollTicks);
  15365. glideY.jumpTo (scrollY);
  15366. gliding = true;
  15367. }
  15368. const auto grid = gridArea();
  15369. glideX.target = juce::jlimit (0.0, juce::jmax (0.0, hBar.getMaximumRangeLimit() - grid.getWidth() / pixelsPerTick), glideX.target + ticks);
  15370. if (ticks != 0.0) // (a whole number of pixels from the start: the cached picture shifts, round 174e2)
  15371. glideX.target = std::round (glideX.target * pixelsPerTick) / pixelsPerTick;
  15372. glideY.target = juce::jlimit (0.0, juce::jmax (0.0, (double) tracksHeight() - grid.getHeight()), glideY.target + pixels);
  15373. if (immediate || ! ui::motion::enabled()) // (Settings › General › Animations off: the wheel jumps)
  15374. {
  15375. scrollTicks = glideX.target;
  15376. scrollY = (int) std::round (glideY.target);
  15377. gliding = false;
  15378. updateScrollBars();
  15379. glideX.jumpTo (scrollTicks); // the scroll bar may have clamped it
  15380. glideY.jumpTo (scrollY);
  15381. repaintScrolled();
  15382. return;
  15383. }
  15384. vblank.start(); // the next frames at the display's refresh (round 190gv: no vertical blanks while still)
  15385. glideFrame();
  15386. }
  15387. void PlaylistComponent::glideFrame()
  15388. {
  15389. if (! gliding)
  15390. return;
  15391. // someone else moved the view (scroll bar, zoom, pan, playback follow): the glide gives way
  15392. if (std::abs (scrollTicks - glideX.current) > 1e-6 || std::abs ((double) scrollY - std::round (glideY.current)) > 0.5)
  15393. {
  15394. gliding = false;
  15395. return;
  15396. }
  15397. // whole pixels sideways (round 174e2: the cached picture then shifts instead of being painted again), at least one
  15398. // pixel towards the target each frame. Only when it is moving sideways: a zoom can leave the view between two pixels,
  15399. // and a plain wheel there flipped it by that fraction every frame, each frame painting everything (round 174f)
  15400. if (glideX.isMoving())
  15401. {
  15402. const auto fromPixels = scrollTicks * pixelsPerTick;
  15403. const auto steppedPixels = glideX.step (0.45, 0.5 / pixelsPerTick) * pixelsPerTick;
  15404. scrollTicks = (glideX.target * pixelsPerTick > fromPixels ? std::ceil (steppedPixels - 1.0e-6) : std::floor (steppedPixels + 1.0e-6)) / pixelsPerTick;
  15405. if ((glideX.target - scrollTicks) * (glideX.target * pixelsPerTick - fromPixels) < 0.0) // (never past the target)
  15406. scrollTicks = glideX.target;
  15407. }
  15408. scrollY = (int) std::round (glideY.step (0.45, 1.0));
  15409. glideY.current = scrollY;
  15410. const auto wanted = scrollTicks;
  15411. updateScrollBars();
  15412. if (std::abs (scrollTicks - wanted) > 1.0e-6) // (the scroll bar clamped it: this is as far as it goes)
  15413. glideX.target = scrollTicks;
  15414. glideX.current = scrollTicks;
  15415. gliding = glideX.isMoving() || glideY.isMoving();
  15416. repaintScrolled();
  15417. }
  15418. // Round 190pm (research190oe P23, ui/TouchInput.h): Touch mode's gestures on the Playlist. A long press on a clip opens
  15419. // its menu (FL's right click deletes: that stays on the mouse's right button), anywhere else it is the right click there
  15420. // (a header's menu, the ruler's); two fingers pan (Simple layout) and a pinch zooms the time around their centre.
  15421. void PlaylistComponent::touchLongPress (const juce::MouseEvent& rightClick)
  15422. {
  15423. bool right = false, left = false;
  15424. const auto hit = rightClick.x >= headerWidth ? clipAt (rightClick.x, rightClick.y, right, left) : -1;
  15425. if (hit >= 0)
  15426. {
  15427. lastTouchActionForSnapshot = "clip menu " + juce::String (hit);
  15428. if (! ui::showingForShots())
  15429. showClipMenu (hit);
  15430. return;
  15431. }
  15432. lastTouchActionForSnapshot = "right click";
  15433. const juce::Component::SafePointer<PlaylistComponent> safe (this);
  15434. mouseDown (rightClick);
  15435. if (safe != nullptr && drag != Drag::erase)
  15436. mouseUp (rightClick);
  15437. else if (safe != nullptr)
  15438. {
  15439. drag = Drag::none; // (an empty place: nothing to delete, the right drag ends here)
  15440. mouseUp (rightClick);
  15441. }
  15442. }
  15443. void PlaylistComponent::touchPan (float dx, float dy)
  15444. {
  15445. settleViewGlide(); // (rollup 0.1.32 step 2: 190pm's touch gestures land 190qe's zoom glide first, as the wheel and pinch do)
  15446. gliding = false;
  15447. scrollTicks = juce::jmax (0.0, scrollTicks - (double) dx / pixelsPerTick);
  15448. scrollY = juce::jmax (0, scrollY - juce::roundToInt (dy));
  15449. updateScrollBars();
  15450. repaint();
  15451. }
  15452. void PlaylistComponent::touchPinch (float scale, juce::Point<float> centre)
  15453. {
  15454. settleViewGlide(); // (rollup 0.1.32 step 2: 190pm's touch gestures land 190qe's zoom glide first, as the wheel and pinch do)
  15455. gliding = false;
  15456. const auto anchorPixels = (double) juce::jmax (0.0f, centre.x - (float) headerWidth);
  15457. const auto zoomed = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick * (double) scale);
  15458. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  15459. pixelsPerTick = zoomed;
  15460. zoomBeforeAll = 0.0;
  15461. updateScrollBars();
  15462. repaint();
  15463. }
  15464. void PlaylistComponent::mouseMagnify (const juce::MouseEvent& e, float scale)
  15465. {
  15466. gliding = false;
  15467. settleViewGlide(); // (round 190qe: a zoom glide lands first)
  15468. const auto factor = gesture::pinchZoomFactor (scale);
  15469. if (e.mods.isAltDown()) // the track heights, around the pointer
  15470. {
  15471. setTrackZoom (trackZoom * factor, e.y);
  15472. return;
  15473. }
  15474. const auto anchorPixels = (double) juce::jmax (0, e.x - headerWidth);
  15475. const auto zoomed = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick * factor);
  15476. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  15477. pixelsPerTick = zoomed;
  15478. zoomBeforeAll = 0.0;
  15479. updateScrollBars();
  15480. repaint();
  15481. }
  15482. void PlaylistComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& rawWheel)
  15483. {
  15484. const auto wheel = flmods::normalisedWheel (rawWheel); // Windows touchpads: pieces of a notch (round 170e)
  15485. const auto ctrl = flmods::ctrl (e.mods), alt = e.mods.isAltDown(), shift = e.mods.isShiftDown();
  15486. settleViewGlide(); // (round 190qe: a zoom glide lands first; the wheel goes on from there)
  15487. // FL's right-hold + wheel (round 190mp, DE-61; FL manual, captured in the Piano roll 190mp A3.3): over the clips each
  15488. // notch down picks the next tool to the right, up the one to the left (no wrap); the held press does nothing more
  15489. if (e.mods.isRightButtonDown() && ! e.mods.isLeftButtonDown() && ! e.mods.isMiddleButtonDown() && e.x >= headerWidth)
  15490. {
  15491. if (wheel.deltaY != 0.0f)
  15492. {
  15493. drag = Drag::none;
  15494. tools.step (wheel.deltaY < 0.0f ? 1 : -1);
  15495. }
  15496. return;
  15497. }
  15498. // issue #254 (round 190ou): a notch of the horizontal wheel (a tilt wheel, a second wheel) moves the view 1.5 beats
  15499. // sideways whatever the zoom, as in FL 2026 (a trackpad's swipe and Shift+wheel keep their own ways below)
  15500. if (! ctrl && ! alt)
  15501. if (const auto notch = gesture::horizontalWheelNotch (wheel.deltaX, wheel.deltaY, wheel.isSmooth, shift); notch != 0)
  15502. {
  15503. glideBy (notch * gesture::horizontalWheelBeats * ppq, 0.0);
  15504. return;
  15505. }
  15506. // issue #154: the wheel scrolls a linked header's effects list when it has more rows than fit
  15507. if (! shift && ! ctrl && ! alt && insertsWheel (e, wheel.deltaY))
  15508. return;
  15509. // Shift+wheel over a track header: moves the track up / down
  15510. if (shift && ! ctrl && e.x < headerWidth && e.y >= tracksTop() && wheel.deltaY != 0.0f)
  15511. {
  15512. const auto track = yToTrack (e.y);
  15513. const auto other = track + (wheel.deltaY > 0 ? -1 : 1);
  15514. if (other >= 0 && other < numTracks())
  15515. {
  15516. setSelection ({});
  15517. engine.editSong ([track, other] (Song& s) { noteedit::swapTracks (s, track, other); });
  15518. // the mouse follows the track, so the next wheel step moves it further
  15519. refreshTrackLayout();
  15520. juce::Desktop::setMousePosition (localPointToGlobal (juce::Point<int> (e.x, trackToY (other) + heightOf (other) / 2)));
  15521. }
  15522. return;
  15523. }
  15524. // FL's Edit › "Nudge clips with mouse wheel" (on by default; FUN_00e82270): Shift+wheel shifts the clips' content
  15525. if (shift && ! ctrl && ! alt && EditorGlobals::get().wheelNudging && gridArea().contains (e.getPosition()) && wheel.deltaY != 0.0f)
  15526. if (nudgeWithWheel (e.getPosition(), wheel.deltaY))
  15527. return;
  15528. if (shift && alt) // nudge the selected clips by the grid
  15529. {
  15530. if (wheel.deltaY != 0.0f && ! selection.empty())
  15531. {
  15532. const auto now = juce::Time::getMillisecondCounter();
  15533. const auto newBurst = now - lastWheelEdit > 700; // one undo step per burst
  15534. lastWheelEdit = now;
  15535. moveClips (selection, (wheel.deltaY > 0 ? 1 : -1) * gridTicks(), 0, newBurst, false); // (shared with Shift+arrows)
  15536. }
  15537. return;
  15538. }
  15539. if (alt && ! shift) // Alt+wheel (and Ctrl+Alt+wheel, as in the Piano Roll) zooms vertically: the track heights, around the mouse
  15540. {
  15541. gliding = false;
  15542. setTrackZoom (trackZoom * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth), e.y);
  15543. return;
  15544. }
  15545. // issue #186 (core/WheelZones.h, a LYNX extra, off by default): the plain wheel zooms over the arrangement and
  15546. // scrolls over the track headers; Ctrl does the other one. Off: Ctrl zooms, as in FL
  15547. if (wheelzones::zoomsHere (e.x < headerWidth, ctrl, wheel.deltaY != 0.0f))
  15548. {
  15549. gliding = false;
  15550. // (issue #276, round 190qr: the LYNX extra "Zoom around the song position" keeps the playhead in place instead)
  15551. const auto grid = gridArea();
  15552. const auto anchorPixels = zoomanchor::anchorX (zoomanchor::atSongPosition(), (double) juce::jmax (0, e.x - headerWidth),
  15553. tickToX ((double) songPositionTick()) - headerWidth, 0.0, (double) grid.getWidth());
  15554. const auto zoomed = juce::jlimit (4.0 / (4 * ppq), maxPixelsPerTick, pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  15555. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  15556. pixelsPerTick = zoomed;
  15557. zoomBeforeAll = 0.0;
  15558. updateScrollBars();
  15559. repaintZoomed();
  15560. return;
  15561. }
  15562. // plain wheel: up/down (Shift: left/right); a horizontal wheel or trackpad swipe scrolls sideways (a trackpad at once)
  15563. if (shift)
  15564. glideBy (gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 120.0) / pixelsPerTick, 0.0, wheel.isSmooth);
  15565. else
  15566. glideBy (gesture::wheelScrollPixels (wheel.deltaX, wheel.isSmooth, 80.0) / pixelsPerTick,
  15567. gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 2.0 * defaultRowHeight()), wheel.isSmooth);
  15568. }
  15569. bool PlaylistComponent::nudgeWithWheel (juce::Point<int> p, float deltaY)
  15570. {
  15571. // FL (FUN_00e82270, checked in FL 2026: "playlist shift clip" in the undo history): Shift+wheel shifts the CONTENT of
  15572. // the selected clips, or with none selected of the clip under the mouse, inside the clips' bounds: a notch is one
  15573. // pixel's worth of ticks at the current zoom (the PLForm's +0xb04, rounded), up = the content moves earlier. Over
  15574. // an empty part of the grid nothing happens and the wheel is still taken. One undo step per burst of the wheel.
  15575. const auto& song = engine.getSong();
  15576. std::vector<int> targets = selection;
  15577. if (targets.empty())
  15578. {
  15579. bool right = false, left = false;
  15580. if (const auto hit = clipAt (p.x, p.y, right, left); hit >= 0 && song.playlist[(std::size_t) hit].kind != ClipKind::automation)
  15581. targets = { hit };
  15582. else
  15583. return true;
  15584. }
  15585. const auto delta = (deltaY > 0 ? 1 : -1) * clipops::pixelStepTicks (pixelsPerTick);
  15586. const auto now = juce::Time::getMillisecondCounter();
  15587. const auto newBurst = now - lastWheelEdit > 700;
  15588. lastWheelEdit = now;
  15589. engine.editSong ([targets, delta] (Song& s) { clipops::shiftClipContent (s.playlist, targets, delta); }, newBurst);
  15590. return true;
  15591. }
  15592. void PlaylistComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
  15593. {
  15594. if (bar == &hBar)
  15595. scrollTicks = start;
  15596. else
  15597. scrollY = (int) start;
  15598. repaintScrolled();
  15599. }
  15600. void PlaylistComponent::changeListenerCallback (juce::ChangeBroadcaster* source)
  15601. {
  15602. updateDropLaneProbe();
  15603. if (source == ui::WaveformCache::getInstanceWithoutCreating())
  15604. {
  15605. repaint();
  15606. return;
  15607. }
  15608. // the clip list changed externally (undo, pattern removal...): the selection no longer applies
  15609. const auto count = engine.getSong().playlist.size();
  15610. // round 190rs (G-31, 190rl FIX-LIST 12): over an undo / redo the selection is found again by content — clips are
  15611. // re-sorted after a move, so by index it lit up other clips
  15612. if (engine.getSongStamp() != knownClipKeysStamp)
  15613. {
  15614. auto now = clipKeysInOrder();
  15615. if (engine.getHistoryStepStamp() > knownClipKeysStamp && knownClipKeysStamp != 0 && drag == Drag::none && ! selection.empty())
  15616. setSelection (selkeep::remap (knownClipKeys, selection, now)); // (sets knownClipCount)
  15617. knownClipKeys = std::move (now);
  15618. knownClipKeysStamp = engine.getSongStamp();
  15619. }
  15620. if (count != knownClipCount && drag == Drag::none)
  15621. {
  15622. knownClipCount = count;
  15623. selection.clear();
  15624. }
  15625. // switching pattern (top bar, Channel Rack) sets the pencil back to the pattern
  15626. if (engine.getSong().currentPattern != knownCurrentPattern)
  15627. {
  15628. knownCurrentPattern = engine.getSong().currentPattern;
  15629. // (a pattern clip clicked with the Pencil / Brush selected its pattern: it stays the template, issue #175)
  15630. const auto keep = brush.picked.has_value() && painttemplate::matches (*brush.picked, ClipKind::pattern, -1, knownCurrentPattern);
  15631. if (keep)
  15632. {
  15633. brush.kind = ClipKind::pattern;
  15634. brush.index = -1;
  15635. }
  15636. else
  15637. brush = {};
  15638. }
  15639. followButton.setToggleState (EditorGlobals::get().isFollowing (false), juce::dontSendNotification);
  15640. refreshArrangementBox();
  15641. foldLanesAfterOpen(); // round 190oo (CS O-3; nothing unless a project was just opened)
  15642. refreshTrackLayout();
  15643. updateHeaderWidth(); // round 190gz: the project's "Link Playlist tracks to mixer tracks" (menu, undo, another project)
  15644. if (engine.getSong().patternBlocksOn != blocksShown) // Pattern Blocks turned on / off (menu, undo, another project)
  15645. resized();
  15646. if (videoSectionHeight() != videoLanes->getHeight()) // video tracks added / removed / resized (round 174d)
  15647. resized();
  15648. else if (sectionsLaneHeight() != laidOutSectionsHeight) // round 190ol: the first section added, the last removed, undo
  15649. resized();
  15650. else if (chordLaneHeight() != laidOutChordHeight) // round 190pf: the Chord lane switched on / off
  15651. resized();
  15652. if (chordLane != nullptr && chordLane->isVisible())
  15653. chordLane->repaint(); // (its own picture is kept while the chords and the view stay the same)
  15654. blocksView->refresh();
  15655. videoLanes->refresh();
  15656. updateScrollBars();
  15657. repaint();
  15658. }
  15659. // Round 190im (R5, DC-7): the level behind a lit activity strip: the held level of the mixer tracks a playing clip goes
  15660. // to (an audio track's own mixer track; a pattern's channels' mixer tracks; an audio clip's channel's), read through the
  15661. // meters' fourth reader (MeterBank::takeActivityPeak) once per mixer track and frame. -1: the clip plays no audio
  15662. // (automation), lit at full brightness as FL lights it.
  15663. float PlaylistComponent::activityLevelOf (const Song& song, const Clip& c)
  15664. {
  15665. if (const auto stamp = engine.getPublishCount(); stamp != patternInsertsStamp)
  15666. {
  15667. patternInsertsStamp = stamp;
  15668. patternInserts.assign (song.patterns.size(), {});
  15669. for (std::size_t p = 0; p < song.patterns.size(); ++p)
  15670. {
  15671. auto& list = patternInserts[p];
  15672. for (const auto& n : song.patterns[p].notes)
  15673. if (n.channel >= 0 && n.channel < (int) song.channels.size())
  15674. list.push_back (song.channels[(std::size_t) n.channel].mixerTrack);
  15675. std::sort (list.begin(), list.end());
  15676. list.erase (std::unique (list.begin(), list.end()), list.end());
  15677. }
  15678. }
  15679. auto level = -1.0f;
  15680. auto read = [&] (int insert) {
  15681. if (insert < 0 || insert >= maxMixerTracks)
  15682. return;
  15683. auto& held = activityInsertLevels[insert];
  15684. if (held.second != activityFrame) // (once per frame: the held level falls ~20 dB a second, a peak lifts it at once)
  15685. {
  15686. auto& bank = engine.getMeters();
  15687. const auto peak = juce::jmax (bank.takeActivityPeak (insert, 0), bank.takeActivityPeak (insert, 1));
  15688. held = { juce::jmax (peak, held.first * ui::fallFor (0.92f, activityElapsedMs)), activityFrame };
  15689. }
  15690. level = juce::jmax (level, held.first);
  15691. };
  15692. const auto linked = c.track >= 0 && c.track < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) c.track].mixerTrack : -1;
  15693. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) patternInserts.size())
  15694. for (const auto insert : patternInserts[(std::size_t) c.pattern])
  15695. read (insert);
  15696. else if (c.kind == ClipKind::audio)
  15697. read (linked >= 0 ? linked : c.channel >= 0 && c.channel < (int) song.channels.size() ? song.channels[(std::size_t) c.channel].mixerTrack : -1);
  15698. return level;
  15699. }
  15700. // Rollup 0.1.30 (190im's perf question, its option (b)): the activity strips' level steps (DC-7) on, or the strips lit /
  15701. // dark only (round 190ig's look: a lit strip at step 4). LYNX_ACTIVITY_STEPS=0 / 1 picks one for an A/B measure.
  15702. static bool activityLevelSteps()
  15703. {
  15704. static const bool on = juce::SystemStats::getEnvironmentVariable ("LYNX_ACTIVITY_STEPS", "1") != "0";
  15705. return on;
  15706. }
  15707. // (rollup 0.1.30) `c` or one of its parents lies wholly under a later, visible, opaque sibling (a maximised panel's
  15708. // frame): repainting it would only make that sibling paint again
  15709. static bool hiddenBehindOpaque (const juce::Component& c)
  15710. {
  15711. for (const auto* a = &c; a->getParentComponent() != nullptr; a = a->getParentComponent())
  15712. {
  15713. const auto* parent = a->getParentComponent();
  15714. for (int i = parent->getIndexOfChildComponent (a) + 1; i < parent->getNumChildComponents(); ++i)
  15715. if (const auto* s = parent->getChildComponent (i); s->isVisible() && s->isOpaque() && s->getBounds().contains (a->getBounds()))
  15716. return true;
  15717. }
  15718. return false;
  15719. }
  15720. // the strip's brightness step 1..4 for a level (-1: no audio, full)
  15721. static char activityStepOf (float level)
  15722. {
  15723. if (level < 0.0f)
  15724. return 4;
  15725. const auto db = juce::Decibels::gainToDecibels (level, -100.0f);
  15726. return (char) (db > -9.0f ? 4 : db > -18.0f ? 3 : db > -30.0f ? 2 : 1);
  15727. }
  15728. bool PlaylistComponent::playheadTrailOn() const
  15729. {
  15730. return ui::motion::enabled() && engine.getTransport().playing.load (std::memory_order_relaxed) && playheadTick >= 0.0;
  15731. }
  15732. // The screen's pixels per component pixel (the window's DPI scale x the desktop scale x any transform): the scale the cached
  15733. // picture is drawn at. (getApproximateScaleFactorForComponent alone leaves out the peer's DPI scale and divides the global
  15734. // scale back out: 1 at Windows' 150 % and at LYNX_UIPERF_SCALE=150.)
  15735. static double screenPixelScale (const juce::Component& c)
  15736. {
  15737. const auto* peer = c.getPeer();
  15738. return (double) juce::Component::getApproximateScaleFactorForComponent (&c) * (double) juce::Desktop::getInstance().getGlobalScaleFactor()
  15739. * (peer != nullptr ? peer->getPlatformScaleFactor() : 1.0);
  15740. }
  15741. bool PlaylistComponent::liveFrame (double nowMs)
  15742. {
  15743. const auto feel = feelFrame (nowMs); // round 190qe: the edge scroll of a drag, the zoom glide
  15744. auto& transport = engine.getTransport();
  15745. const auto& song = engine.getSong();
  15746. const auto playing = transport.playing.load();
  15747. // round 190im (R15): a scroll by hand while playing (the view moved sideways at the same zoom, not by Follow) pauses
  15748. // Follow; a play or a stop lifts the pause
  15749. auto& globals = EditorGlobals::get();
  15750. globals.noteTransport (playing);
  15751. if (playing && scrollTicks != followSeenScroll && pixelsPerTick == followSeenZoom)
  15752. globals.pauseFollowForScroll (EditorGlobals::FollowView::playlist);
  15753. followSeenScroll = scrollTicks;
  15754. followSeenZoom = pixelsPerTick;
  15755. auto tick = -1.0;
  15756. // (between two audio blocks the playhead moves on at the song's tempo: smooth at 144 Hz, round 174e)
  15757. if (song.mode == PlayMode::song && (playing || transport.positionTicks.load() > 0.0))
  15758. tick = engine.songPlayheadTicks() + engine.playheadAdvanceTicks();
  15759. // whenever it moved: the line is anti-aliased, so even a fraction of a pixel shows (zoomed out, a playhead crossing
  15760. // a few pixels a second glides at the display's rate instead of stepping, as FL's does)
  15761. const auto moved = (tick < 0.0) != (playheadTick < 0.0) || std::abs ((tick - playheadTick) * pixelsPerTick) >= 0.002;
  15762. // round 190im (R5, DC-5): the glow trail behind the line while playing (Animations on); its own repaint when it
  15763. // comes or goes without the line moving (Stop: the line stays, the trail goes)
  15764. const auto trail = playheadTrailOn();
  15765. const auto trailFlip = trail != trailShown;
  15766. trailShown = trail;
  15767. // round 190ip: stopped, the playhead is painted again (pixel-identical when nothing moves); the overlay goes a few
  15768. // frames later, once that paint is on screen
  15769. if (gpuPlayhead.isShowing() && (! playing || ! isShowing()))
  15770. {
  15771. gpuPlayhead.hide (isShowing()); // (no longer shown: at once)
  15772. repaintPlayheadColumn (playheadTick);
  15773. }
  15774. if ((moved || trailFlip) && ui::showingOrShot (*this))
  15775. {
  15776. // only the cursor column (old and new) is repainted: large projects stay cheap. One rectangle for both: the
  15777. // two strips overlap (a frame moves the line by a pixel or less), and each rectangle of a repaint is a paint
  15778. // (round 190im: the column reaches the trail's width left of the line while it shows)
  15779. const auto left = trail || trailFlip ? 8 + playheadTrail : 8;
  15780. auto column = [this, left] (double t) { return playheadColumn (t, left); };
  15781. auto dirty = [this] (juce::Rectangle<int> r) {
  15782. if (r.isEmpty())
  15783. return;
  15784. playheadRepaintOnly = playheadOverlay; // (the cached image under it stays valid)
  15785. repaint (r);
  15786. playheadRepaintOnly = false;
  15787. };
  15788. const auto before = column (playheadTick);
  15789. playheadTick = tick;
  15790. // while playing the GPU moves it (nothing under it is painted); the frame it starts or stops doing so, the
  15791. // columns are painted once (the painted line goes, or comes back)
  15792. const auto gpu = ui::stepMark (gpuPlayhead, playing && tick >= 0.0, playheadMark(), tick >= 0.0);
  15793. // Follow: if the cursor leaves the screen while playing, scrolls one page (off: the view stays put)
  15794. const auto grid = gridArea();
  15795. // PR #308, FL's Continuous scrolling: the playhead held at a third of the grid. Only with a playhead (Pattern mode
  15796. // has none here: the view stays put, as with the option off), and in whole steps of the screen's pixels (2 px at
  15797. // 150 %), so the cached picture is shifted and only the uncovered strip is painted (repaintScrolled)
  15798. const auto continuous = EditorGlobals::get().isContinuousScroll() && tick >= 0.0;
  15799. const auto quantum = continuous ? (double) edgescroll::wholeQuantum (screenPixelScale (*this)) : 1.0;
  15800. const auto newStart = continuous ? transportedit::followViewStartContinuous (tick, grid.getWidth() / 3.0 / pixelsPerTick, pixelsPerTick / quantum)
  15801. : transportedit::followViewStart (scrollTicks, grid.getWidth() / pixelsPerTick, tick, 20.0 / pixelsPerTick,
  15802. 20.0 / pixelsPerTick);
  15803. if (EditorGlobals::get().followsNow (EditorGlobals::FollowView::playlist) && playing && newStart != scrollTicks)
  15804. {
  15805. scrollTicks = newStart;
  15806. followSeenScroll = scrollTicks; // (round 190im: not a scroll by hand)
  15807. updateScrollBars();
  15808. if (continuous)
  15809. repaintScrolled();
  15810. else
  15811. repaint();
  15812. if (gpuPlayhead.isShowing())
  15813. gpuPlayhead.show (playheadMark()); // (at its place in the new page)
  15814. }
  15815. else if (gpu.onOverlay && ! gpu.flipped)
  15816. {
  15817. // (the GPU moved it: nothing under it is painted)
  15818. }
  15819. else if (const auto after = column (tick); ! before.isEmpty() && ! after.isEmpty() && std::abs (after.getX() - before.getX()) <= 16)
  15820. dirty (before.getUnion (after));
  15821. else
  15822. {
  15823. dirty (before);
  15824. dirty (after);
  15825. }
  15826. }
  15827. else if (moved)
  15828. playheadTick = tick;
  15829. // rollup 0.1.30 (step 3 perf): a Playlist behind a maximised panel (Piano roll, Channel rack, Mixer) is still
  15830. // "showing"; a repaint of its covered parts makes the opaque panel in front paint that area again (measured: +5
  15831. // window frames a second and the message thread 3.6 -> 17 % with the Piano roll or the Channel rack maximised, from
  15832. // the overview's position line). The live parts below stand still while it is covered.
  15833. const auto seen = ui::showingOrShot (*this) && ! hiddenBehindOpaque (*this);
  15834. // round 190im (R5, DC-6): the song position in the overview strip while playing (none when stopped, as FL)
  15835. overview.setPosition (playing && seen ? tick : -1.0);
  15836. // round 190ig (FM-28): FL's activity column beside the headers — a track's strip lit while a clip of it plays under the
  15837. // playhead; only the strips that flip are repainted, nothing runs while stopped once they are dark
  15838. // round 190im (R5, DC-3): the same pass finds the patterns that play, for the picker's marks
  15839. const auto pickerShown = livePicker != nullptr && ui::showingOrShot (*livePicker) && ! hiddenBehindOpaque (*livePicker);
  15840. if ((flHeaders() && seen && (playing || ! activityShown.empty())) || (pickerShown && (playing || ! livePicker->playingPatterns.empty())))
  15841. {
  15842. std::vector<char> now;
  15843. std::vector<int> patternsNow;
  15844. if (playing && tick >= 0.0)
  15845. {
  15846. // (round 190im, DC-7: the brightness steps follow the level 15 times a second — a strip that lights or goes
  15847. // dark does so at once — so the strips' repaints stay few beside the playhead's column)
  15848. const auto levelsDue = activityMs < 0.0 || nowMs - activityMs >= 1000.0 / 15.0;
  15849. if (levelsDue)
  15850. {
  15851. ++activityFrame;
  15852. activityElapsedMs = activityMs < 0.0 ? 1000.0 / 60.0 : juce::jlimit (0.0, 1000.0, nowMs - activityMs);
  15853. activityMs = nowMs;
  15854. }
  15855. now.assign ((std::size_t) numTracks(), 0);
  15856. std::vector<float> levels (now.size(), -2.0f); // (-2: dark; -1: lit by a clip without audio)
  15857. const auto strips = flHeaders() && activityLevelSteps(); // (off: lit / dark only, no level reads)
  15858. for (const auto& c : song.playlist)
  15859. if (! c.muted && c.track >= 0 && c.track < (int) now.size() && (double) c.start <= tick && tick < (double) c.end())
  15860. {
  15861. auto& l = levels[(std::size_t) c.track];
  15862. if (strips && levelsDue) // (round 190im, DC-7: the brightness step from the level of what the track plays)
  15863. {
  15864. const auto own = activityLevelOf (song, c);
  15865. l = l < -1.5f ? own : juce::jmax (own, l); // (a level ≥ 0 beats -1)
  15866. }
  15867. else
  15868. l = juce::jmax (l, -1.0f);
  15869. if (c.kind == ClipKind::pattern && pickerShown)
  15870. patternsNow.push_back (c.pattern);
  15871. }
  15872. for (std::size_t t = 0; t < now.size(); ++t)
  15873. if (levels[t] > -1.5f)
  15874. now[t] = strips && ! levelsDue && t < activityShown.size() && activityShown[t] != 0 ? activityShown[t] : activityStepOf (levels[t]);
  15875. }
  15876. else if (playing && song.mode == PlayMode::pattern && pickerShown) // (Pattern mode: the current pattern plays)
  15877. patternsNow.push_back (song.currentPattern);
  15878. if (! (playing && tick >= 0.0))
  15879. activityMs = -1.0;
  15880. if (pickerShown)
  15881. {
  15882. std::sort (patternsNow.begin(), patternsNow.end());
  15883. patternsNow.erase (std::unique (patternsNow.begin(), patternsNow.end()), patternsNow.end());
  15884. livePicker->setPlayingPatterns (std::move (patternsNow));
  15885. }
  15886. if (! (flHeaders() && seen))
  15887. now.clear();
  15888. const auto count = std::max (now.size(), activityShown.size());
  15889. for (std::size_t t = 0; t < count; ++t)
  15890. {
  15891. const auto was = t < activityShown.size() ? activityShown[t] : (char) 0, is = t < now.size() ? now[t] : (char) 0;
  15892. if (was != is && (int) t < numTracks())
  15893. repaint (headerWidth - trackhdr::selectionStripWidth, trackToY ((int) t), trackhdr::selectionStripWidth, heightOf ((int) t));
  15894. }
  15895. activityShown = std::move (now);
  15896. }
  15897. // Performance mode: the launched and waiting clips (frames, progress) and the headers' track progress
  15898. auto live = false;
  15899. if (song.performanceMode && isShowing())
  15900. {
  15901. const auto& perfState = engine.performanceState();
  15902. const auto zoneEnd = song.performanceZoneEnd();
  15903. auto changed = false;
  15904. for (int t = 0; t < (int) perfShown.size(); ++t)
  15905. {
  15906. const auto v = perfState.tracks[(std::size_t) t].playing.load (std::memory_order_relaxed) * 2 + 1
  15907. + (perfState.tracks[(std::size_t) t].pending.load (std::memory_order_relaxed) + 1) * 7919;
  15908. if (v != perfShown[(std::size_t) t])
  15909. {
  15910. perfShown[(std::size_t) t] = v;
  15911. changed = true;
  15912. }
  15913. }
  15914. live = perfState.anyPlaying.load (std::memory_order_relaxed);
  15915. // (the clips' progress and the waiting clips' blink cover the whole zone: 30 times a second, as before)
  15916. const auto due = live && nowMs - perfRepaintMs >= 1000.0 / 30.0;
  15917. if (zoneEnd > 0 && (changed || due))
  15918. {
  15919. perfRepaintMs = nowMs;
  15920. const auto grid = gridArea();
  15921. const auto x1 = juce::jmin (grid.getRight(), (int) tickToX ((double) zoneEnd) + 2);
  15922. if (x1 > grid.getX())
  15923. repaint (juce::Rectangle<int> (grid.getX(), grid.getY(), x1 - grid.getX(), grid.getHeight()));
  15924. if (showTrackProgress)
  15925. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  15926. }
  15927. }
  15928. // round 190w: the track headers' level meters
  15929. if (stepHeaderMeters (nowMs))
  15930. live = true;
  15931. // round 177d: a recording in progress grows on its tracks (its rows, from where it starts to the playhead; 30 Hz)
  15932. if (engine.isLiveRecording() && isShowing())
  15933. {
  15934. if (nowMs - liveRepaintMs >= 1000.0 / 30.0)
  15935. {
  15936. liveRepaintMs = nowMs;
  15937. const auto rec = engine.liveRecording();
  15938. juce::Rectangle<float> area;
  15939. for (const auto& a : rec.audio)
  15940. area = area.getUnion (liveBounds (a.track, a.span.start, a.span.start + a.span.length).expanded (2.0f, 1.0f));
  15941. if (rec.notes && rec.track >= 0)
  15942. area = area.getUnion (liveBounds (rec.track, (double) rec.from, (double) rec.to + 16.0 / pixelsPerTick).expanded (2.0f, 1.0f));
  15943. const auto now = area.getSmallestIntegerContainer();
  15944. const auto dirty = now.getUnion (liveArea).getIntersection (gridArea());
  15945. liveArea = now;
  15946. if (! dirty.isEmpty())
  15947. repaint (dirty);
  15948. }
  15949. return true;
  15950. }
  15951. if (! liveArea.isEmpty())
  15952. {
  15953. repaint (liveArea);
  15954. liveArea = {};
  15955. }
  15956. return playing || moved || live || feel;
  15957. }
  15958. // Round 190w: FL 2026's track header levels (Playlist menu › View › Track headers [DFM] EEShowAudioTrackMetersAction
  15959. // Checked=true, EEShowInstrumentTrackMetersAction unchecked; [SHOT] flgap190w/shots/fl p1-p3, b4, c4: a stereo peak
  15960. // meter with hold lines in a narrow column right of the header, on every row height).
  15961. int PlaylistComponent::meteredInsertOf (int track) const
  15962. {
  15963. trackmodes::HeaderOptions o;
  15964. o.audioControls = showAudioTrackControls;
  15965. o.audioLevels = showAudioTrackLevels;
  15966. o.instrumentLevels = showInstrumentTrackLevels;
  15967. if (noteedit::isFoldedAway (engine.getSong(), track))
  15968. return -1;
  15969. return trackmodes::meteredInsert (engine.getSong(), track, o);
  15970. }
  15971. bool PlaylistComponent::updateMeterColumn()
  15972. {
  15973. auto any = false;
  15974. if (showAudioTrackLevels || showInstrumentTrackLevels)
  15975. for (int t = 0, n = (int) engine.getSong().playlistTracks.size(); t < n && ! any; ++t)
  15976. any = meteredInsertOf (t) >= 0;
  15977. const auto width = any ? 9 : 0;
  15978. if (width == meterColumn)
  15979. return false;
  15980. meterColumn = width;
  15981. if (! any)
  15982. headerLevels.clear();
  15983. return true;
  15984. }
  15985. bool PlaylistComponent::stepHeaderMeters (double nowMs)
  15986. {
  15987. if (updateMeterColumn())
  15988. repaint (0, tracksTop(), headerWidth, getHeight() - tracksTop());
  15989. if (meterColumn == 0 || ! isShowing())
  15990. {
  15991. headerMeterMs = -1.0;
  15992. return false;
  15993. }
  15994. const auto elapsed = headerMeterMs < 0.0 ? 1000.0 / 60.0 : juce::jlimit (0.0, 1000.0, nowMs - headerMeterMs);
  15995. headerMeterMs = nowMs;
  15996. auto& bank = engine.getMeters();
  15997. const auto grid = gridArea();
  15998. auto moving = false;
  15999. std::map<int, std::array<meters::PeakHold, 2>> next;
  16000. juce::Rectangle<int> dirty;
  16001. for (int t = 0, n = numTracks(); t < n; ++t)
  16002. {
  16003. const auto insert = meteredInsertOf (t);
  16004. if (insert < 0)
  16005. continue;
  16006. if (next.find (insert) == next.end())
  16007. {
  16008. auto levels = headerLevels.count (insert) > 0 ? headerLevels[insert] : std::array<meters::PeakHold, 2> {};
  16009. for (int side = 0; side < 2; ++side)
  16010. levels[(std::size_t) side].advance (bank.takeViewPeak (insert, side), elapsed);
  16011. moving = moving || levels[0].level > 0.0f || levels[1].level > 0.0f || levels[0].peak > 0.0f || levels[1].peak > 0.0f;
  16012. next[insert] = levels;
  16013. }
  16014. const auto y = trackToY (t), h = heightOf (t);
  16015. if (y + h >= grid.getY() && y <= grid.getBottom())
  16016. {
  16017. const auto& before = headerLevels.count (insert) > 0 ? headerLevels[insert] : std::array<meters::PeakHold, 2> {};
  16018. const auto& after = next[insert];
  16019. if (before[0].level != after[0].level || before[1].level != after[1].level || before[0].peak != after[0].peak
  16020. || before[1].peak != after[1].peak)
  16021. dirty = dirty.getUnion (juce::Rectangle<int> (headerWidth - rightColumn(), y, rightColumn(), h));
  16022. }
  16023. }
  16024. headerLevels = std::move (next);
  16025. if (! dirty.isEmpty())
  16026. repaint (dirty.getIntersection (juce::Rectangle<int> (0, tracksTop(), headerWidth, getHeight() - tracksTop())));
  16027. return moving;
  16028. }
  16029. void PlaylistComponent::headerOptionsChanged()
  16030. {
  16031. updateMeterColumn();
  16032. refreshTrackLayout(); // (round 190jf: "Hide collapsed grouped tracks" changes the rows' heights)
  16033. updateScrollBars();
  16034. repaint();
  16035. if (onViewOptionChanged)
  16036. onViewOptionChanged();
  16037. }
  16038. // Round 177d: the recording in progress, live (MusicTech's FL 2025 review: recorded MIDI is not shown in the Playlist
  16039. // while recording, audio recording "unintuitive"). Each audio take is a growing clip with its waveform on the track it
  16040. // will land on; a Song-mode note take is a frame over the range it covers so far (its clip, placed with the first
  16041. // released note, and where it will grow to), with the notes still held. At the stop they become the real clips.
  16042. juce::Rectangle<float> PlaylistComponent::liveBounds (int track, double from, double to) const
  16043. {
  16044. if (track < 0 || track >= numTracks() || to <= from)
  16045. return {};
  16046. const auto x0 = (float) tickToX (from), x1 = (float) tickToX (to);
  16047. return { x0, (float) trackToY (track) + 1.0f, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) heightOf (track) - 3.0f };
  16048. }
  16049. void PlaylistComponent::paintLiveRecording (juce::Graphics& g)
  16050. {
  16051. using namespace theme;
  16052. const auto live = engine.liveRecording();
  16053. const auto& song = engine.getSong();
  16054. const auto visible = g.getClipBounds().toFloat();
  16055. for (const auto& a : live.audio)
  16056. {
  16057. auto from = a.span.start, to = a.span.start + a.span.length;
  16058. if (live.punch.has_value()) // (only the punch range is kept)
  16059. {
  16060. from = juce::jmax (from, (double) live.punch->in);
  16061. to = juce::jmin (to, (double) live.punch->out);
  16062. }
  16063. const auto r = liveBounds (a.track, from, to);
  16064. if (r.isEmpty() || ! r.intersects (visible))
  16065. continue;
  16066. const auto body = paintClipFrame (g, r, colour::accent, a.name, ClipGlyph::audio);
  16067. const auto wave = body.reduced (0.0f, body.getHeight() >= 14.0f ? 2.0f : 1.0f).getIntersection (visible);
  16068. if (a.peaks == nullptr || wave.getWidth() < 1.0f || wave.getHeight() < 2.0f || a.span.ticksPerSample <= 0.0)
  16069. continue;
  16070. // one value per pixel column, read under one lock
  16071. const auto columns = (int) std::ceil (wave.getWidth());
  16072. liveColumns.resize ((std::size_t) columns);
  16073. const auto framesPerPixel = 1.0 / (pixelsPerTick * a.span.ticksPerSample);
  16074. const auto firstFrame = a.span.firstFrame + (xToTick ((int) wave.getX()) - a.span.start) / a.span.ticksPerSample;
  16075. a.peaks->read (firstFrame, framesPerPixel, columns, liveColumns.data());
  16076. juce::RectangleList<float> bars;
  16077. const auto mid = wave.getCentreY(), half = wave.getHeight() * 0.5f;
  16078. for (int k = 0; k < columns; ++k)
  16079. if (const auto h = juce::jmin (1.0f, liveColumns[(std::size_t) k]) * half; h > 0.0f)
  16080. bars.addWithoutMerging ({ wave.getX() + (float) k, mid - h, 1.0f, juce::jmax (1.0f, 2.0f * h) });
  16081. g.setColour (clipContentColour (colour::accent));
  16082. g.fillRectList (bars);
  16083. g.fillRect (wave.getX(), mid - 0.5f, wave.getWidth(), 1.0f); // the zero line, as far as the take has come
  16084. }
  16085. if (live.notes && live.track >= 0 && live.to > live.from)
  16086. {
  16087. const auto r = liveBounds (live.track, (double) live.from, (double) live.to);
  16088. if (r.isEmpty() || ! r.intersects (visible))
  16089. return;
  16090. g.setColour (colour::accent.withAlpha (0.10f));
  16091. g.fillRoundedRectangle (r, radius::sm);
  16092. g.setColour (colour::accent.withAlpha (0.85f));
  16093. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, 1.5f);
  16094. if (live.held.empty() || live.pattern < 0 || live.pattern >= (int) song.patterns.size())
  16095. return;
  16096. // the held notes at their pitch, in the pattern's key range (as the clip draws its notes)
  16097. int low = 127, high = 0;
  16098. for (const auto& n : song.patterns[(std::size_t) live.pattern].notes)
  16099. low = juce::jmin (low, n.key), high = juce::jmax (high, n.key);
  16100. for (const auto& n : live.held)
  16101. low = juce::jmin (low, n.key), high = juce::jmax (high, n.key);
  16102. const auto inner = r.withTrimmedTop (clipHeaderHeight (r)).reduced (0.0f, 3.0f);
  16103. const auto span = juce::jmax (6, high - low + 2);
  16104. const auto bottomKey = (low + high) / 2.0f - span / 2.0f;
  16105. const auto rows = (float) span + 1.0f;
  16106. const auto noteHeight = juce::jlimit (1.5f, 3.0f, inner.getHeight() / rows);
  16107. g.setColour (colour::accent.brighter (0.35f));
  16108. for (const auto& n : live.held)
  16109. {
  16110. const auto at = (double) (live.origin + n.start);
  16111. const auto nx = (float) tickToX (at);
  16112. const auto nw = juce::jmax (2.0f, (float) (n.length * pixelsPerTick) - 1.0f);
  16113. const auto ny = inner.getBottom() - ((float) n.key - bottomKey + 0.5f) / rows * inner.getHeight() - noteHeight * 0.5f;
  16114. g.fillRect (nx, ny, nw, noteHeight);
  16115. }
  16116. }
  16117. }
  16118. // Performance mode (round 165m): the launched clips (a bright frame and, with "Performance clip progress", how far the
  16119. // pass has gone), the clips waiting for their sync point (a blinking frame) and, with "Performance track progress",
  16120. // the playing clip's progress on the track header.
  16121. void PlaylistComponent::paintPerformance (juce::Graphics& g, juce::Rectangle<int> grid)
  16122. {
  16123. using namespace theme;
  16124. const auto& song = engine.getSong();
  16125. const auto& live = engine.performanceState();
  16126. const auto zoneEnd = song.performanceZoneEnd();
  16127. const auto any = live.anyPlaying.load (std::memory_order_relaxed);
  16128. const auto blink = 0.45f + 0.45f * std::sin ((float) juce::Time::getMillisecondCounter() * 0.012f);
  16129. for (int i = 0; i < (int) song.playlist.size(); ++i)
  16130. {
  16131. const auto& c = song.playlist[(std::size_t) i];
  16132. if (c.start >= zoneEnd || c.track < 0 || c.track >= perf::maxTracks)
  16133. continue;
  16134. const auto& view = live.tracks[(std::size_t) c.track];
  16135. const auto playing = any && view.playing.load (std::memory_order_relaxed) == c.start;
  16136. const auto pending = any && view.pending.load (std::memory_order_relaxed) == c.start;
  16137. const auto r = clipBounds (i).toFloat();
  16138. if (! r.intersects (grid.toFloat()))
  16139. continue;
  16140. if (! playing && ! pending)
  16141. {
  16142. // as in FL, the zone's idle clips are dimmed: what plays stands out
  16143. g.setColour (colour::bg0.withAlpha (0.42f));
  16144. g.fillRoundedRectangle (r, radius::sm);
  16145. continue;
  16146. }
  16147. if (playing)
  16148. {
  16149. // a play mark at its left edge (FL: ▸) besides the bright frame
  16150. juce::Path mark;
  16151. const auto mx = r.getX() + 5.0f, my = r.getCentreY() + 3.0f;
  16152. mark.addTriangle (mx, my - 4.0f, mx, my + 4.0f, mx + 6.0f, my);
  16153. g.setColour (colour::ledOn);
  16154. g.fillPath (mark);
  16155. g.setColour (colour::ledOn);
  16156. g.drawRoundedRectangle (r.reduced (1.0f), radius::sm, 2.0f);
  16157. if (showClipProgress)
  16158. {
  16159. // as in FL, the part already played is lighter, up to a thin playhead line
  16160. const auto p = juce::jlimit (0.0f, 1.0f, view.progress.load (std::memory_order_relaxed));
  16161. const auto played = r.reduced (1.0f).withWidth (juce::jmax (0.0f, (r.getWidth() - 2.0f) * p));
  16162. g.setColour (colour::textPrimary.withAlpha (0.16f));
  16163. g.fillRect (played);
  16164. g.setColour (colour::ledOn.withAlpha (0.85f));
  16165. g.fillRect (played.withX (played.getRight() - 1.0f).withWidth (1.5f));
  16166. }
  16167. }
  16168. if (pending)
  16169. {
  16170. g.setColour (colour::warning.withAlpha (blink));
  16171. g.drawRoundedRectangle (r.reduced (1.0f), radius::sm, 2.0f);
  16172. }
  16173. }
  16174. (void) showTrackProgress; // (drawn on the headers: paintOverChildren)
  16175. }
  16176. void PlaylistComponent::togglePerformanceMode()
  16177. {
  16178. const auto on = ! engine.getSong().performanceMode;
  16179. engine.editSong ([on] (Song& s) { s.performanceMode = on; });
  16180. if (on && engine.getSong().performanceZoneEnd() <= 0)
  16181. ui::postHint ({ tr ("Performance mode: put a Start marker where the song starts (right-click the ruler); the clips before it are launched with a click while playing"), {} }, 6000);
  16182. repaint();
  16183. }
  16184. void PlaylistComponent::zoomOnPerformanceClips()
  16185. {
  16186. const auto end = engine.getSong().performanceZoneEnd();
  16187. if (end > 0)
  16188. zoomToTicks (0.0, (double) end);
  16189. }
  16190. bool PlaylistComponent::isInterestedInDragSource (const SourceDetails& details)
  16191. {
  16192. int gridTrack = 0, gridScene = 0;
  16193. auto pickerKind = ClipKind::pattern;
  16194. std::vector<int> pickerEntries;
  16195. return BrowserComponent::isBrowserDrag (details) || BrowserComponent::draggedPattern (details) >= 0
  16196. || clipGridDrag (details.description, gridTrack, gridScene) || pickerDrag (details.description, pickerKind, pickerEntries)
  16197. || (! simpleHeaders && (BrowserComponent::isGeneratorDrag (details) || BrowserComponent::isEffectDrag (details))) // (issue #152.6)
  16198. || (simpleHeaders && onSimpleSoundDropped && BrowserComponent::isGeneratorDrag (details)); // (round 190sa: BandLab)
  16199. }
  16200. // Round 190sa (Q1 G-S1, BandLab: a loop dropped on the timeline becomes a track with its region where it was dropped): a
  16201. // sound dropped anywhere on the Simple timeline is a new instrument track, as its double-click makes, with its first
  16202. // (empty, four-bar) clip at the bar it was dropped on; on the track headers, at the song's start. Effects stay refused.
  16203. void PlaylistComponent::simpleSoundDropped (const SourceDetails& details)
  16204. {
  16205. const auto p = details.localPosition;
  16206. if (p.y < tracksTop() || p.y >= gridArea().getBottom() || p.x >= gridArea().getRight() || ! onSimpleSoundDropped)
  16207. return;
  16208. auto generator = BrowserComponent::draggedGenerator (details);
  16209. if (! generator)
  16210. return;
  16211. const auto tick = p.x >= headerWidth ? juce::jmax<std::int64_t> (0, snap (xToTick (p.x), true)) : (std::int64_t) 0;
  16212. onSimpleSoundDropped (std::move (*generator), details.description.toString().fromFirstOccurrenceOf ("|", false, false), tick);
  16213. }
  16214. void PlaylistComponent::pluginDropped (const SourceDetails& details)
  16215. {
  16216. const auto p = details.localPosition;
  16217. auto generator = BrowserComponent::draggedGenerator (details);
  16218. auto fx = generator ? std::optional<EffectSlot>() : BrowserComponent::draggedEffect (details);
  16219. if (! generator && ! fx)
  16220. return;
  16221. if (layoutstyle::current() == layoutstyle::Style::clipLaunch)
  16222. {
  16223. // Live (DROP-FACTS C): a device dropped on an Arrangement track goes into that track as in the Session view;
  16224. // below the last track (Live's drop area) a new track holds it
  16225. if (p.y < tracksTop() || p.y >= gridArea().getBottom())
  16226. return;
  16227. auto track = yToTrack (p.y);
  16228. if (track < 0)
  16229. track = trackmodes::firstFreeTrack (engine.getSong());
  16230. if (track < 0)
  16231. return;
  16232. auto apply = [&] (Song& song) {
  16233. return generator ? plugindrop::instrumentOnSessionTrack (song, *generator, track) : plugindrop::effectOnSessionTrack (song, *fx, track);
  16234. };
  16235. auto trial = engine.getSong(); // (a refused drop leaves no undo step)
  16236. if (const auto check = apply (trial); ! check.ok())
  16237. {
  16238. ui::postHint ({ plugindropui::message (check.error), {} }, 4000);
  16239. return;
  16240. }
  16241. plugindrop::Result r;
  16242. engine.editSong ([&] (Song& song) { r = apply (song); });
  16243. selectTrack (track);
  16244. if (generator && ! r.replaced && onGeneratorAdded && ! r.channels.empty())
  16245. onGeneratorAdded (r.channels.front(), engine.getSong().channels[(std::size_t) r.channels.front()].instrument);
  16246. repaint();
  16247. return;
  16248. }
  16249. // FL (DROP-FACTS A/B, 0xe7a470): a plugin is taken only over the track-header column; on the lanes nothing happens
  16250. if (p.x >= headerWidth || p.y < tracksTop() || p.y >= gridArea().getBottom())
  16251. return;
  16252. const auto track = yToTrack (p.y);
  16253. if (track < 0)
  16254. return;
  16255. // issue #154 (LYNX extra): an effect dropped on a linked header's effects list goes in where it is dropped
  16256. if (fx && insertsDrop (track, p, *fx))
  16257. {
  16258. repaint();
  16259. return;
  16260. }
  16261. const auto shift = juce::ModifierKeys::currentModifiers.isShiftDown();
  16262. if (generator)
  16263. {
  16264. // the header under the mouse becomes the only selected track unless it is one of them; then every selected
  16265. // track takes the plugin (0xe79d60 -> 0x12ebbd0)
  16266. if (! isTrackSelected (track))
  16267. selectTrack (track);
  16268. auto tracks = plugindrop::generatorTargets (track, tracksForMenu (track));
  16269. if ((int) tracks.size() > plugindrop::maxInstrumentsAtOnce)
  16270. {
  16271. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  16272. plugindropui::message (plugindrop::Error::tooMany));
  16273. return;
  16274. }
  16275. if ((int) tracks.size() > plugindrop::askAboveInstruments)
  16276. {
  16277. const auto count = (int) tracks.size();
  16278. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("Potentially slow operation"),
  16279. tr ("Are you sure you want to load {0} plugins at once?", { juce::String (count) }),
  16280. tr ("Yes"), tr ("No"), this,
  16281. juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<PlaylistComponent> (this),
  16282. gen = std::move (*generator), tracks, shift] (int result) mutable {
  16283. if (safe != nullptr && result == 1)
  16284. safe->applyGeneratorDrop (std::move (gen), std::move (tracks), shift);
  16285. }));
  16286. return;
  16287. }
  16288. applyGeneratorDrop (std::move (*generator), std::move (tracks), shift);
  16289. return;
  16290. }
  16291. // an effect: into the first free slot of the mixer track the header plays through (0xe79d60 -> 0x12e69a0)
  16292. auto trial = engine.getSong();
  16293. if (const auto check = plugindrop::effectOnTrack (trial, *fx, track); ! check.ok())
  16294. {
  16295. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, plugindropui::title (check.error),
  16296. plugindropui::message (check.error));
  16297. return;
  16298. }
  16299. plugindrop::Result r;
  16300. engine.editSong ([&] (Song& song) { r = plugindrop::effectOnTrack (song, std::move (*fx), track); });
  16301. selectTrack (track);
  16302. if (onLinkedMixerTrack && r.insert > 0)
  16303. onLinkedMixerTrack (r.insert); // (FL points the Mixer at that mixer track)
  16304. repaint();
  16305. }
  16306. void PlaylistComponent::applyGeneratorDrop (ChannelDef generator, std::vector<int> tracks, bool shift)
  16307. {
  16308. // (a drop refused before anything changed leaves no undo step; one that fails part-way keeps what it did, as FL)
  16309. auto trial = engine.getSong();
  16310. if (const auto check = plugindrop::generatorOnTracks (trial, generator, tracks); ! check.ok() && check.tracks.empty())
  16311. {
  16312. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, plugindropui::title (check.error),
  16313. plugindropui::message (check.error));
  16314. return;
  16315. }
  16316. plugindrop::Result r;
  16317. engine.editSong ([&] (Song& song) { r = plugindrop::generatorOnTracks (song, generator, tracks); });
  16318. if (! r.ok())
  16319. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, plugindropui::title (r.error), plugindropui::message (r.error));
  16320. selectTracks (r.tracks);
  16321. // the plugin's window opens for a single track; for several only while Shift is held (FL 0xe71980 / 0x12ebbd0)
  16322. if (onGeneratorAdded && (r.tracks.size() == 1 || shift))
  16323. for (const auto channel : r.channels)
  16324. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  16325. onGeneratorAdded (channel, engine.getSong().channels[(std::size_t) channel].instrument);
  16326. repaint();
  16327. }
  16328. juce::String PlaylistComponent::pickerDragDescription (ClipKind kind, const std::vector<int>& entries)
  16329. {
  16330. juce::StringArray list;
  16331. for (const auto e : entries)
  16332. list.add (juce::String (e));
  16333. return "lynx-picker|" + juce::String ((int) kind) + "|" + list.joinIntoString (",");
  16334. }
  16335. bool PlaylistComponent::pickerDrag (const juce::var& description, ClipKind& kind, std::vector<int>& entries)
  16336. {
  16337. const auto text = description.toString();
  16338. if (! text.startsWith ("lynx-picker|"))
  16339. return false;
  16340. const auto parts = juce::StringArray::fromTokens (text, "|", "");
  16341. if (parts.size() != 3)
  16342. return false;
  16343. const auto k = parts[1].getIntValue();
  16344. if (k != (int) ClipKind::pattern && k != (int) ClipKind::audio && k != (int) ClipKind::automation)
  16345. return false;
  16346. kind = (ClipKind) k;
  16347. entries.clear();
  16348. for (const auto& e : juce::StringArray::fromTokens (parts[2], ",", ""))
  16349. if (e.isNotEmpty())
  16350. entries.push_back (e.getIntValue());
  16351. return ! entries.empty();
  16352. }
  16353. void PlaylistComponent::dropFromPicker (ClipKind kind, const std::vector<int>& entries, juce::Point<int> p, bool shift)
  16354. {
  16355. // FL 2026 (FLEngine FUN_00e7a470, picker branch; FUN_012f30b0 with Shift; core/PickerDrop.h)
  16356. if (entries.empty() || p.y < tracksTop() || p.y >= gridArea().getBottom())
  16357. return;
  16358. const auto track = yToTrack (p.y);
  16359. // the mouse time, snapped with the Playlist's snap to the nearest line (FL's FUN_00e5a350; only its Cell snap, which
  16360. // LYNX has not, rounds down); over the track headers the view's left edge
  16361. const auto tick = juce::jmax (0.0, xToTick (juce::jmax (p.x, gridArea().getX())));
  16362. const auto start = juce::jmax<std::int64_t> (0, snapLine (tick));
  16363. const auto& song = engine.getSong();
  16364. std::vector<Clip> clips;
  16365. for (const auto e : entries)
  16366. {
  16367. const auto valid = kind == ClipKind::pattern ? e >= 0 && e < (int) song.patterns.size()
  16368. : kind == ClipKind::audio ? e >= 0 && e < (int) song.channels.size() && song.channels[(std::size_t) e].instrument == InstrumentKind::audioClip
  16369. : e >= 0 && e < (int) song.automations.size();
  16370. if (valid)
  16371. clips.push_back (makeSourceClip (kind, e, track, start));
  16372. }
  16373. if (clips.empty())
  16374. return;
  16375. const juce::Component::SafePointer<PlaylistComponent> safe (this);
  16376. auto apply = [safe, clips, track, start, shift] (bool moveOff) {
  16377. if (safe == nullptr)
  16378. return;
  16379. auto& engine = safe->engine;
  16380. const auto placed = pickerdrop::place (engine.getSong(), clips, track, start, shift, moveOff);
  16381. if (placed.empty())
  16382. return;
  16383. const auto first = (int) engine.getSong().playlist.size();
  16384. engine.editSong ([&placed, shift] (Song& s) { // (one undo step, FL's "drop")
  16385. s.playlist.insert (s.playlist.end(), placed.begin(), placed.end());
  16386. s.currentPattern = pickerdrop::currentPatternAfter (placed, shift, s.currentPattern);
  16387. s.mode = PlayMode::song;
  16388. });
  16389. std::vector<int> indices;
  16390. for (int i = first; i < (int) engine.getSong().playlist.size(); ++i)
  16391. indices.push_back (i);
  16392. // the dropped clips become the selection (FL flags them selected; live check 190hm, shots fl-08 / fl-12); audio
  16393. // clips on an audio track follow its mixer track, as any placed clip
  16394. safe->setSelection ({});
  16395. safe->setSelection (safe->sortClips (std::move (indices)));
  16396. safe->repaint();
  16397. };
  16398. if (! pickerdrop::asksAboutInstrumentTrack (song, clips, track, shift))
  16399. {
  16400. apply (false);
  16401. return;
  16402. }
  16403. // FL asks once per drop (MB_YESNO | MB_ICONQUESTION); Yes = the next empty tracks, No = stop there
  16404. auto options = juce::MessageBoxOptions()
  16405. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  16406. .withTitle (tr ("Can't drop on an instrument track"))
  16407. .withMessage (tr ("Instrument tracks are not for audio or automation clips.") + "\n\n"
  16408. + tr ("Would you like to place the clip(s) on the next empty playlist track(s)?"))
  16409. .withButton (tr ("Yes"))
  16410. .withButton (tr ("No"))
  16411. .withAssociatedComponent (this);
  16412. juce::AlertWindow::showAsync (options, [apply] (int result) { apply (result == 1); });
  16413. }
  16414. // Round 190im (R5, DE-135): while something is dragged over the Playlist, the clips the drop would make are drawn where
  16415. // they would land (the snapped time, the track under the mouse, their length), so the place is seen before the release.
  16416. // FL's own drop feedback is not captured yet (capture C-11; FL's picker drag shows the entry's picture under the
  16417. // mouse, FLEngine FUN_00e4daa0): this is LYNX's aid in every layout. Sources: the Picker panel (issue #177's drag
  16418. // description, "lynx-picker|kind|entries", branch wip/pickerdrag190hm: entry k on the track under the mouse + k at the
  16419. // nearest snap line; Shift: one after the other on that track), a clip of the clip grid, a pattern or an audio file of
  16420. // the Browser. Only the old and new ghost rectangles are repainted, on drag moves only.
  16421. void PlaylistComponent::updateDropGhost (const SourceDetails& details)
  16422. {
  16423. std::vector<Clip> ghost;
  16424. juce::String name; // (round 190jj: the Simple ghost's name tag)
  16425. const auto& song = engine.getSong();
  16426. const auto grid = gridArea();
  16427. const auto p = details.localPosition;
  16428. if (p.y >= tracksTop() && p.y < grid.getBottom() && p.x < grid.getRight())
  16429. {
  16430. const auto track = juce::jmax (0, yToTrack (p.y));
  16431. const auto snapped = juce::jmax<std::int64_t> (0, snap (xToTick (p.x), true));
  16432. const auto ticksOfSeconds = [&song] (double seconds) { return juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * song.bpm / 60.0 * ppq)); };
  16433. const auto channelTicks = [&] (int channel) -> std::int64_t {
  16434. if (channel < 0 || channel >= (int) song.channels.size())
  16435. return 0;
  16436. if (auto data = engine.getSampleLibrary().findLoaded (juce::String::fromUTF8 (song.channels[(std::size_t) channel].samplePath.c_str())))
  16437. return ticksOfSeconds ((double) data->frames() / data->sampleRate);
  16438. return 0;
  16439. };
  16440. const auto add = [&] (ClipKind kind, int index, int t, std::int64_t start, std::int64_t length) {
  16441. if (length <= 0 || t < 0)
  16442. return;
  16443. Clip c;
  16444. c.kind = kind;
  16445. c.pattern = kind == ClipKind::pattern ? index : 0;
  16446. c.channel = kind == ClipKind::audio ? index : -1;
  16447. c.automation = kind == ClipKind::automation ? index : -1;
  16448. c.track = t;
  16449. c.start = start;
  16450. c.length = length;
  16451. ghost.push_back (c);
  16452. };
  16453. const auto patternTicks = [&song] (int pattern) {
  16454. return pattern >= 0 && pattern < (int) song.patterns.size()
  16455. ? juce::jmax<std::int64_t> (ppq, song.patterns[(std::size_t) pattern].effectiveLength (song.meter())) : (std::int64_t) 0;
  16456. };
  16457. const auto text = details.description.toString();
  16458. int gridTrack = 0, gridScene = 0;
  16459. if (text.startsWith ("lynx-picker|"))
  16460. {
  16461. const auto parts = juce::StringArray::fromTokens (text, "|", "");
  16462. const auto kind = parts.size() == 3 ? (ClipKind) parts[1].getIntValue() : ClipKind::pattern;
  16463. const auto shift = juce::ModifierKeys::currentModifiers.isShiftDown();
  16464. auto at = juce::jmax<std::int64_t> (0, snapLine (juce::jmax (0.0, xToTick (juce::jmax (p.x, grid.getX())))));
  16465. int k = 0;
  16466. for (const auto& e : juce::StringArray::fromTokens (parts[2], ",", ""))
  16467. {
  16468. const auto index = e.getIntValue();
  16469. if (name.isEmpty())
  16470. name = kind == ClipKind::pattern && index >= 0 && index < (int) song.patterns.size()
  16471. ? juce::String::fromUTF8 (song.patterns[(std::size_t) index].name.c_str())
  16472. : kind == ClipKind::audio && index >= 0 && index < (int) song.channels.size()
  16473. ? juce::String::fromUTF8 (song.channels[(std::size_t) index].name.c_str())
  16474. : juce::String();
  16475. const auto length = kind == ClipKind::pattern ? patternTicks (index)
  16476. : kind == ClipKind::audio ? channelTicks (index)
  16477. : (index >= 0 && index < (int) song.automations.size() ? song.barTicks() * 4 : 0);
  16478. add (kind, index, shift ? track : track + k, at, length);
  16479. if (shift)
  16480. at += juce::jmax<std::int64_t> (1, length);
  16481. ++k;
  16482. }
  16483. }
  16484. else if (clipGridDrag (details.description, gridTrack, gridScene))
  16485. {
  16486. if (const auto* c = song.clipGrid ? launcher::clipAt (*song.clipGrid, gridTrack, gridScene) : nullptr)
  16487. add (c->kind, c->kind == ClipKind::audio ? c->channel : c->kind == ClipKind::automation ? c->automation : c->pattern, track, snapped, c->length);
  16488. }
  16489. else if (const auto pattern = BrowserComponent::draggedPattern (details); pattern >= 0)
  16490. {
  16491. add (ClipKind::pattern, pattern, track, snapped, patternTicks (pattern));
  16492. if (pattern < (int) song.patterns.size())
  16493. name = juce::String::fromUTF8 (song.patterns[(std::size_t) pattern].name.c_str());
  16494. }
  16495. else if (const auto file = BrowserComponent::draggedFile (details); file.existsAsFile() && p.x >= headerWidth)
  16496. {
  16497. if (! sampleDropGhost (p, file, ghost)) // (issue #325: over an audio clip the clips that change)
  16498. add (ClipKind::audio, -1, track, snapped, dropGhostAudioTicks (file));
  16499. name = file.getFileNameWithoutExtension();
  16500. }
  16501. else if (simpleHeaders && BrowserComponent::isGeneratorDrag (details)) // (round 190sa: a sound makes a new track)
  16502. {
  16503. name = text.fromFirstOccurrenceOf ("|", false, false);
  16504. if (const auto lane = dropLaneTrack(); lane >= 0 && p.x >= headerWidth)
  16505. add (ClipKind::pattern, -1, lane, snapped, 4 * song.barTicks()); // (on the new track's row, where it goes)
  16506. }
  16507. }
  16508. finishDropGhost (std::move (ghost), p, name);
  16509. }
  16510. // (an audio file's length in ticks at the song's tempo, read once per drag: the loaded sample, else the file's header)
  16511. std::int64_t PlaylistComponent::dropGhostAudioTicks (const juce::File& file)
  16512. {
  16513. if (file.getFullPathName() != dropGhostFile)
  16514. {
  16515. const auto& song = engine.getSong();
  16516. const auto ticksOfSeconds = [&song] (double seconds) { return juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * song.bpm / 60.0 * ppq)); };
  16517. dropGhostFile = file.getFullPathName();
  16518. dropGhostFileTicks = 0;
  16519. if (auto data = engine.getSampleLibrary().findLoaded (dropGhostFile))
  16520. dropGhostFileTicks = ticksOfSeconds ((double) data->frames() / data->sampleRate);
  16521. else
  16522. {
  16523. static juce::AudioFormatManager formats; // (the header only: its length)
  16524. if (formats.getNumKnownFormats() == 0)
  16525. formats.registerBasicFormats();
  16526. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (file)); reader != nullptr && reader->sampleRate > 0.0)
  16527. dropGhostFileTicks = ticksOfSeconds ((double) reader->lengthInSamples / reader->sampleRate);
  16528. }
  16529. }
  16530. return dropGhostFileTicks;
  16531. }
  16532. // Round 190jj: files dragged from outside LYNX (Explorer) show the same ghost as the Browser's: the first audio file's
  16533. // length on the track under the mouse
  16534. void PlaylistComponent::updateDropGhostForFiles (const juce::StringArray& files, juce::Point<int> p)
  16535. {
  16536. std::vector<Clip> ghost;
  16537. juce::String name;
  16538. const auto grid = gridArea();
  16539. if (! files.isEmpty() && p.y >= tracksTop() && p.y < grid.getBottom() && p.x >= headerWidth && p.x < grid.getRight())
  16540. {
  16541. const juce::File file (files[0]);
  16542. name = file.getFileNameWithoutExtension();
  16543. const auto onClip = files.size() == 1 && sampleDropGhost (p, file, ghost); // (issue #325)
  16544. if (! onClip && file.existsAsFile() && ! file.hasFileExtension ("mid;midi") && ! videotracks::isVideoFile (file))
  16545. if (const auto length = dropGhostAudioTicks (file); length > 0)
  16546. {
  16547. Clip c;
  16548. c.kind = ClipKind::audio;
  16549. c.channel = c.automation = -1;
  16550. c.track = juce::jmax (0, yToTrack (p.y));
  16551. c.start = juce::jmax<std::int64_t> (0, snap (xToTick (p.x), true));
  16552. c.length = length;
  16553. ghost.push_back (c);
  16554. }
  16555. }
  16556. finishDropGhost (std::move (ghost), p, name);
  16557. }
  16558. juce::String PlaylistComponent::simpleDropRefusal (int track, ClipKind kind) const
  16559. {
  16560. using K = simpletracks::Kind;
  16561. if (! simpleHeaders || kind != ClipKind::audio)
  16562. return {};
  16563. const auto k = simpletracks::kindOf (engine.getSong(), track);
  16564. return k && (*k == K::instrument || *k == K::drums || *k == K::sampler || *k == K::pads) ? tr ("Region not supported by this track") : juce::String();
  16565. }
  16566. // The ghost the drag shows now; only the old and the new ghost (and the Simple tag) are repainted, on drag moves only
  16567. void PlaylistComponent::finishDropGhost (std::vector<Clip> ghost, juce::Point<int> mouse, const juce::String& name)
  16568. {
  16569. auto tagOnly = false;
  16570. juce::String reason;
  16571. if (simpleHeaders)
  16572. {
  16573. // BandLab: below the drop lane only the name tag follows the mouse (the lane keeps its placeholder)
  16574. const auto lane = dropLaneTrack();
  16575. if (! ghost.empty() && lane >= 0 && ghost.front().track > lane)
  16576. ghost.clear();
  16577. tagOnly = ghost.empty() && name.isNotEmpty() && gridArea().contains (mouse);
  16578. if (! ghost.empty())
  16579. reason = simpleDropRefusal (ghost.front().track, ghost.front().kind);
  16580. }
  16581. const auto sameGhost = ghost.size() == dropGhost.size()
  16582. && std::equal (ghost.begin(), ghost.end(), dropGhost.begin(), [] (const Clip& a, const Clip& b) {
  16583. return a.track == b.track && a.start == b.start && a.length == b.length && a.kind == b.kind;
  16584. });
  16585. if (sameGhost && tagOnly == dropGhostTagOnly && reason == dropGhostReason && name == dropGhostName && (! tagOnly || mouse == dropGhostMouse))
  16586. return;
  16587. dropGhost = std::move (ghost);
  16588. dropGhostName = simpleHeaders ? name : juce::String();
  16589. dropGhostReason = reason;
  16590. dropGhostTagOnly = tagOnly;
  16591. dropGhostMouse = mouse;
  16592. const auto now = dropGhostBounds();
  16593. if (! dropGhostArea.isEmpty())
  16594. repaint (dropGhostArea);
  16595. if (! now.isEmpty())
  16596. repaint (now);
  16597. dropGhostArea = now;
  16598. }
  16599. void PlaylistComponent::clearDropGhost()
  16600. {
  16601. dropGhost.clear();
  16602. dropGhostFile.clear();
  16603. dropGhostName.clear();
  16604. dropGhostReason.clear();
  16605. dropGhostTagOnly = false;
  16606. if (! dropGhostArea.isEmpty())
  16607. repaint (dropGhostArea);
  16608. dropGhostArea = {};
  16609. }
  16610. // Simple: the name tag, at the ghost's lower left (BandLab), or under the mouse when there is no ghost
  16611. juce::Rectangle<int> PlaylistComponent::dropGhostTag() const
  16612. {
  16613. if (! simpleHeaders || dropGhostName.isEmpty() || (dropGhost.empty() && ! dropGhostTagOnly))
  16614. return {};
  16615. const auto w = juce::jlimit (60, 190, juce::roundToInt (juce::GlyphArrangement::getStringWidth (theme::font (theme::type::small, true), dropGhostName)) + 20);
  16616. constexpr int h = 24;
  16617. if (dropGhost.empty())
  16618. return { dropGhostMouse.x - w / 2, dropGhostMouse.y + 8, w, h };
  16619. const auto& c = dropGhost.front();
  16620. const auto x0 = (int) std::floor (tickToX ((double) c.start));
  16621. const auto bottom = trackToY (c.track) + heightOf (c.track) - 3;
  16622. return { x0 + 3, bottom - h - 2, w, h };
  16623. }
  16624. juce::Rectangle<int> PlaylistComponent::dropGhostBounds() const
  16625. {
  16626. juce::Rectangle<int> area;
  16627. const auto grid = gridArea();
  16628. for (const auto& c : dropGhost)
  16629. {
  16630. if (c.track >= numTracks())
  16631. continue;
  16632. const auto x0 = (int) std::floor (tickToX ((double) c.start)), x1 = (int) std::ceil (tickToX ((double) c.end()));
  16633. area = area.getUnion (juce::Rectangle<int> (x0, trackToY (c.track), juce::jmax (2, x1 - x0), heightOf (c.track)).expanded (2).getIntersection (grid));
  16634. }
  16635. if (const auto tag = dropGhostTag(); ! tag.isEmpty())
  16636. area = area.getUnion (tag.expanded (2).getIntersection (grid));
  16637. return area;
  16638. }
  16639. void PlaylistComponent::paintDropGhost (juce::Graphics& g)
  16640. {
  16641. if (dropGhost.empty() && ! dropGhostTagOnly)
  16642. return;
  16643. using namespace theme;
  16644. const auto& song = engine.getSong();
  16645. const juce::Graphics::ScopedSaveState keep (g);
  16646. g.reduceClipRegion (gridArea());
  16647. // Round 190jj (capture190ji §3, C-11, shots/fl-c11-ghost-z3.png): FL 2026's drop ghost in the Pattern layout — a
  16648. // borderless white block at ~13 % (about +34 RGB over the grid), as long as the clip, inside the row's grid lines
  16649. // (24 px of a 26 px row), its left edge on the snapped line. No outline, no track highlight, no text.
  16650. if (flHeaders())
  16651. {
  16652. for (const auto& c : dropGhost)
  16653. if (c.track < numTracks())
  16654. {
  16655. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  16656. g.setColour (juce::Colours::white.withAlpha (0.13f));
  16657. g.fillRect (juce::Rectangle<float> (std::round (x0), (float) trackToY (c.track) + 1.0f, juce::jmax (2.0f, std::round (x1) - std::round (x0)),
  16658. (float) heightOf (c.track) - 2.0f));
  16659. }
  16660. return;
  16661. }
  16662. // Round 190jj (capture190ji §1e, shots/bl-e-drop-lane-drag.png): BandLab's ghost in the Simple layout — a region
  16663. // inset in the row, white at ~18 % with a 2 px grey dashed outline (#7c7c7c), or red with the reason over a track that
  16664. // can't take it; the name tag (#1d2021, light text) at its lower left
  16665. if (simpleHeaders)
  16666. {
  16667. for (const auto& c : dropGhost)
  16668. {
  16669. if (c.track >= numTracks())
  16670. continue;
  16671. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  16672. const auto r = juce::Rectangle<float> (std::round (x0) + 0.5f, (float) trackToY (c.track) + 3.5f, juce::jmax (8.0f, std::round (x1) - std::round (x0) - 1.0f),
  16673. (float) heightOf (c.track) - 7.0f);
  16674. const auto refused = dropGhostReason.isNotEmpty();
  16675. g.setColour (refused ? juce::Colour (0xffe5484d).withAlpha (0.30f) : juce::Colours::white.withAlpha (0.18f));
  16676. g.fillRoundedRectangle (r, 3.0f);
  16677. juce::Path outline, dashed;
  16678. outline.addRoundedRectangle (r, 3.0f);
  16679. const float dashes[] { 4.0f, 3.0f };
  16680. juce::PathStrokeType (1.5f).createDashedStroke (dashed, outline, dashes, 2);
  16681. g.setColour (refused ? juce::Colour (0xffb0646a) : juce::Colour (0xff7c7c7c));
  16682. g.fillPath (dashed);
  16683. if (refused)
  16684. {
  16685. g.setColour (colour::textPrimary);
  16686. g.setFont (font (type::small, true));
  16687. g.drawFittedText (dropGhostReason, r.reduced (8.0f, 4.0f).withTrimmedBottom (r.getHeight() * 0.4f).toNearestInt(), juce::Justification::centred, 2, 0.85f);
  16688. }
  16689. }
  16690. if (const auto tag = dropGhostTag(); ! tag.isEmpty())
  16691. {
  16692. g.setColour (juce::Colour (0xff1d2021));
  16693. g.fillRoundedRectangle (tag.toFloat(), 4.0f);
  16694. g.setColour (juce::Colour (0xffcecfcf));
  16695. g.setFont (font (type::small, true));
  16696. g.drawText (dropGhostName, tag.reduced (10, 0), juce::Justification::centredLeft, true);
  16697. }
  16698. return;
  16699. }
  16700. for (const auto& c : dropGhost)
  16701. {
  16702. if (c.track >= numTracks())
  16703. continue;
  16704. auto colour = theme::colour::accent;
  16705. if (c.kind == ClipKind::pattern)
  16706. colour = patternColour (song, c.pattern);
  16707. else if (c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  16708. colour = audioClipColour (song.channels[(std::size_t) c.channel]);
  16709. else if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size() && song.automations[(std::size_t) c.automation].colour != 0)
  16710. colour = juce::Colour (song.automations[(std::size_t) c.automation].colour);
  16711. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  16712. const auto r = juce::Rectangle<float> (x0, (float) trackToY (c.track) + 1.0f, juce::jmax (2.0f, x1 - x0), (float) heightOf (c.track) - 2.0f);
  16713. g.setColour (colour.withAlpha (0.45f));
  16714. g.fillRect (r);
  16715. g.setColour (colour.brighter (0.8f));
  16716. g.drawRect (r, 1.5f);
  16717. g.fillRect (r.withWidth (2.0f)); // (the start, where the snap put it)
  16718. }
  16719. }
  16720. void PlaylistComponent::dragOverForSnapshot (const juce::var& description, juce::Point<int> at)
  16721. {
  16722. if (description.isVoid())
  16723. {
  16724. itemDragExit (SourceDetails ({}, nullptr, at));
  16725. return;
  16726. }
  16727. itemDragMove (SourceDetails (description, nullptr, at)); // (round 190jj: the Simple drop lane lights as for a real drag)
  16728. }
  16729. void PlaylistComponent::itemDropped (const SourceDetails& details)
  16730. {
  16731. clearDropGhost();
  16732. setDropLaneHot (false);
  16733. // issue #177: entries dragged out of the Picker panel
  16734. auto pickerKind = ClipKind::pattern;
  16735. if (std::vector<int> entries; pickerDrag (details.description, pickerKind, entries))
  16736. {
  16737. dropFromPicker (pickerKind, entries, details.localPosition, juce::ModifierKeys::currentModifiers.isShiftDown());
  16738. return;
  16739. }
  16740. if (simpleHeaders && BrowserComponent::isGeneratorDrag (details)) // (round 190sa)
  16741. {
  16742. simpleSoundDropped (details);
  16743. return;
  16744. }
  16745. if (BrowserComponent::isGeneratorDrag (details) || BrowserComponent::isEffectDrag (details))
  16746. {
  16747. pluginDropped (details);
  16748. return;
  16749. }
  16750. // a clip dragged out of the clip grid (round 190bv): a copy of it where it is dropped, one pass long
  16751. if (int gridTrack = 0, gridScene = 0; clipGridDrag (details.description, gridTrack, gridScene))
  16752. {
  16753. if (! clipGridDragHolds (engine.getSong(), details.description)) // (round 190rw: the song changed under the drag)
  16754. return;
  16755. const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (details.localPosition.x), true));
  16756. const auto track = juce::jmax (0, yToTrack (details.localPosition.y));
  16757. engine.editSong ([=] (Song& s) { session::toPlaylist (s, gridTrack, gridScene, track, start); });
  16758. return;
  16759. }
  16760. // a pattern from the Browser's "Current project": a clip of it where it is dropped
  16761. if (const auto pattern = BrowserComponent::draggedPattern (details); pattern >= 0 && pattern < (int) engine.getSong().patterns.size())
  16762. {
  16763. const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (details.localPosition.x), true));
  16764. const auto track = juce::jmax (0, yToTrack (details.localPosition.y));
  16765. engine.editSong ([=] (Song& s) {
  16766. Clip clip;
  16767. clip.kind = ClipKind::pattern;
  16768. clip.pattern = pattern;
  16769. clip.track = track;
  16770. clip.start = start;
  16771. clip.length = juce::jmax<std::int64_t> (ppq, s.patterns[(std::size_t) pattern].effectiveLength (s.meter()));
  16772. s.playlist.push_back (clip);
  16773. s.mode = PlayMode::song;
  16774. });
  16775. return;
  16776. }
  16777. if (const auto file = BrowserComponent::draggedFile (details); file.existsAsFile())
  16778. filesDropped ({ file.getFullPathName() }, details.localPosition.x, details.localPosition.y);
  16779. }
  16780. // ---------------------------------------------------------------------------
  16781. PatternPicker::PatternPicker (AudioEngine& e, PlaylistComponent& p)
  16782. : engine (e),
  16783. playlist (p)
  16784. {
  16785. engine.addChangeListener (this);
  16786. seenBrush = playlist.brush.kind;
  16787. playlist.livePicker = this; // (round 190im: the Playlist's frame step tells it what plays)
  16788. }
  16789. PatternPicker::~PatternPicker()
  16790. {
  16791. if (playlist.livePicker == this)
  16792. playlist.livePicker = nullptr;
  16793. engine.removeChangeListener (this);
  16794. }
  16795. void PatternPicker::setPlayingPatterns (std::vector<int> now)
  16796. {
  16797. if (now == playingPatterns)
  16798. return;
  16799. // only the entries whose mark comes or goes (the pattern list: entry i = pattern i)
  16800. std::vector<int> changed;
  16801. std::set_symmetric_difference (playingPatterns.begin(), playingPatterns.end(), now.begin(), now.end(), std::back_inserter (changed));
  16802. playingPatterns = std::move (now);
  16803. if (view != 0)
  16804. return;
  16805. for (const auto p : changed) // (round 190ne: a pattern's row is found in the list: track clips sit in their group)
  16806. if (const auto row = listRowOfPattern (p); row >= scroll)
  16807. if (const auto y = headerHeight + (row - scroll) * rowHeight; y < listBottom())
  16808. repaint (0, y, getWidth(), rowHeight);
  16809. }
  16810. void PatternPicker::changeListenerCallback (juce::ChangeBroadcaster*)
  16811. {
  16812. // the pencil's source changed elsewhere (a clip clicked, the track menu): show its kind, as FL does
  16813. if (playlist.brush.kind != seenBrush)
  16814. {
  16815. seenBrush = playlist.brush.kind;
  16816. view = seenBrush == ClipKind::audio ? 1 : seenBrush == ClipKind::automation ? 2 : 0;
  16817. scroll = 0;
  16818. }
  16819. repaint();
  16820. }
  16821. void PatternPicker::setView (int newView)
  16822. {
  16823. view = juce::jlimit (0, 2, newView);
  16824. scroll = 0;
  16825. repaint();
  16826. }
  16827. const std::vector<PatternPicker::Row>& PatternPicker::rows() const
  16828. {
  16829. const auto& song = engine.getSong();
  16830. // round 190ne: built once per published song (and view, group state, clip look), not at every paint and mouse move
  16831. const auto key = view | (trackClipsOpen ? 4 : 0) | (flClipLook() ? 8 : 0);
  16832. if (engine.getPublishCount() == rowCacheStamp && key == rowCacheKey)
  16833. return rowCache;
  16834. rowCacheStamp = engine.getPublishCount();
  16835. rowCacheKey = key;
  16836. auto& list = rowCache;
  16837. list.clear();
  16838. if (view == 0)
  16839. {
  16840. // FL's list: every ordinary pattern; then (round 190ne, core/TrackClips.h) the track clips in a folded group, by
  16841. // track. Without track clips the list is exactly FL's.
  16842. int trackClips = 0;
  16843. for (int i = 0; i < (int) song.patterns.size(); ++i)
  16844. if (song.patterns[(std::size_t) i].trackClip)
  16845. ++trackClips;
  16846. else
  16847. list.push_back ({ ClipKind::pattern, i, juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()),
  16848. PlaylistComponent::patternColour (song, i) });
  16849. if (trackClips > 0)
  16850. {
  16851. list.push_back ({ ClipKind::pattern, -1, tr ("Track clips ({0})", { juce::String (trackClips) }), juce::Colour(), true });
  16852. if (trackClipsOpen)
  16853. {
  16854. const auto owners = trackclips::ownerTracks (song);
  16855. const auto uses = trackclips::uses (song);
  16856. std::vector<int> order;
  16857. for (int i = 0; i < (int) song.patterns.size(); ++i)
  16858. if (song.patterns[(std::size_t) i].trackClip)
  16859. order.push_back (i);
  16860. std::stable_sort (order.begin(), order.end(), [&owners] (int a, int b) {
  16861. return (unsigned) owners[(std::size_t) a] < (unsigned) owners[(std::size_t) b]; // (by track; unused last)
  16862. });
  16863. for (const auto i : order)
  16864. {
  16865. Row row { ClipKind::pattern, i, juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()), PlaylistComponent::patternColour (song, i) };
  16866. row.trackClip = true;
  16867. row.uses = uses[(std::size_t) i];
  16868. list.push_back (std::move (row));
  16869. }
  16870. }
  16871. }
  16872. }
  16873. if (view == 1)
  16874. for (int c = 0; c < (int) song.channels.size(); ++c)
  16875. if (song.channels[(std::size_t) c].instrument == InstrumentKind::audioClip)
  16876. list.push_back ({ ClipKind::audio, c, juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str()),
  16877. PlaylistComponent::audioClipColour (song.channels[(std::size_t) c]) });
  16878. if (view == 2)
  16879. for (int a = 0; a < (int) song.automations.size(); ++a)
  16880. list.push_back ({ ClipKind::automation, a, juce::String::fromUTF8 (song.automations[(std::size_t) a].name.c_str()),
  16881. flClipLook() ? flHeaderFill (song.automations[(std::size_t) a].colour) : theme::colour::automation }); // (round 190ig)
  16882. return list;
  16883. }
  16884. juce::Rectangle<int> PatternPicker::tabBounds (int tab) const
  16885. {
  16886. const auto w = (getWidth() - 8) / 3;
  16887. return { 4 + tab * w, 2, w, headerHeight - 4 };
  16888. }
  16889. int PatternPicker::listBottom() const
  16890. {
  16891. return view == 0 ? getHeight() - footerHeight : getHeight();
  16892. }
  16893. juce::Rectangle<int> PatternPicker::addBounds() const
  16894. {
  16895. return view == 0 ? juce::Rectangle<int> (4, getHeight() - footerHeight + 2, getWidth() - 8, footerHeight - 4) : juce::Rectangle<int>();
  16896. }
  16897. juce::Rectangle<int> PatternPicker::groupSwitchBounds (int listRow) const
  16898. {
  16899. // the group row's "shown" switch, at its right end
  16900. const auto y = headerHeight + (listRow - scroll) * rowHeight;
  16901. return { getWidth() - 4 - 46, y + 6, 42, rowHeight - 12 };
  16902. }
  16903. int PatternPicker::rowAt (int y) const
  16904. {
  16905. if (y < headerHeight || y >= listBottom())
  16906. return -1;
  16907. const auto index = (y - headerHeight) / rowHeight + scroll;
  16908. return index < (int) rows().size() ? index : -1;
  16909. }
  16910. void PatternPicker::paint (juce::Graphics& g)
  16911. {
  16912. const auto& song = engine.getSong();
  16913. const auto& list = rows();
  16914. using namespace theme;
  16915. g.fillAll (colour::bg2);
  16916. g.setColour (colour::bg3);
  16917. g.fillRect (0, 0, getWidth(), headerHeight);
  16918. g.setColour (colour::border);
  16919. g.fillRect (0, headerHeight - 1, getWidth(), 1);
  16920. // the three tabs: patterns, audio clips, automation clips
  16921. const Icon tabIcons[] = { Icon::pattern, Icon::audioFile, Icon::automate };
  16922. for (int t = 0; t < 3; ++t)
  16923. {
  16924. const auto r = tabBounds (t).toFloat();
  16925. if (t == view || t == hoverTab)
  16926. {
  16927. g.setColour (t == view ? colour::bg5 : colour::bg4);
  16928. g.fillRoundedRectangle (r, radius::sm);
  16929. }
  16930. icons::draw (g, tabIcons[t], r.withSizeKeepingCentre (16.0f, 16.0f), t == view ? colour::accent : t == hoverTab ? colour::textPrimary : colour::textSecondary);
  16931. }
  16932. {
  16933. juce::Graphics::ScopedSaveState state (g);
  16934. g.reduceClipRegion (0, headerHeight, getWidth(), listBottom() - headerHeight);
  16935. for (int i = scroll; i < (int) list.size(); ++i)
  16936. {
  16937. const auto y = headerHeight + (i - scroll) * rowHeight;
  16938. if (y > listBottom())
  16939. break;
  16940. const auto& row = list[(std::size_t) i];
  16941. if (row.group) // round 190ne: the track clips' group row (LYNX's own: a fold arrow, its name, the "shown" switch)
  16942. {
  16943. const auto band = juce::Rectangle<int> (4, y + 3, getWidth() - 8, rowHeight - 6).toFloat();
  16944. g.setColour (i == hoverRow ? colour::bg4 : colour::bg3);
  16945. g.fillRoundedRectangle (band, radius::sm);
  16946. const auto a = juce::Rectangle<float> (band.getX() + 6.0f, band.getCentreY() - 4.0f, 8.0f, 8.0f);
  16947. juce::Path tri;
  16948. if (trackClipsOpen) // open: points down
  16949. tri.addTriangle (a.getX(), a.getY() + 1.5f, a.getRight(), a.getY() + 1.5f, a.getCentreX(), a.getBottom() - 1.5f);
  16950. else
  16951. tri.addTriangle (a.getX() + 1.5f, a.getY(), a.getX() + 1.5f, a.getBottom(), a.getRight() - 1.5f, a.getCentreY());
  16952. g.setColour (colour::textSecondary);
  16953. g.fillPath (tri);
  16954. const auto toggle = groupSwitchBounds (i);
  16955. const auto shown = trackclips::shownInSelector();
  16956. g.setColour (shown ? colour::accent.withAlpha (0.35f) : colour::bg2);
  16957. g.fillRoundedRectangle (toggle.toFloat(), radius::sm);
  16958. g.setColour (shown ? colour::accent : colour::border);
  16959. g.drawRoundedRectangle (toggle.toFloat().reduced (0.5f), radius::sm, 1.0f);
  16960. g.setColour (shown ? colour::textPrimary : colour::textSecondary);
  16961. g.setFont (font (type::caption, shown));
  16962. textcache::drawText (g, tr ("shown"), toggle, juce::Justification::centred, true);
  16963. g.setColour (colour::textPrimary);
  16964. g.setFont (font (type::small, true));
  16965. // (round 190oj CS-21: narrows to 80 % before an ellipsis — "Track clips (…" lost its count in a 142 px picker)
  16966. textcache::drawFittedText (g, row.name, juce::Rectangle<int> ((int) a.getRight() + 5, y + 2, toggle.getX() - (int) a.getRight() - 8, rowHeight - 4),
  16967. juce::Justification::centredLeft, 1, 0.8f);
  16968. continue;
  16969. }
  16970. const auto r = juce::Rectangle<int> (row.trackClip ? 12 : 4, y + 2, getWidth() - (row.trackClip ? 16 : 8), rowHeight - 4);
  16971. const auto current = row.kind == ClipKind::pattern ? (playlist.brush.kind == ClipKind::pattern && row.index == song.currentPattern)
  16972. : (playlist.brush.kind == row.kind && playlist.brush.index == row.index);
  16973. const auto rowColour = tame (row.colour);
  16974. const auto box = r.toFloat();
  16975. auto fill = rowColour.interpolatedWith (colour::bg3, current ? 0.25f : 0.55f);
  16976. if (flClipLook() && ! theme::soft()) // round 190ig (FM-S2 picker, FL): the row filled with its own colour, brightness 0.42-0.58 (round 190qw: the Soft look keeps the tint)
  16977. {
  16978. const auto own = row.kind == ClipKind::audio && row.index < (int) song.channels.size() ? flHeaderFill (song.channels[(std::size_t) row.index].colour)
  16979. : row.colour;
  16980. fill = own.withBrightness (juce::jlimit (0.42f, 0.58f, own.getBrightness()) + (current ? 0.08f : 0.0f));
  16981. }
  16982. if (i == hoverRow && ! current)
  16983. fill = fill.interpolatedWith (colour::bg5, 0.35f);
  16984. g.setColour (fill);
  16985. g.fillRoundedRectangle (box, radius::sm);
  16986. // a faint miniature of the pattern's notes behind the name (FL's picker shows the same)
  16987. if (row.kind == ClipKind::pattern && row.index < (int) song.patterns.size())
  16988. {
  16989. const auto& pattern = song.patterns[(std::size_t) row.index];
  16990. if (! pattern.notes.empty())
  16991. {
  16992. int low = 127, high = 0;
  16993. for (const auto& n : pattern.notes)
  16994. {
  16995. low = juce::jmin (low, n.key);
  16996. high = juce::jmax (high, n.key);
  16997. }
  16998. const auto body = box.reduced (3.0f, 3.0f);
  16999. const auto span = (float) juce::jmax (6, high - low + 2);
  17000. const auto length = (double) juce::jmax<std::int64_t> (1, pattern.effectiveLength (song.meter()));
  17001. g.setColour (clipContentColour (rowColour).withAlpha (0.15f)); // (round 190oj: 0.35 read as a strike-through of the name; FL's level)
  17002. for (const auto& n : pattern.notes)
  17003. {
  17004. const auto nx = body.getX() + (float) (n.start / length) * body.getWidth();
  17005. const auto nw = juce::jmax (1.5f, (float) (n.length / length) * body.getWidth());
  17006. const auto ny = body.getBottom() - ((float) (n.key - low) + 1.0f) / span * body.getHeight();
  17007. g.fillRect (nx, ny, juce::jmin (nw, body.getRight() - nx), 1.5f);
  17008. }
  17009. }
  17010. }
  17011. if (row.kind == ClipKind::pattern && picked.contains (row.index) && picked.items.size() > 1) // picked with others
  17012. {
  17013. g.setColour (colour::accent.withAlpha (0.8f));
  17014. g.drawRoundedRectangle (box.reduced (0.5f), radius::sm, 1.2f);
  17015. }
  17016. if (current) // the current source: the accent strip
  17017. {
  17018. g.setColour (colour::accent);
  17019. g.fillRoundedRectangle (box.withWidth (3.0f), 1.5f);
  17020. }
  17021. // round 190im (R5, DC-3): a pattern that plays now — FL's bar at the entry's right edge, steady, following the
  17022. // pattern that plays (not the selection). Round 190jj (capture190ji, shots/fl-picker-playing-mark-z2.png): FL
  17023. // 2026 draws it 3 px wide in #597FFF inside the row, one pixel in from its edges; LYNX's looks: the playhead colour
  17024. if (row.kind == ClipKind::pattern && std::binary_search (playingPatterns.begin(), playingPatterns.end(), row.index))
  17025. {
  17026. g.setColour (flClipLook() ? juce::Colour (0xff597fff) : colour::playhead);
  17027. g.fillRect (box.reduced (0.0f, 1.0f).withLeft (box.getRight() - 4.0f).withWidth (3.0f));
  17028. }
  17029. g.setColour (flClipLook() ? flHeaderInk (fill) : clipTitleText (fill));
  17030. g.setFont (font (type::small, current));
  17031. auto text = r.withTrimmedLeft (9).withTrimmedRight (4);
  17032. if (row.trackClip && row.uses > 1) // round 190ne: linked copies, "x2" (the Playlist marks them with a link)
  17033. {
  17034. const auto count = juce::String::fromUTF8 ("\xc3\x97") + juce::String (row.uses);
  17035. textcache::drawText (g, count, text.removeFromRight (22), juce::Justification::centredRight, false);
  17036. }
  17037. textcache::drawText (g, row.name, text, juce::Justification::centredLeft, true);
  17038. }
  17039. }
  17040. if (const auto add = addBounds(); ! add.isEmpty())
  17041. {
  17042. g.setColour (hoverAdd ? colour::bg4 : colour::bg3);
  17043. g.fillRoundedRectangle (add.toFloat(), radius::sm);
  17044. icons::draw (g, Icon::plus, add.toFloat().withSizeKeepingCentre (14.0f, 14.0f), hoverAdd ? colour::textPrimary : colour::textSecondary);
  17045. }
  17046. g.setColour (colour::border);
  17047. g.drawVerticalLine (getWidth() - 1, 0.0f, (float) getHeight());
  17048. }
  17049. void PatternPicker::mouseDown (const juce::MouseEvent& e)
  17050. {
  17051. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::begin); // (round 190jv: one undo step per gesture)
  17052. for (int t = 0; t < 3; ++t)
  17053. if (tabBounds (t).contains (e.getPosition()))
  17054. {
  17055. setView (t);
  17056. return;
  17057. }
  17058. if (addBounds().contains (e.getPosition()))
  17059. {
  17060. if (onNewPattern)
  17061. onNewPattern();
  17062. return;
  17063. }
  17064. const auto list = rows();
  17065. const auto i = rowAt (e.y);
  17066. dragRow = -1;
  17067. dragging = false;
  17068. if (i < 0)
  17069. return;
  17070. const auto& row = list[(std::size_t) i];
  17071. if (row.group) // round 190ne: the group row folds / unfolds; its switch lists track clips in the pattern selector
  17072. {
  17073. if (groupSwitchBounds (i).contains (e.getPosition()))
  17074. {
  17075. trackclips::setShownInSelector (! trackclips::shownInSelector());
  17076. engine.sendChangeMessage(); // (the toolbar's pattern selector refills)
  17077. if (playlist.onViewOptionChanged)
  17078. playlist.onViewOptionChanged(); // (an app setting: saved now)
  17079. }
  17080. else
  17081. {
  17082. trackClipsOpen = ! trackClipsOpen;
  17083. const auto visible = juce::jmax (1, (listBottom() - headerHeight) / rowHeight);
  17084. scroll = juce::jlimit (0, juce::jmax (0, (int) rows().size() - visible), scroll);
  17085. }
  17086. repaint();
  17087. return;
  17088. }
  17089. // FL's Alt+right-hold on a pattern (round 190mp, DE-134; capture 190mp A6, fl-pl-picker-preview.png): the entry is
  17090. // selected, the pattern becomes the current one, the transport switches to pattern mode and plays it from its start
  17091. // while the button is held; no menu. The release stops it and puts SONG mode back (mouseUp).
  17092. if (row.kind == ClipKind::pattern && e.mods.isAltDown() && e.mods.isRightButtonDown() && ! e.mods.isLeftButtonDown())
  17093. {
  17094. pickersel::clamp (picked, (int) engine.getSong().patterns.size());
  17095. picked.clear();
  17096. picked.add (row.index);
  17097. playlist.brush = { row.kind, row.index, {} };
  17098. seenBrush = row.kind;
  17099. if (engine.getTransport().playing.load())
  17100. engine.stop();
  17101. previewModeBefore = (int) engine.getSong().mode;
  17102. engine.editSong ([p = row.index] (Song& s) {
  17103. s.currentPattern = p;
  17104. s.mode = PlayMode::pattern;
  17105. }, false);
  17106. engine.seek (0.0);
  17107. engine.play();
  17108. repaint();
  17109. return;
  17110. }
  17111. if (! flmods::popup (e.mods))
  17112. dragRow = i; // (issue #177: a drag from here places it on the Playlist)
  17113. // issue #175 (FL 2026, checked live: shots/FL-175-picker-choice-paints-plain.png): a click on the item the clicked
  17114. // clip came from keeps that clip as what the tools paint; another item paints its plain version
  17115. {
  17116. auto picked = playlist.brush.picked;
  17117. const auto current = row.kind == ClipKind::pattern ? row.index : engine.getSong().currentPattern;
  17118. if (picked && ! painttemplate::matches (*picked, row.kind, row.index, current))
  17119. picked.reset();
  17120. playlist.brush = { row.kind, row.index, std::move (picked) };
  17121. }
  17122. seenBrush = row.kind;
  17123. if (row.kind == ClipKind::pattern && row.index != engine.getSong().currentPattern)
  17124. engine.editSong ([p = row.index] (Song& s) { s.currentPattern = p; }, false);
  17125. // FL's picker selection (PickerPanelMouseDown FUN_00e4d5d0, REA_rodada169k §2.2)
  17126. pressedRow = -1;
  17127. if (row.kind == ClipKind::pattern)
  17128. {
  17129. pickersel::clamp (picked, (int) engine.getSong().patterns.size());
  17130. if (flmods::popup (e.mods))
  17131. pickersel::rightDown (picked, row.index, flmods::ctrl (e.mods));
  17132. else
  17133. {
  17134. deselectOnUp = pickersel::leftDownDeselects (picked, row.index, flmods::ctrl (e.mods));
  17135. pressedRow = i;
  17136. }
  17137. }
  17138. if (flmods::popup (e.mods) && row.kind == ClipKind::pattern && onPatternMenu)
  17139. onPatternMenu();
  17140. else if (flmods::popup (e.mods)) // round 190iu (issue #191.6): a take / a recorded envelope can be deleted from here
  17141. workflowextras::showPickerItemMenu (engine, row.kind, row.index, [safe = juce::Component::SafePointer<PatternPicker> (this)] {
  17142. if (safe != nullptr)
  17143. safe->repaint();
  17144. });
  17145. repaint();
  17146. }
  17147. juce::PopupMenu PatternPicker::pickerMenu()
  17148. {
  17149. const auto& song = engine.getSong();
  17150. const auto unused = unusedPatterns (song);
  17151. std::size_t duplicates = 0;
  17152. for (const auto& group : identicalPatterns (song))
  17153. duplicates += group.size() - 1;
  17154. const juce::Component::SafePointer<PatternPicker> safe (this);
  17155. auto edited = [safe] {
  17156. if (safe != nullptr)
  17157. {
  17158. safe->picked.clear(); // (the indices moved)
  17159. safe->repaint();
  17160. }
  17161. };
  17162. juce::PopupMenu menu, select, sort, sortMenu;
  17163. menu.addSectionHeader (tr ("Tools")); // (FL: Playlist menu › Picker panel › Tools, checked in FL in round 177d)
  17164. select.addItem (tr ("Patterns ({0})", { juce::String ((int) unused.size()) }), ! unused.empty(), false, [safe, unused] {
  17165. if (safe == nullptr)
  17166. return;
  17167. safe->setView (0);
  17168. safe->picked.clear();
  17169. for (auto p : unused)
  17170. safe->picked.add (p);
  17171. safe->repaint();
  17172. });
  17173. menu.addSubMenu (tr ("Select unused"), select);
  17174. sortMenu.addItem (tr ("By name"), song.patterns.size() > 1, false, [this, edited] {
  17175. engine.editSongPatternOrder ([] (Song& s) { sortPatterns (s, PatternSort::name); });
  17176. edited();
  17177. });
  17178. sortMenu.addItem (tr ("By color"), song.patterns.size() > 1, false, [this, edited] {
  17179. engine.editSongPatternOrder ([] (Song& s) { sortPatterns (s, PatternSort::colour); });
  17180. edited();
  17181. });
  17182. sort.addSubMenu (tr ("Patterns"), sortMenu);
  17183. menu.addSubMenu (tr ("Sort"), sort);
  17184. menu.addSeparator();
  17185. // LYNX's own (not in FL)
  17186. menu.addItem (tr ("Delete unused patterns ({0})", { juce::String ((int) unused.size()) }), ! unused.empty() && unused.size() < song.patterns.size(), false,
  17187. [this, edited] {
  17188. engine.editSong ([] (Song& s) { deletePatterns (s, unusedPatterns (s)); });
  17189. edited();
  17190. });
  17191. menu.addItem (tr ("Merge identical patterns ({0})", { juce::String ((int) duplicates) }), duplicates > 0, false, [this, edited] {
  17192. engine.editSong ([] (Song& s) { mergeIdenticalPatterns (s); });
  17193. edited();
  17194. });
  17195. workflowextras::addPickerCleanupItems (menu, engine, edited); // round 190iu (issue #191.6): unused takes and envelopes
  17196. return menu;
  17197. }
  17198. void PatternPicker::mouseDrag (const juce::MouseEvent& e)
  17199. {
  17200. // issue #177, FL's PickerPanelMouseMove (FUN_00e4daa0): with the left button held past the drag distance and Ctrl up,
  17201. // the entry is dragged; a pattern joins the picked ones (alone when it was not picked) and every picked one goes
  17202. if (dragging || dragRow < 0 || flmods::ctrl (e.mods) || ! e.mouseWasDraggedSinceMouseDown())
  17203. return;
  17204. const auto list = rows();
  17205. if (dragRow >= (int) list.size())
  17206. return;
  17207. const auto row = list[(std::size_t) dragRow];
  17208. auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this);
  17209. if (container == nullptr || container->isDragAndDropActive())
  17210. return;
  17211. std::vector<int> entries { row.index };
  17212. if (row.kind == ClipKind::pattern)
  17213. {
  17214. pickersel::clamp (picked, (int) engine.getSong().patterns.size());
  17215. if (! picked.contains (row.index))
  17216. {
  17217. picked.clear();
  17218. picked.add (row.index);
  17219. }
  17220. entries = pickerdrop::draggedEntries (picked.items, row.index);
  17221. }
  17222. dragging = true;
  17223. pressedRow = -1; // (no selection change on the release)
  17224. deselectOnUp = false;
  17225. auto image = dragImageOf (dragRow);
  17226. const auto offset = dragImageOffset();
  17227. repaint();
  17228. container->startDragging (PlaylistComponent::pickerDragDescription (row.kind, entries), this, juce::ScaledImage (image), false, &offset);
  17229. }
  17230. // the entry's own picture, semi-transparent, below the mouse and to its right (round 190jj, capture190ji C-11,
  17231. // shots/fl-c11-ghost-z3.png: FL 2026 draws it at 70 %-ish with its left edge ~34 px left of the mouse and its top ~40 px
  17232. // below, so the drop ghost in the row under the mouse stays visible; it was centred on the mouse)
  17233. juce::Image PatternPicker::dragImageOf (int listRow)
  17234. {
  17235. const auto bounds = juce::Rectangle<int> (4, headerHeight + (listRow - scroll) * rowHeight + 2, getWidth() - 8, rowHeight - 4)
  17236. .getIntersection (getLocalBounds());
  17237. auto image = bounds.isEmpty() ? juce::Image (juce::Image::ARGB, 1, 1, true) : createComponentSnapshot (bounds, true);
  17238. image = image.convertedToFormat (juce::Image::ARGB);
  17239. image.multiplyAllAlphas (0.7f);
  17240. return image;
  17241. }
  17242. int PatternPicker::rowCentreForSnapshot (int pattern) const
  17243. {
  17244. const auto r = listRowOfPattern (pattern);
  17245. return r < 0 ? -1 : headerHeight + (r - scroll) * rowHeight + rowHeight / 2;
  17246. }
  17247. int PatternPicker::listRowOfPattern (int pattern) const
  17248. {
  17249. const auto list = rows();
  17250. for (int i = 0; i < (int) list.size(); ++i)
  17251. if (list[(std::size_t) i].kind == ClipKind::pattern && list[(std::size_t) i].index == pattern)
  17252. return i;
  17253. return -1;
  17254. }
  17255. void PatternPicker::mouseUp (const juce::MouseEvent& e)
  17256. {
  17257. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::end); // (closes when mouseUp returns)
  17258. if (previewModeBefore >= 0) // (round 190mp, DE-134: the Alt+right-hold preview ends: stop, the mode it had, the start)
  17259. {
  17260. engine.stop();
  17261. if (engine.getSong().mode != (PlayMode) previewModeBefore)
  17262. engine.editSong ([m = (PlayMode) previewModeBefore] (Song& s) { s.mode = m; }, false);
  17263. engine.seek (0.0);
  17264. previewModeBefore = -1;
  17265. repaint();
  17266. return;
  17267. }
  17268. if (dragging) // (issue #177: the drag ended; the press changed nothing more)
  17269. {
  17270. dragging = false;
  17271. dragRow = -1;
  17272. pressedRow = -1;
  17273. return;
  17274. }
  17275. dragRow = -1;
  17276. // FL's PickerPanelMouseUp FUN_00e4e080: plain = only this one, Ctrl = toggle, Shift = the range from the first picked
  17277. const auto i = rowAt (e.y);
  17278. if (pressedRow < 0 || i != pressedRow)
  17279. {
  17280. pressedRow = -1;
  17281. return;
  17282. }
  17283. pressedRow = -1;
  17284. const auto list = rows();
  17285. if (i >= (int) list.size() || list[(std::size_t) i].kind != ClipKind::pattern || list[(std::size_t) i].group)
  17286. return;
  17287. pickersel::leftUp (picked, list[(std::size_t) i].index, flmods::ctrl (e.mods), e.mods.isShiftDown(), deselectOnUp);
  17288. deselectOnUp = false;
  17289. repaint();
  17290. }
  17291. std::vector<int> PatternPicker::pickedPatterns() const
  17292. {
  17293. auto s = picked;
  17294. pickersel::clamp (s, (int) engine.getSong().patterns.size());
  17295. return s.items;
  17296. }
  17297. void PatternPicker::mouseDoubleClick (const juce::MouseEvent& e)
  17298. {
  17299. const auto list = rows();
  17300. const auto i = rowAt (e.y);
  17301. if (i >= 0 && list[(std::size_t) i].kind == ClipKind::pattern && ! list[(std::size_t) i].group && onOpenPattern)
  17302. onOpenPattern();
  17303. }
  17304. void PatternPicker::mouseMove (const juce::MouseEvent& e)
  17305. {
  17306. int tab = -1;
  17307. for (int t = 0; t < 3; ++t)
  17308. if (tabBounds (t).contains (e.getPosition()))
  17309. tab = t;
  17310. const auto row = rowAt (e.y);
  17311. const auto add = addBounds().contains (e.getPosition());
  17312. if (tab != hoverTab || row != hoverRow || add != hoverAdd)
  17313. {
  17314. hoverTab = tab;
  17315. hoverRow = row;
  17316. hoverAdd = add;
  17317. repaint();
  17318. }
  17319. }
  17320. void PatternPicker::mouseExit (const juce::MouseEvent&)
  17321. {
  17322. hoverTab = hoverRow = -1;
  17323. hoverAdd = false;
  17324. repaint();
  17325. }
  17326. ui::Hint PatternPicker::hintAt (juce::Point<int> p)
  17327. {
  17328. ui::Hint hint;
  17329. const char* tabs[] = { TR_NOOP ("Picker: patterns"), TR_NOOP ("Picker: audio clips"), TR_NOOP ("Picker: automation clips") };
  17330. for (int t = 0; t < 3; ++t)
  17331. if (tabBounds (t).contains (p))
  17332. {
  17333. hint.text = tr (tabs[t]) + " " + tr ("[LMB] show");
  17334. return hint;
  17335. }
  17336. if (addBounds().contains (p))
  17337. {
  17338. hint.text = tr ("New pattern");
  17339. return hint;
  17340. }
  17341. const auto list = rows();
  17342. if (const auto i = rowAt (p.y); i >= 0 && list[(std::size_t) i].group) // round 190ne
  17343. {
  17344. hint.value = list[(std::size_t) i].name;
  17345. hint.text = groupSwitchBounds (i).contains (p)
  17346. ? tr ("Shown: [LMB] list the track clips in the pattern selector too (on / off)")
  17347. : tr ("Track clips: the clips of tracks whose clips own their notes, kept out of the pattern list [LMB] fold / unfold");
  17348. return hint;
  17349. }
  17350. if (const auto i = rowAt (p.y); i >= 0)
  17351. {
  17352. hint.value = list[(std::size_t) i].name;
  17353. if (list[(std::size_t) i].trackClip && list[(std::size_t) i].uses > 1)
  17354. hint.value << " " << tr ("({0} linked clips)", { juce::String (list[(std::size_t) i].uses) });
  17355. hint.text = list[(std::size_t) i].kind == ClipKind::pattern
  17356. ? tr ("Pattern: [LMB] paint it with the pencil [drag] place it on the Playlist (Shift on drop: one after another) [Ctrl+LMB] / [Shift+LMB] pick several [2xLMB] open [RMB] menu [Alt+RMB] hold to hear it")
  17357. : tr ("Clip source: [LMB] paint it with the pencil [drag] place it on the Playlist");
  17358. hint.hasMenu = list[(std::size_t) i].kind == ClipKind::pattern;
  17359. }
  17360. return hint;
  17361. }
  17362. void PatternPicker::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  17363. {
  17364. const auto rows = (int) this->rows().size();
  17365. const auto visible = juce::jmax (1, (listBottom() - headerHeight) / rowHeight);
  17366. scroll = juce::jlimit (0, juce::jmax (0, rows - visible), scroll - (int) std::round (wheel.deltaY * 6.0f));
  17367. repaint();
  17368. }
  17369. bool PlaylistComponent::flHeaders() const noexcept
  17370. {
  17371. return ! simpleHeaders && flClipLook();
  17372. }
  17373. int PlaylistComponent::flHeaderWidthNow() noexcept
  17374. {
  17375. return flClipLook() ? flPatternHeaderWidth : flHeaderWidth;
  17376. }
  17377. #include "PlaylistPoints190lw.inc" // issue #207 (round 190lw)
  17378. #include "PlaylistRange190pa.inc" // round 190pa (research190oe P14): ranges on chosen tracks
  17379. } // namespace lynx