MainComponent.cpp 584 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074
  1. #include "ui/ControllerBridge.h"
  2. #include "ui/KeyFocus.h"
  3. #include "ui/TrackIcons.h"
  4. #include "core/EscClose.h"
  5. #include "core/DetailChain.h"
  6. #include "core/MeterScale.h"
  7. #include "core/FactoryContent.h"
  8. #include "core/SoundLibrary.h"
  9. #include "ui/ExternalDrag.h"
  10. #include "ui/LabelFont.h"
  11. #include "ui/AudioClipboard.h"
  12. #include "ui/MidiClipboard.h"
  13. #include "ui/VideoTracks.h"
  14. #include "ui/AdrWindow.h"
  15. #include "ui/FirstSongTour.h" // (round 190fq: the support note waits for the Welcome screen)
  16. #include "ui/GamepadInput.h"
  17. #include "ui/ThemeSettings.h"
  18. #include "ui/ColourPicker.h"
  19. #include "core/AutoScanPolicy.h"
  20. #include "core/Crossfader.h"
  21. #include "core/RenderAhead.h"
  22. #include "core/DrawMode.h"
  23. #include "core/SessionKeys.h"
  24. #include "core/EditorLimit.h"
  25. #include "core/FirstSongTour.h"
  26. #include "core/SessionKeys.h"
  27. #include "core/FlSettings.h"
  28. #include "core/PlaylistOps.h"
  29. #include "core/ClipOps.h"
  30. #include "core/OneClickRec.h"
  31. #include "core/CountIn.h"
  32. #include "core/GrossBeatLocator.h"
  33. #include "core/MixerOps.h"
  34. #include "core/NoteNames.h"
  35. #include "core/LiveNote.h"
  36. #include "core/LiveKeys.h"
  37. #include "core/KeyGuess.h"
  38. #include "core/ProjectKey.h"
  39. #include "core/ScaleKeys.h"
  40. #include "core/SimplePads.h"
  41. #include "core/SamplerPage.h"
  42. #include "core/SessionOps.h"
  43. #include "ui/FileChoosers.h"
  44. #include "ui/ProjectLoading.h"
  45. #include "ui/UiTrace.h"
  46. #include "core/LoadTrace.h"
  47. #include "ui/MainComponent.h"
  48. #include "ui/Motion.h"
  49. #include "ui/RemoteControlSettings.h"
  50. #include "ui/NativeChild.h"
  51. #include "core/PlaylistOps.h"
  52. #include "core/Performance.h"
  53. #include "core/TransportEdit.h"
  54. #include "ui/CrashReporter.h"
  55. #include "ui/DanceView.h"
  56. #include "engine/AudioLogger.h"
  57. #include "ui/PluginSkin.h"
  58. #include "platform/Paths.h"
  59. #include "ui/SetupWizard.h"
  60. #include "ui/DemoMode.h" // (round 190np)
  61. #include "core/FlPluginDb.h"
  62. #include "core/Preferences.h"
  63. #include "core/EditorPolish.h"
  64. #include "ui/HistoryPanel.h"
  65. #include "ui/PolyEditor.h" // (round 190lo)
  66. #include "ui/LyricsPanel.h"
  67. #include "ui/ReferenceMatchPanel.h"
  68. #include "ui/VersionsPanel.h"
  69. #include "ui/PluginsOffPanel.h"
  70. #include "ui/MissingFilesDialog.h"
  71. #include "ui/SettingsDialog.h"
  72. #include "ui/SimpleDock.h"
  73. #include "ui/PluginManager.h"
  74. #include "ui/ShortcutManager.h"
  75. #include "ui/WaveformView.h"
  76. #include "ui/WorkflowExtras.h" // round 190iu (issues #186, #191)
  77. #include "ui/QuickAddPalette.h"
  78. #include "ui/QuickPick.h"
  79. #include "core/FolderWatcher.h"
  80. #include "ui/PluginPickerView.h"
  81. #include "ui/ProjectPickerView.h"
  82. #include "ui/PatcherEditor.h"
  83. #include "ui/ToolWindow.h"
  84. #include "ui/RackEditor.h"
  85. #include "ui/HelixEditor.h"
  86. #include "ui/LoopStarterWindow.h"
  87. #include "ui/WindowOwner.h"
  88. #include "engine/PluginSandbox.h"
  89. #include "platform/FileTypes.h"
  90. #include "platform/CrashGuard.h"
  91. #include "platform/LinuxRealtime.h"
  92. #include "platform/Package.h"
  93. #include "engine/Text.h"
  94. #include "core/MetronomeVoice.h"
  95. #include "core/RackOps.h"
  96. #include "core/Templates.h"
  97. #include "ui/NewProjectDialog.h"
  98. #include "ui/PluginMonitorWindow.h"
  99. #include "ui/SimpleLook.h"
  100. #include "ui/TouchKeyboard.h"
  101. #include "engine/MidiFileIo.h"
  102. #include "engine/ProjectFile.h"
  103. #include "ui/ExtendedHintPanel.h"
  104. #include "engine/ProjectDowngrade.h"
  105. #include "engine/ProjectPackage.h"
  106. #include "engine/SessionPack.h"
  107. #include "ui/SessionDialogs.h"
  108. #include "engine/LiveSessions.h"
  109. #include "ui/LiveChat.h"
  110. #include "ui/LiveRemoteUi.h"
  111. #include "core/ProjectSafety.h"
  112. #include "core/MissingFiles.h"
  113. #include "ui/AutomationUi.h"
  114. #include "ui/RemoteControl.h"
  115. #include "ui/ChannelSettings.h"
  116. #include "core/ClipLauncher.h"
  117. #include "ui/ClipGridComponent.h"
  118. #include "ui/Dialogs.h"
  119. #include "ui/DialogFrame.h"
  120. #include "ui/EventEditor.h"
  121. #include "ui/EditorTools.h"
  122. #include "ui/AudioEditor.h"
  123. #include "ui/TempoTapper.h"
  124. #include "ui/ExportDialog.h"
  125. #include "engine/AacEncoder.h"
  126. #include "ui/AudioCheck.h"
  127. #include "ui/AlsExportDialog.h"
  128. #include "ui/DawProjectExport.h" // round 190jf (B22)
  129. #include "ui/OtherAppsExport.h"
  130. #include "ui/FlStudioExportDialog.h"
  131. #include "ui/FruitySlicerEditor.h"
  132. #include "ui/SlicexEditor.h"
  133. #include "core/NativeEngines.h"
  134. #include "ui/ParametricEqEditor.h"
  135. #include "ui/PluginWindow.h"
  136. #include "ui/I18n.h"
  137. #include "ui/Theme.h"
  138. #include "ui/TypeAhead.h"
  139. #include "ui/WaveformView.h"
  140. #include "ui/WorkflowExtras.h" // round 190iu (issues #186, #191)
  141. #include "ui/TextCache.h" // round 190ki: the tempo readout's widths
  142. #include "core/HintMarkup.h"
  143. #include "core/SongStats.h"
  144. #if JUCE_PLUGINHOST_VST3
  145. namespace juce
  146. {
  147. // cmake/LynxPatchJuce.cmake fix 20 (round 177b): LYNX's items at the top of a VST3 plugin's parameter context menu
  148. extern void (*lynxVst3ParamMenuHook) (AudioPluginInstance&, int, PopupMenu&);
  149. } // namespace juce
  150. #endif
  151. namespace lynx
  152. {
  153. // round 177b: the engine LYNX's VST3 parameter-menu hook uses (set while the main window lives)
  154. static AudioEngine*& vst3MenuEngine()
  155. {
  156. static AudioEngine* engine = nullptr;
  157. return engine;
  158. }
  159. namespace
  160. {
  161. using workspace::Panel;
  162. constexpr Panel panelOrder[] = { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser };
  163. const char* panelAction (Panel p)
  164. {
  165. switch (p)
  166. {
  167. case Panel::playlist: return "panel.playlist";
  168. case Panel::channelRack: return "panel.channelRack";
  169. case Panel::pianoRoll: return "panel.pianoRoll";
  170. case Panel::mixer: return "panel.mixer";
  171. case Panel::browser: return "panel.browser";
  172. }
  173. return "";
  174. }
  175. juce::String panelName (Panel p)
  176. {
  177. switch (p)
  178. {
  179. case Panel::playlist: return "Playlist";
  180. case Panel::channelRack: return "Channel Rack";
  181. case Panel::pianoRoll: return "Piano Roll";
  182. case Panel::mixer: return "Mixer";
  183. case Panel::browser: return "Browser";
  184. }
  185. return {};
  186. }
  187. } // namespace
  188. MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
  189. : persistent (restoreUserSettings),
  190. engine (e),
  191. rack (e),
  192. pianoRoll (e),
  193. playlist (e),
  194. mixer (e),
  195. browser (e)
  196. {
  197. if (startupMark != nullptr) startupMark ("main window: panels constructed (rack, piano roll, playlist, mixer, browser)"); // (round 190gd)
  198. rackcards::install(); // (round 183c: racks show as their own card in the Device View)
  199. helixcards::install(); // (round 190ja: Helix shows as Live's Wavetable in the Device View)
  200. heldKeys.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on, true); });
  201. connectBrowser (browser);
  202. if (restoreUserSettings) // (issue #104: the Plugin database folder on disk; changes made in LYNX are written to it)
  203. {
  204. quickpick::installPluginDatabase (engine);
  205. // round 190bf: and a change made to it in the file manager shows in the Browser by itself, about a second
  206. // later, as in FL (fl190be Q2); the menus and the picker read it when they next open
  207. const auto root = quickpick::pluginDatabaseFolder();
  208. auto safe = juce::Component::SafePointer<MainComponent> (this);
  209. pluginDatabaseWatcher = std::make_unique<folderwatch::Watcher> (
  210. std::vector<std::string> { root.getChildFile ("Effects").getFullPathName().toStdString(), root.getChildFile ("Generators").getFullPathName().toStdString() },
  211. [safe] {
  212. juce::MessageManager::callAsync ([safe] {
  213. if (safe != nullptr)
  214. safe->readPluginDatabaseAgain();
  215. });
  216. });
  217. quickpick::setPluginDatabaseWatched (true); // (round 190mf: the menus read it again only after a change)
  218. }
  219. addChildComponent (updateBar);
  220. addChildComponent (remoteControlBar);
  221. remoteControlBar.setFont (theme::font (theme::type::small, true));
  222. remoteControlBar.setColour (juce::Label::backgroundColourId, theme::colour::accent.withAlpha (0.16f));
  223. remoteControlBar.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  224. remoteControlBar.setJustificationType (juce::Justification::centredLeft);
  225. updateBar.onVisibilityChanged = [this] { resized(); };
  226. if (restoreUserSettings) // (the real window: Update saves the project as on quit and reopens it)
  227. updater::setHost ({ [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  228. if (safe != nullptr)
  229. safe->confirmDiscard (std::move (then));
  230. },
  231. [safe = juce::Component::SafePointer<MainComponent> (this)] {
  232. return safe != nullptr ? safe->currentFile : juce::File();
  233. } });
  234. mixeroptions::changed = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  235. if (safe != nullptr)
  236. {
  237. safe->saveUiSettings();
  238. safe->playlist.repaint();
  239. }
  240. };
  241. workflowextras::bind (&engine);
  242. workflowextras::onChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // round 190iu
  243. if (safe != nullptr)
  244. {
  245. safe->saveUiSettings();
  246. safe->playlist.refreshViewOptions(); // (round 190jq: header width, pointer click, automation clip lanes)
  247. if (trackonly::active())
  248. safe->hidePanelForTrackOnly();
  249. }
  250. };
  251. mixeroptions::setShowUsedOnly = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  252. if (safe != nullptr)
  253. safe->mixer.getStripsForSnapshot().setShowUsedOnly (on);
  254. };
  255. mixeroptions::setShowLoudness = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  256. if (safe != nullptr)
  257. safe->mixer.getStripsForSnapshot().setShowLoudness (on);
  258. };
  259. mixeroptions::setShowStripInserts = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  260. if (safe != nullptr)
  261. safe->mixer.getStripsForSnapshot().setShowStripInserts (on);
  262. };
  263. mixeroptions::selectPlaylistTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks) {
  264. if (safe != nullptr)
  265. safe->playlist.selectTracks (tracks);
  266. };
  267. mixeroptions::renderTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks,
  268. std::function<void (const std::vector<juce::File>&)> done) {
  269. if (safe != nullptr)
  270. safe->mixer.selectTrack (0); // (round 190my: FL's render window selects the Master, see exportAudio)
  271. if (safe != nullptr)
  272. showExportDialogForTracks (safe->engine, safe->currentFile.getParentDirectory(), safe->projectName, tracks, std::move (done));
  273. };
  274. // round 190np: LYNX_EMPTY_HINTS=1 shows the empty-state hints in an off-screen window too (--paintbench measures them)
  275. onboardingOn = ! persistent && juce::SystemStats::getEnvironmentVariable ("LYNX_EMPTY_HINTS", {}) == "1";
  276. if (persistent)
  277. {
  278. engine.getRollingLog().setEnabled (true); // on by default, as in FL (Tools › Audio logger)
  279. loadUiSettings();
  280. loadOnboarding(); // round 190np: the welcome card's answer, the Next-3 ticks, the tips seen
  281. onboardingOn = true;
  282. if (std::exchange (showExtendedHintAfterLoad, false)) // round 190mr (DF-49)
  283. showExtendedHint (true);
  284. // the start-up song follows Options › Mixer too (round 163) and the automatic crossfades of new projects (166e)
  285. engine.setSong (makeNewProject());
  286. skin::onStyleSettingsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // an editor's own style was picked
  287. if (safe != nullptr) safe->saveUiSettings();
  288. };
  289. messages::onChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // "Remember my choice" / Manage messages
  290. if (safe != nullptr) safe->saveUiSettings();
  291. };
  292. loadKeyMap();
  293. startSession();
  294. if (BrowserComponent::sampleBrowserWasOpen()) // it was open when LYNX closed (round 163)
  295. juce::Timer::callAfterDelay (800, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  296. if (safe != nullptr && findToolWindow ("sampleBrowser") == nullptr)
  297. safe->openSampleBrowser();
  298. });
  299. EditorGlobals::get().onOptionsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // Follow on/off
  300. if (safe != nullptr) safe->saveUiSettings();
  301. };
  302. }
  303. if (startupMark != nullptr) startupMark ("main window: settings, key map, start-up song, session");
  304. PianoRollComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  305. PlaylistComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  306. // FL's middle + right click tool menu (round 190mp, DE-62): the editor's main menu = its window's ▾ items
  307. pianoRoll.mainMenu = [this] { juce::PopupMenu m; addPanelMenuItems (Panel::pianoRoll, m); return m; };
  308. playlist.mainMenu = [this] { juce::PopupMenu m; addPanelMenuItems (Panel::playlist, m); return m; };
  309. pianoRoll.onNoteNamesChanged = [this] { saveUiSettings(); };
  310. // FL's EEPlayBtnClick (FLEngine 0xe4bd40, REA round 169f): Pattern mode first (also while the song plays), then the
  311. // play / pause of the transport. EEPlayBtnMouseDown (0xe4bda0), right button: FL's Stop (FUN_011ca520 (0, 0), the very
  312. // call of the toolbar's StopBtnClick), which in FL goes back to where playback started, pressed again to the start
  313. // (measured in FL 2026, round 169f, Pattern mode after a ruler click)
  314. pianoRoll.onPlayPause = [this] {
  315. if (engine.getSong().mode != PlayMode::pattern)
  316. toggleMode();
  317. playPause();
  318. };
  319. pianoRoll.onPlayRightClick = [this] { stopAndRewind (false); }; // FL's Stop (FUN_011ca520 (0, 0)), issue #169
  320. pianoRoll.onBrowseScores = [this] { // (round 168g: the Piano roll's File › Browse scores)
  321. showPanel (Panel::browser);
  322. browser.showScores();
  323. };
  324. EventEditorHooks::onBrowseAutomations = [this] { // (the Event editor's File › Browse automations: FL's Scores\\Automation)
  325. showPanel (Panel::browser);
  326. browser.showScores ("Automation");
  327. };
  328. newButton.setTooltip (tr ("New project") + " (Ctrl+N)");
  329. newButton.onClick = [this] { newProject(); };
  330. openButton.setTooltip (tr ("Open project") + " (Ctrl+O)");
  331. openButton.onClick = [this] { chooseFileToOpen(); };
  332. saveButton.setTooltip (tr ("Save project") + " (Ctrl+S)");
  333. saveButton.onClick = [this] { save (false); };
  334. exportButton.setTooltip (tr ("Export audio: WAV, FLAC or OGG") + " (Ctrl+R)");
  335. exportButton.onClick = [this] { exportAudio(); };
  336. auto withKey = [this] (const juce::String& text, const char* id) {
  337. const auto key = shortcutText (id).trim();
  338. return key.isEmpty() ? text : text + " (" + key + ")";
  339. };
  340. undoButton.setTooltip (withKey (tr ("Undo"), "edit.undo"));
  341. undoButton.onClick = [this] { flUndo(); }; // FL's toolbar Undo is its Edit › Undo (UndoAction)
  342. undoButton.onRightClick = [this] { showHistory(); };
  343. redoButton.setTooltip (withKey (tr ("Redo"), "edit.redo"));
  344. redoButton.onClick = [this] { undoRedo (true); };
  345. redoButton.onRightClick = [this] { showHistory(); };
  346. audioEditorButton.setTooltip (tr ("Open audio editor / New audio editor"));
  347. audioEditorButton.onClick = [this] { openMasterAudioEditor (false); };
  348. audioEditorButton.onRightClick = [this] { openMasterAudioEditor (true); };
  349. // FL's toolbar picker button (round 171c): a click opens the Plugin picker (F8); a right-click LYNX's quick-add palette
  350. pluginPickerButton.setTooltip (withKey (tr ("Plugin picker: every plugin as a picture; drag one onto the Channel Rack or the Mixer (right-click: quick-add palette)"),
  351. "view.pluginPicker"));
  352. pluginPickerButton.onClick = [this] { togglePluginPicker(); };
  353. pluginPickerButton.onRightClick = [this] { showQuickAdd(); };
  354. // transport: Play toggles play / stop-and-back; Stop returns to the start; double-click Stop = all notes off
  355. playButton.setTooltip (tr ("Play; pressed again, stops and goes back to where it started") + " (Space; Ctrl+Space pauses)");
  356. // round 190np: the transport's controls by component ID (--demo, the tips' anchors)
  357. playButton.setComponentID ("toolbar.play");
  358. stopButton.setComponentID ("toolbar.stop");
  359. recordButton.setComponentID ("toolbar.record");
  360. patternModeButton.setComponentID ("toolbar.patternMode");
  361. songModeButton.setComponentID ("toolbar.songMode");
  362. tempoDisplay.setComponentID ("toolbar.tempo");
  363. playButton.onClick = [this] {
  364. // round 190jj: the Simple capsule's Play shows Pause while the song runs (BandLab), and pauses
  365. if (toolbarlayout::transportStates (toolbarLook).stopWhilePlaying
  366. && (engine.getTransport().playing.load() || engine.isCountingIn() || engine.isWaitingForInput()))
  367. playPause();
  368. else
  369. playStop();
  370. };
  371. stopButton.setTooltip (tr ("Stop and return to the start (double-click: back to the start and all notes off)"));
  372. stopButton.onClick = [this] { stopAndRewind(); };
  373. stopButton.onDoubleClick = [this] { // FL-like: a double Stop goes back to the very start (and silences hanging notes)
  374. engine.panic();
  375. stopAndRewind (true);
  376. };
  377. stopButton.onRightClick = [this] { showStopMenu(); };
  378. output.onModeChanged = [this] { saveUiSettings(); };
  379. hintBar.onMenu = [this] { return makeToolbarMenu(); }; // (round 190kn: FL's hint bar right-click = the toolbars menu)
  380. // round 190kn (FL's CPU panel): double-click = Plugin performance monitor; the menu's refresh rate is kept
  381. perfMeter.onOpenMonitor = [this] { showPluginMonitor (engine); };
  382. perfMeter.onRefreshChanged = [this] { saveUiSettings(); };
  383. recordButton.setOnColour (theme::colour::record);
  384. recordButton.setIconColour (theme::colour::record.withMultipliedSaturation (0.8f));
  385. recordButton.onClick = [this] { toggleRecording(); };
  386. recordMenuButton.setTooltip (tr ("Recording options: what to record"));
  387. recordMenuButton.onClick = [this] { showRecordMenu(); };
  388. recordButton.onRightClick = [this] { showRecordMenu(); };
  389. // Pattern / Song: a two-segment switch (L toggles); right-click shows the matching panel
  390. // as in FL, a two-line switch in front of the transport buttons: pattern on top, song below
  391. patternModeButton.setText (tr ("Pattern"));
  392. songModeButton.setText (tr ("Song"));
  393. for (auto* b : { &patternModeButton, &songModeButton })
  394. {
  395. b->setOnColour (theme::colour::bg6);
  396. b->setIconColourWhenOn (theme::colour::textPrimary);
  397. }
  398. patternModeButton.setTooltip (tr ("Pattern mode: plays the current pattern in a loop") + " (L)\n" + tr ("Right-click: show the Channel Rack"));
  399. songModeButton.setTooltip (tr ("Song mode: plays the Playlist arrangement") + " (L)\n" + tr ("Right-click: show the Playlist"));
  400. patternModeButton.onClick = [this] {
  401. if (engine.getSong().mode != PlayMode::pattern)
  402. toggleMode();
  403. };
  404. songModeButton.onClick = [this] {
  405. if (engine.getSong().mode != PlayMode::song)
  406. toggleMode();
  407. };
  408. patternModeButton.onRightClick = [this] { showPanel (Panel::channelRack); };
  409. songModeButton.onRightClick = [this] { showPanel (Panel::playlist); };
  410. metronomeButton.setClickingTogglesState (true);
  411. metronomeButton.setOnColour (theme::colour::bg6);
  412. metronomeButton.setIconColourWhenOn (theme::colour::accent);
  413. metronomeButton.setTooltip (tr ("Metronome"));
  414. metronomeButton.onClick = [this] {
  415. engine.getTransport().metronome.store (metronomeButton.getToggleState());
  416. saveUiSettings(); // FL keeps it (ToolbarForm "MetronomeBtn", issue #152)
  417. };
  418. midiLight.onReconnect = [this] {
  419. engine.reconnectMidiInputs();
  420. midiInputTicks = 0; // shows the reopened inputs at the next tick
  421. };
  422. metronomeButton.onRightClick = [this] { showMetronomeMenu(); };
  423. // FL's MultiLinkBtn (round 177b-4): lit while "Multilink to controllers" is on; [RMB] FL's MLWheelMenu (round 190df)
  424. multilinkButton.setFlat (true);
  425. multilinkButton.setWantsKeyboardFocus (false);
  426. multilinkButton.onClick = [this] { runAction ("options.multilink"); };
  427. multilinkButton.onRightClick = [this] {
  428. auto menu = getMultilinkMenuForSnapshot();
  429. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&multilinkButton));
  430. };
  431. typingPianoButton.setOnColour (theme::colour::bg6);
  432. typingPianoButton.setIconColourWhenOn (theme::colour::accent);
  433. typingPianoButton.onClick = [this] { toggleTypingPiano(); };
  434. typingPianoButton.onRightClick = [this] { showTypingPianoMenu(); };
  435. // count-in and wait-for-input switches next to the metronome, as in FL's recording panel
  436. for (auto* b : { &countInButton, &waitInputButton })
  437. {
  438. b->setOnColour (theme::colour::bg6);
  439. b->setIconColourWhenOn (theme::colour::accent);
  440. }
  441. countInButton.onClick = [this] { runAction ("record.countIn"); };
  442. waitInputButton.onClick = [this] { runAction ("record.waitForInput"); };
  443. // FL (manual "Toolbar panels", round 190ld): "Recording Count-in ... Right-Click to choose bars"; Wait for input's
  444. // right-click has "Only when recording" and "Respect recording filter"
  445. countInButton.onRightClick = [this] { makeCountInMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&countInButton)); };
  446. waitInputButton.onRightClick = [this] { makeWaitInputMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&waitInputButton)); };
  447. // round 170e2: FL's "Blend recorded notes" switch (on = overdub, off = replace) and its tempo tapper button
  448. blendButton.setOnColour (theme::colour::bg6);
  449. blendButton.setIconColourWhenOn (theme::colour::accent);
  450. blendButton.onClick = [this] { runAction ("record.blend"); };
  451. tapTempoButton.onClick = [this] {
  452. if (isClipLaunchWorkflow())
  453. liveTap(); // (round 190lr, DL-49: Live's Tap box taps)
  454. else
  455. openTempoTapper (engine);
  456. };
  457. tapTempoButton.onRightClick = [this] {
  458. if (isClipLaunchWorkflow())
  459. showLiveTapMenu();
  460. };
  461. // round 170e3: loop record, step edit and punch in/out as switches beside them
  462. for (auto* b : { &loopRecordButton, &stepEditButton, &punchButton })
  463. {
  464. b->setOnColour (theme::colour::bg6);
  465. b->setIconColourWhenOn (theme::colour::accent);
  466. }
  467. loopRecordButton.onClick = [this] { runAction ("record.loop"); };
  468. stepEditButton.onClick = [this] { runAction ("record.stepEdit"); };
  469. punchButton.onClick = [this] { runAction (toolbarLook == toolbarlayout::Look::live ? "record.punchIn" : "record.punch"); }; // (round 190lx: Live's Punch-In)
  470. for (int i = 0; i < workspace::panelCount; ++i)
  471. {
  472. const auto panel = (Panel) i;
  473. auto& b = panelButtons[(std::size_t) i];
  474. b.setFlat (true);
  475. b.setOnColour (theme::colour::bg5);
  476. b.setIconColourWhenOn (theme::colour::textPrimary);
  477. b.setTooltip (panelName (panel) + " (" + keys::displayString (keyMap.chordsFor (panelAction (panel)).empty() ? keys::Chord {}
  478. : keyMap.chordsFor (panelAction (panel)).front()) + ")\n"
  479. + tr ("Click: show, focus or hide. Right-click: show maximized"));
  480. b.onClick = [this, panel] { togglePanel (panel); };
  481. b.onRightClick = [this, panel] {
  482. showPanel (panel);
  483. if (! workspace.isMaximised (panel) && ! workspace.isDetached (panel))
  484. workspace.toggleMaximised (panel);
  485. refreshPanelButtons();
  486. };
  487. }
  488. patternBox.setTooltip (tr ("Current pattern (Numpad +/-: next/previous, F4: next empty, F2: rename)"));
  489. patternBox.onStep = [this] (int delta) { stepPatternFromSelector (delta); };
  490. gridBox.setScrollWheelEnabled (true);
  491. patternBox.onChange = [this]
  492. {
  493. const auto index = patternBox.getSelectedItemIndex();
  494. if (index >= 0 && index != engine.getSong().currentPattern)
  495. selectPattern (index);
  496. };
  497. newPatternButton.setTooltip (tr ("New pattern"));
  498. newPatternButton.onClick = [this]
  499. {
  500. engine.editSong ([] (Song& s) {
  501. Pattern p;
  502. p.name = newPatternName (s);
  503. s.patterns.push_back (std::move (p));
  504. s.currentPattern = (int) s.patterns.size() - 1;
  505. });
  506. };
  507. swingSlider.setRange (0.0, 1.0, 0.01);
  508. swingSlider.setDoubleClickReturnValue (true, 0.0);
  509. swingSlider.setValue (engine.getSong().swing, juce::dontSendNotification);
  510. swingSlider.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  511. swingSlider.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  512. swingSlider.onValueChange = [this] { engine.editSong ([v = (float) swingSlider.getValue()] (Song& s) { s.swing = v; }); };
  513. swingSlider.setTooltip (tr ("Swing of the Channel Rack (all channels)"));
  514. swingSlider.setMouseClickGrabsKeyboardFocus (false);
  515. swingSlider.setWantsKeyboardFocus (false);
  516. patternMenuButton.setTooltip (tr ("Pattern: rename, color, clone, insert, split, length, delete"));
  517. patternMenuButton.onClick = [this] { showPatternMenu(); };
  518. // the workspace panels
  519. rack.onOpenPianoRoll = [this] { openPianoRoll(); };
  520. // round 190mk (DE-33, FL's manual): a click on a channel's piano roll preview shows / hides the Piano roll; a right-click
  521. // opens it scrolled to the clicked spot
  522. rack.onPreviewClick = [this] (int row) {
  523. if (row >= 0 && workspace.isPanelVisible (Panel::pianoRoll))
  524. togglePanel (Panel::pianoRoll);
  525. else
  526. openPianoRoll();
  527. };
  528. rack.onPreviewRightClick = [this] (int, double tick) {
  529. openPianoRoll();
  530. pianoRoll.centreOnTick (tick, 0.27); // (FL: the clicked spot about 27 % in from the left, capture 190mk A2.3)
  531. };
  532. mixerinput::openAudioSettings = [this] { openSettings ((int) SettingsPage::audio); };
  533. PatcherWindows::onBrowsePluginDatabase = [this] (bool) {
  534. showPanel (Panel::browser);
  535. browser.showPluginDatabaseForSnapshot(); // (its Generators and Effects folders open)
  536. if (auto* w = getTopLevelComponent())
  537. w->toFront (true);
  538. };
  539. rack.onOpenMixerInsert = [this] (int insert) { // double-click on a channel's route box
  540. showPanel (Panel::mixer);
  541. mixer.selectTrack (insert);
  542. };
  543. playlist.onLinkedMixerTrack = [this] (int insert) { // round 190ft (FL FUN_012e3aa0): only while the mixer shows
  544. if (mixer.isShowing())
  545. mixer.selectTrack (insert);
  546. };
  547. openMixerInsertHandler() = rack.onOpenMixerInsert; // and on the channel window's TRACK box (round 168s)
  548. channelWrapperItemsHandler() = [this] (int channel, wrappermenu::Spec& spec) { rack.fillWindowMenu (channel, spec); }; // (round 190in, R8)
  549. locateInBrowserHandler() = [this] (const juce::File& file) { // (the sampler's File row, round 190df)
  550. showPanel (Panel::browser);
  551. browser.locateFile (file);
  552. };
  553. // the Sampler waveform menu's "Open in new sampler channel" / "... Fruity Granulizer channel" (round 190ey): the file in
  554. // a new channel of that kind (as the audio clip menu's Open in a new Sampler channel), its editor open
  555. openInNewChannelHandler() = [this] (const juce::File& file, InstrumentKind kind) {
  556. if (! file.existsAsFile())
  557. return;
  558. // round 190gk: "... Fruity Slicer channel" / "... Slicex channel": FL loads the plugin's template channel, then
  559. // the sample into it (SBONewMenuClick 0x11f8330, REA 190fl); LYNX's new channel of that kind, and its editor
  560. // loads the file as its own Load does (slices / regions as on a load)
  561. if (kind == InstrumentKind::fruityslicer || kind == InstrumentKind::slicex)
  562. {
  563. auto made = natives::makeChannel (kind, flStudioAccess());
  564. if (! made)
  565. return;
  566. // round 190gw (live check 190gu B3): the channel takes the sample's name, " #n" when taken
  567. made->name = samplerpage::openInNewChannelName (engine.getSong(), file.getFileNameWithoutExtension().toStdString());
  568. const auto added = rack.addChannel (*made, false);
  569. if (kind == InstrumentKind::slicex)
  570. loadSlicexSampleWhenOpened (added, file.getFullPathName());
  571. else
  572. loadSampleWhenOpened (added, file.getFullPathName());
  573. showPanel (Panel::channelRack);
  574. rack.toggleEditor (added, false);
  575. loadSlicexSampleWhenOpened (-1, {}); // (an editor that did not open forgets it)
  576. loadSampleWhenOpened (-1, {});
  577. return;
  578. }
  579. ChannelDef c;
  580. c.instrument = kind;
  581. audioclips::loadSampleInto (c, file.getFullPathName().toStdString(), file.getFileNameWithoutExtension().toStdString());
  582. c.instrument = kind; // (loadSampleInto keeps the Granulizer; a sampler stays one)
  583. c.name = samplerpage::openInNewChannelName (engine.getSong(), file.getFileNameWithoutExtension().toStdString()); // (round 190gw)
  584. const auto added = rack.addChannel (c, false);
  585. showPanel (Panel::channelRack);
  586. rack.toggleEditor (added, false);
  587. };
  588. mixer.onInstrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); };
  589. rackViewport.setViewedComponent (&rack, false);
  590. rackViewport.setScrollBarsShown (true, true);
  591. workspace.setContent (Panel::playlist, playlistArea, "Playlist", Icon::playlist);
  592. workspace.setContent (Panel::channelRack, rackViewport, "Channel Rack", Icon::channelRack);
  593. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll);
  594. workspace.setContent (Panel::mixer, mixer, "Mixer", Icon::mixer);
  595. workspace.setContent (Panel::browser, browser, "Browser", Icon::browser);
  596. workspace.setTitleTooltip (Panel::channelRack, tr ("Shift+wheel here changes the pattern"));
  597. // FL keeps the channel filter, the global swing and the graph editor switch in the rack's title bar
  598. rackFilterBox.text = rack.filterName();
  599. rackFilterBox.onClick = [this] { rack.showFilterMenu (&rackFilterBox); };
  600. rack.onFilterChanged = [this] {
  601. rackFilterBox.text = rack.filterName();
  602. rackFilterBox.repaint();
  603. rackGraphButton.setToggleState (rack.areGraphLanesShown(), juce::dontSendNotification);
  604. rackPianoRollButton.setToggleState (rack.isPianoRollView(), juce::dontSendNotification);
  605. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  606. };
  607. rackGraphButton.setClickingTogglesState (false);
  608. rackGraphButton.onClick = [this] { rack.toggleGraphLanes(); };
  609. // the step sequencer / piano-roll view switch (FL keeps it in the rack's title bar too)
  610. rackPianoRollButton.setClickingTogglesState (false);
  611. rackPianoRollButton.setOnColour (theme::colour::bg6);
  612. rackPianoRollButton.setIconColourWhenOn (theme::colour::accent);
  613. rackPianoRollButton.onClick = [this] { runAction ("rack.pianoRollView"); };
  614. ui::setHint (rackPianoRollButton, tr ("Piano-roll view: every channel shows its notes as a miniature piano roll (click one to edit it) "
  615. "instead of the step buttons; click again for the steps"));
  616. rackTitleTools.addAndMakeVisible (rackPianoRollButton);
  617. // Follow (issue #12): a long pattern pages along with the playing step
  618. rackFollowButton.setClickingTogglesState (false);
  619. rackFollowButton.setOnColour (theme::colour::bg6);
  620. rackFollowButton.setIconColourWhenOn (theme::colour::accent);
  621. rackFollowButton.setWantsKeyboardFocus (false);
  622. rackFollowButton.setMouseClickGrabsKeyboardFocus (false);
  623. rackFollowButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  624. rackFollowButton.setTooltip (tr ("Follow: a pattern longer than the Channel Rack pages along with the playing step; off, it stays where you scrolled"));
  625. ui::setQuickTip (rackFollowButton, tr ("Follow the playhead"));
  626. rackFollowButton.onClick = [this] { runAction ("rack.follow"); };
  627. rackTitleTools.addAndMakeVisible (rackFollowButton);
  628. // FL's Loop button (round 165f-rack): click switches the pattern's channel looping, right-click its loop type and burns
  629. rackLoopButton.setClickingTogglesState (false);
  630. rackLoopButton.setOnColour (theme::colour::bg6);
  631. rackLoopButton.setIconColourWhenOn (theme::colour::accent);
  632. rackLoopButton.onClick = [this] { rack.toggleLooping(); };
  633. rackLoopButton.onRightClick = [this] { rack.showLoopMenu (&rackLoopButton); };
  634. ui::setHint (rackLoopButton, tr ("Channel looping: channels shorter than the pattern repeat to its end (polyrhythms) [LMB] on / off "
  635. "[RMB] loop type (step channels, all channels, advanced) and Burn to pattern"));
  636. rackTitleTools.addAndMakeVisible (rackLoopButton);
  637. // Loop Starter (round 168b; FL 25's dice in the Channel Rack): a drum loop of the genre's kit, re-rolled with dice
  638. rackLoopStarterButton.setWantsKeyboardFocus (false);
  639. rackLoopStarterButton.onClick = [this] { loopstarterui::open (engine); };
  640. ui::setHint (rackLoopStarterButton, tr ("Loop Starter: pick a genre and get a drum loop (kit channels with steps) to re-roll and send to the Playlist"));
  641. rackTitleTools.addAndMakeVisible (rackLoopStarterButton);
  642. // the pattern selector (issue #9): change the pattern the rack edits right from its title bar
  643. rackPatternSelector.onStep = [this] (int delta) { stepPatternFromSelector (delta); };
  644. rackPatternSelector.onMenu = [this] { showRackPatternList(); };
  645. ui::setHint (rackPatternSelector, tr ("Pattern the Channel Rack edits: [LMB] on the name: the list of patterns, on the arrows: previous / next [Wheel] step") + " " + tr ("[LMB] drag up / down: step through the patterns"));
  646. rackTitleTools.addAndMakeVisible (rackPatternSelector);
  647. rackTitleTools.addAndMakeVisible (rackFilterBox);
  648. rackTitleTools.addAndMakeVisible (swingSlider);
  649. // the pattern length in bars (issue #12)
  650. rackLengthBox.onSet = [this] (int bars) {
  651. const auto index = engine.getSong().currentPattern;
  652. const auto ticks = (std::int64_t) juce::jlimit (0, 999, bars) * engine.getSong().barTicks();
  653. if (index >= 0 && index < (int) engine.getSong().patterns.size() && engine.getSong().patterns[(std::size_t) index].lengthTicks != ticks)
  654. engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; });
  655. refreshRackLengthBox();
  656. };
  657. rackLengthBox.onMenu = [this] { showPatternLengthMenu(); };
  658. ui::setHint (rackLengthBox, tr ("Pattern length in bars: [LMB] drag or [Wheel] change it [2xLMB] automatic (from the notes) [RMB] menu"));
  659. ui::setQuickTip (rackLengthBox, tr ("Pattern length (bars)"));
  660. rackTitleTools.addAndMakeVisible (rackLengthBox);
  661. rackTitleTools.addAndMakeVisible (rackGraphButton);
  662. rackTitleTools.layout = [this] {
  663. auto r = rackTitleTools.getLocalBounds();
  664. rackPatternSelector.setBounds (r.removeFromLeft (rackPatternSelectorWidth).reduced (0, 3));
  665. r.removeFromLeft (6);
  666. rackFilterBox.setBounds (r.removeFromLeft (rackFilterBoxWidth).reduced (0, 3));
  667. r.removeFromLeft (4);
  668. swingSlider.setBounds (r.removeFromLeft (26));
  669. r.removeFromLeft (4);
  670. rackLengthBox.setBounds (r.removeFromLeft (rackLengthBoxWidth).reduced (0, 3));
  671. r.removeFromLeft (4);
  672. rackGraphButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  673. r.removeFromLeft (4);
  674. rackPianoRollButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  675. r.removeFromLeft (4);
  676. rackFollowButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  677. r.removeFromLeft (4);
  678. rackLoopButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  679. r.removeFromLeft (4);
  680. rackLoopStarterButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  681. };
  682. workspace.setTitleAccessory (Panel::channelRack, &rackTitleTools, rackTitleToolsWidth);
  683. workspace.setTitleAccessory (Panel::mixer, &mixer.getLayoutBox(), MixerLayoutBox::width); // FL's "Mixer layout" (issue #52)
  684. mixer.getStripsForSnapshot().onLayoutChanged = [this] {
  685. mixer.getLayoutBox().repaint();
  686. mixer.selectTrack (mixer.getStripsForSnapshot().getSelectedTrack()); // keep the selected strip in view
  687. saveUiSettings();
  688. };
  689. workspace.onPanelMenu = [this] (Panel panel, juce::PopupMenu& menu) { addPanelMenuItems (panel, menu); };
  690. workspace.onFocusChanged = [this] (Panel panel) {
  691. refreshPanelButtons();
  692. // another panel took over (a click, F5..F9): the Browser's search box gives the keys back (issue #9)
  693. if (panel != Panel::browser)
  694. browser.leaveSearchBox();
  695. };
  696. workspace.onKeyInDetachedWindow = [this] (const juce::KeyPress& key) { return keyPressed (key); };
  697. PluginWindows::setDockWorkspace (&workspace); // FL's docked plugin windows float there (issue #116, developer switch)
  698. setEditorDock (&workspace); // and LYNX's own editor windows (round 190ev)
  699. workspace.onTitleWheel = [this] (Panel panel, const juce::MouseEvent& ev, const juce::MouseWheelDetails& wheel) {
  700. if (panel == Panel::channelRack && ev.mods.isShiftDown())
  701. selectPattern (stepPattern (engine.getSong(), (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1));
  702. };
  703. workspace.onTitleRightClick = [this] (Panel panel, const juce::MouseEvent&) {
  704. if (panel == Panel::channelRack)
  705. showPatternMenu();
  706. };
  707. workspace.onDefaultLayout = [this] { fitChannelRack (true); };
  708. workspace.setPersistent (persistent);
  709. playlist.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  710. playlist.onOpenPianoRoll = [this] {
  711. // edit a channel that plays in this pattern
  712. const auto& song = engine.getSong();
  713. const auto& notes = song.activePattern().notes;
  714. const auto channel = engine.getSelectedChannel();
  715. if (! notes.empty() && std::none_of (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }))
  716. engine.setSelectedChannel (notes.front().channel);
  717. openPianoRoll();
  718. };
  719. picker.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  720. picker.onPatternMenu = [this] { makePatternMenu (picker.pickedPatterns()).showMenuAsync (juce::PopupMenu::Options().withMousePosition()); };
  721. picker.onNewPattern = [this] { newPatternButton.onClick(); };
  722. playlist.onRenamePattern = [this] (int p) { showRenamePattern (p); };
  723. playlist.onGeneratorAdded = [this] (int channel, InstrumentKind kind) { rack.openGeneratorWindow (channel, kind); }; // round 190dx
  724. playlist.onViewOptionChanged = [this] { saveUiSettings(); };
  725. playlist.onOpenInSampler = [this] (int channel) {
  726. // the audio clip's file in a new Sampler channel (to play it from notes), its settings open
  727. const auto& song = engine.getSong();
  728. if (channel < 0 || channel >= (int) song.channels.size())
  729. return;
  730. ChannelDef c;
  731. c.name = song.channels[(std::size_t) channel].name;
  732. c.instrument = InstrumentKind::sampler;
  733. c.samplePath = song.channels[(std::size_t) channel].samplePath;
  734. c.colour = song.channels[(std::size_t) channel].colour;
  735. const auto added = rack.addChannel (c, false);
  736. showPanel (Panel::channelRack);
  737. rack.toggleEditor (added, false);
  738. };
  739. ui::setHint (pianoRoll, tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  740. ui::setHint (playlist, tr ("Playlist: [LMB] paint the current pattern [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  741. // recent files (stored in %APPDATA%\LYNX)
  742. recent.setMaxNumberOfItems (50); // (FL keeps up to 50: File › Recent projects › More; round 190ih)
  743. recent.restoreFromString (PluginHost::settingsFolder().getChildFile ("recentes.txt").loadFileAsString());
  744. addAndMakeVisible (menuBar);
  745. for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &audioEditorButton, &playButton, &stopButton,
  746. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  747. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton, &tempoDisplay, &patternBox, &newPatternButton, &patternMenuButton, &pluginPickerButton, &timeDisplay,
  748. &songPosition, &masterVolume, &masterPitch, &perfMeter, &chordPanel, &keyPanel, &output, &hintBar, &tweakReadout, &workspace, &midiLight,
  749. &multilinkButton, &linkToggle })
  750. {
  751. addAndMakeVisible (c);
  752. c->setMouseClickGrabsKeyboardFocus (false); // the PC keyboard stays with the main window
  753. }
  754. // the dancers of the project's dance channels (FL's Fruity Dance) over the workspace (round 165e)
  755. danceStage = std::make_unique<DanceStage> (engine);
  756. danceStage->setMouseClickGrabsKeyboardFocus (false);
  757. addAndMakeVisible (*danceStage);
  758. for (auto& b : panelButtons)
  759. {
  760. addAndMakeVisible (b);
  761. b.setMouseClickGrabsKeyboardFocus (false);
  762. b.setWantsKeyboardFocus (false);
  763. }
  764. for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &audioEditorButton, &playButton, &stopButton,
  765. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  766. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton, &newPatternButton, &patternMenuButton, &pluginPickerButton })
  767. b->setWantsKeyboardFocus (false);
  768. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &audioEditorButton, &recordMenuButton, &newPatternButton, &patternMenuButton,
  769. &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton })
  770. b->setFlat (true);
  771. // a light header: every toolbar button is flat; "on" is a faint wash, in the accent for the states that
  772. // matter while working (playing, recording, metronome, recording options)
  773. {
  774. using namespace theme;
  775. const auto onWash = colour::accent.withAlpha (0.24f), onIcon = colour::accentHover; // (round 170e3: a clearer "on")
  776. for (auto* b : { &playButton, &stopButton, &recordButton, &patternModeButton, &songModeButton })
  777. b->setFlat (true);
  778. playButton.setOnColour (onWash);
  779. playButton.setIconColourWhenOn (onIcon);
  780. recordButton.setOnColour (colour::record.withAlpha (0.2f));
  781. recordButton.setIconColourWhenOn (colour::record);
  782. saveButton.setOnColour (onWash); // (round 190ih: the save reminder's blink)
  783. saveButton.setIconColourWhenOn (onIcon);
  784. // round 190jo (FM-2): on FL's tiles the switches preview their "on" look under the mouse (FL 2024+)
  785. for (auto* b : { &playButton, &recordButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton,
  786. &stepEditButton, &punchButton, &multilinkButton, &snapToggleButton })
  787. b->setHoverShowsOn (true);
  788. for (auto* b : { &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton, &stepEditButton, &punchButton,
  789. &patternModeButton, &songModeButton, &multilinkButton })
  790. {
  791. b->setOnColour (onWash);
  792. b->setIconColourWhenOn (onIcon);
  793. }
  794. for (auto& b : panelButtons)
  795. {
  796. b.setOnColour (colour::textPrimary.withAlpha (0.08f));
  797. b.setIconColourWhenOn (colour::textPrimary);
  798. }
  799. // round 190je (one state rule): the transport and the save reminder light up when they act, they are not
  800. // switches whose "on" look a hover should preview (the others with "on" colours are)
  801. for (auto* b : { &playButton, &recordButton, &saveButton })
  802. b->setToggleLook (false);
  803. }
  804. quickTips = std::make_unique<ui::QuickTipWindow>();
  805. ui::installSliderContract();
  806. // FL's Last tweaked and automation recording (REA round 143): every automatable control reports its moves
  807. ui::onTweak = [this] (const AutomationTarget& t) {
  808. engine.noteTweaked (t);
  809. engine.controlTweakedForUndo(); // (round 190mv, DF-134: FL's "Undo knob tweaks")
  810. };
  811. // Options › Theme › Startup sound: its Play button (issue #12)
  812. themeui::previewStartupSound = [this] (const juce::String& path) {
  813. std::shared_ptr<const SampleData> sound;
  814. if (path.isNotEmpty() && juce::File (path).existsAsFile())
  815. sound = engine.getSampleLibrary().load (path);
  816. engine.previewSample (sound != nullptr ? sound : makeStartupSample());
  817. };
  818. // the toolbar's last-tweaked read-out opens the parameter's own menu (FL's Tools › Last tweaked; round 162d)
  819. tweakReadout.onClick = [this] {
  820. makeLastTweakedMenu (0).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&tweakReadout));
  821. };
  822. // FL's "Edit events in piano roll" (REA round 146): the channel's own parameter selects its channel
  823. onEditEventsInPianoRoll = [this] (const AutomationTarget& t) {
  824. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  825. || t.kind == AutomationTargetKind::channelParam || t.kind == AutomationTargetKind::channelAdjust;
  826. if (onChannel && t.index >= 0 && t.index < (int) engine.getSong().channels.size())
  827. engine.setSelectedChannel (t.index);
  828. openPianoRoll();
  829. pianoRoll.showEventLane (t);
  830. };
  831. PluginWindows::onGesture = [this] (const juce::AudioPluginInstance& plugin, int param, bool starting) {
  832. if (const auto t = engine.targetOfPlugin (plugin, param))
  833. {
  834. if (starting)
  835. engine.noteTweaked (*t, true);
  836. else
  837. engine.tweakReleased (*t);
  838. }
  839. };
  840. engine.nameAutomation = [this] (const AutomationTarget& t) { return describeAutomationTarget (engine, t).toStdString(); };
  841. externaldrag::install(); // issue #174: drags onto a hosted plugin's own editor become the system's file drag
  842. ui::installTypeAhead(); // issue #182: type-to-jump in menus, dropdowns and lists (JUCE fix 37)
  843. #if JUCE_PLUGINHOST_VST3
  844. // round 177b: a right-click on a VST3 plugin's knob (when the plugin asks the host for the parameter's menu) offers
  845. // LYNX's parameter items first: Create automation clip, Edit events, Link to MIDI / internal controller...
  846. vst3MenuEngine() = &engine;
  847. juce::lynxVst3ParamMenuHook = [] (juce::AudioPluginInstance& plugin, int param, juce::PopupMenu& menu) {
  848. if (auto* e = vst3MenuEngine())
  849. if (const auto t = e->targetOfPlugin (plugin, param))
  850. {
  851. menu.addSectionHeader ("LYNX SHARE - " + describeAutomationTarget (*e, *t));
  852. addAutomationItem (menu, *e, *t, true);
  853. }
  854. };
  855. #endif
  856. addAndMakeVisible (gridBox); // global grid (editors)
  857. snapToggleButton.setFlat (true);
  858. snapToggleButton.setOnColour (juce::Colours::transparentBlack);
  859. snapToggleButton.setIconColourWhenOn (theme::colour::accent);
  860. snapToggleButton.setWantsKeyboardFocus (false);
  861. snapToggleButton.setMouseClickGrabsKeyboardFocus (false);
  862. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  863. snapToggleButton.onClick = [this] {
  864. EditorGlobals::get().toggleGrid();
  865. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  866. };
  867. addAndMakeVisible (snapToggleButton);
  868. engine.addChangeListener (this);
  869. // MIDI controller profiles (round 190aw): LYNX as the controllers see it
  870. controllerBridge = std::make_unique<ControllerBridge> (engine, ControllerBridge::Window {
  871. [this] (const std::string& action) { return runAction (action); },
  872. [this] { return mixer.getSelectedTrack(); },
  873. [this] (int track) { mixer.selectTrack (track); } });
  874. engine.setControllerSurface (controllerBridge.get());
  875. // "Omni" links of mixer-slot controls follow the selected mixer track (round 190bt)
  876. engine.selectedMixerTrackForLinks = [this] { return mixer.getSelectedTrack(); };
  877. // round 190ef: the MIDI mappings of slots, scenes and transport switches act here; the transport is mappable
  878. engine.onRemoteFire = [this] (const remotemap::Fire& f) { fireRemote (f); };
  879. mapmode::tag (playButton, remotemap::Target::of (RemoteAction::play));
  880. mapmode::tag (stopButton, remotemap::Target::of (RemoteAction::stop));
  881. mapmode::tag (recordButton, remotemap::Target::of (RemoteAction::record));
  882. mapmode::tag (metronomeButton, remotemap::Target::of (RemoteAction::metronome));
  883. mapmode::tag (tempoDisplay, remotemap::Target::parameter ({ AutomationTargetKind::tempo, 0, 0, 0 }));
  884. setTypingPiano (typingPiano);
  885. setKeyboardSettingsListener ([this] { saveUiSettings(); }); // round 190ds: the keyboards' modes are UI settings
  886. setTypingKeyLetters ([this] (int key) -> std::string {
  887. // the letter of the typing key that plays `key` (FL's layout; the first key of the layout that does), Keys mode
  888. if (! typingPiano)
  889. return {};
  890. for (const char letter : std::string ("ZSXDCVGBHNJMQ2W3ER5T6Y7UI9O0P,L.;/")) // (the Q row before its duplicates , . /)
  891. if (const auto notes = keys::typingPianoKey (letter, typingOctave, typingRoot, typingLayout).notes; ! notes.empty() && notes.front() == key)
  892. return std::string (1, letter);
  893. return {};
  894. });
  895. refreshRecordOptionButtons();
  896. refreshToolbar();
  897. refreshPanelButtons();
  898. setToolbarLayout (toolbarLayout, false); // icon sizes and row height (loaded with the UI options)
  899. if (persistent && toolbarLayout.uiScale != 100)
  900. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  901. addChildComponent (chordNearHint);
  902. chordPanel.onMenu = [this] { showChordPanelMenu(); };
  903. keyPanel.onClick = [this] { showKeyMenu(); };
  904. linkToggle.setComponentID ("toolbar.link");
  905. linkToggle.onConfigure = [this] { openSettings ((int) SettingsPage::link); };
  906. keyPanel.setComponentID ("toolbar.key"); // (round 190dv: the first-song tour's ring)
  907. refreshKeyPanel();
  908. PianoRollComponent::onSelectedKeys = [this] (const std::vector<int>& keys) {
  909. if (! chordPanel.isVisible())
  910. return;
  911. refreshChordOptions();
  912. chordReadout.selection (keys, juce::Time::getMillisecondCounter());
  913. auto text = juce::String::fromUTF8 (chordReadout.text().c_str());
  914. chordPanel.setText (chordReadout.lastWasNovelty() ? tr (text) : text);
  915. };
  916. setControlHints();
  917. fittedChannelCount = (int) engine.getSong().channels.size();
  918. hintBar.setHint ({ idleHint(), {}, false, false });
  919. setWantsKeyboardFocus (true);
  920. installDialogTextFocus(); // dialogs open with their text field focused (round 165q)
  921. // issue #218 (round 190ng): the toolbar's drop-downs (Pattern, snap) never keep the PC keyboard; any drop-down or button
  922. // of this window or a panel window that gets it hands it back (ui/KeyFocus.h)
  923. // (LYNX_FIX218=0: as before, for the before / after check of --focus218shot190ng)
  924. if (juce::SystemStats::getEnvironmentVariable ("LYNX_FIX218", "1") != "0")
  925. {
  926. for (auto* box : std::initializer_list<juce::Component*> { &patternBox, &gridBox })
  927. {
  928. box->setWantsKeyboardFocus (false);
  929. box->setMouseClickGrabsKeyboardFocus (false);
  930. }
  931. ui::keyfocus::install (*this);
  932. }
  933. if (startupMark != nullptr) startupMark ("main window: toolbar, menus, controllers");
  934. setSize (1180, 642);
  935. startTimerHz (30);
  936. uiTraceMonitor.start ([this, last = std::make_shared<RtStats::Snapshot>()] {
  937. // the audio side of the second (the watchdog thread: atomics only)
  938. const auto rt = engine.getRtStats().snapshot();
  939. const auto calls = rt.callbacks - last->callbacks;
  940. juce::String text;
  941. text << "audio: callbacks " << juce::String ((juce::int64) calls) << ", over deadline " << juce::String ((juce::int64) (rt.overBudget - last->overBudget))
  942. << ", late " << juce::String ((juce::int64) (rt.lateCalls - last->lateCalls)) << ", max load since start " << juce::String (rt.maxLoad * 100.0, 0)
  943. << "%, cpu " << juce::String (engine.getDeviceManager().getCpuUsage() * 100.0, 1) << "%";
  944. *last = rt;
  945. return text;
  946. });
  947. // new or updated plugins since the last run: an incremental scan in the background (unchanged files are
  948. // skipped), a few seconds after start so it doesn't compete with loading; the first run asks in the wizard
  949. if (autoscan::atStartup (persistent, setupWizardDone(), backgroundScanAtStart()) && platform::testMode())
  950. platform::testModeLog ("background plugin scan at start");
  951. else if (autoscan::atStartup (persistent, setupWizardDone(), backgroundScanAtStart()))
  952. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  953. if (safe != nullptr)
  954. safe->engine.getPluginHost().startBackgroundScan();
  955. });
  956. // round 168t (the YouTube review, 168d #9: "How do we get back to the playlist? Where is the playlist?"): the first
  957. // three starts name the window buttons and their keys in the hint bar for a while
  958. if (persistent)
  959. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  960. if (safe != nullptr)
  961. safe->showWindowsTip();
  962. });
  963. // Online Sessions P2 (round 169b): live sessions
  964. live = std::make_unique<LiveSessionManager> (engine);
  965. liveui::attach (*live);
  966. liveui::setRemoteSession (live.get(), &engine); // (P5-A1: the shared plugins in the menus, the guest's editor)
  967. live->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  968. if (safe != nullptr)
  969. {
  970. safe->repaint (safe->titleArea);
  971. safe->menuItemsChanged();
  972. safe->updateTitle(); // (the session's state is in the window title too: narrow layouts hide the badge)
  973. }
  974. };
  975. live->onJoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  976. if (safe == nullptr)
  977. return;
  978. const auto* host = song.session.find (session::hostTag);
  979. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  980. safe->startNewProject (std::move (song), {});
  981. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  982. safe->updateTitle();
  983. };
  984. // round 169j: the host's LYNX SHARE restarted during a session: its journal's song becomes the open project again
  985. live->onResumed = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  986. if (safe == nullptr)
  987. return;
  988. const auto journal = LiveSessionManager::readJournal (LiveSessionManager::defaultJournal());
  989. safe->startNewProject (std::move (song), {});
  990. if (journal && journal->projectFile.existsAsFile())
  991. {
  992. safe->currentFile = journal->projectFile;
  993. safe->projectName = journal->projectFile.getFileNameWithoutExtension();
  994. }
  995. safe->updateTitle();
  996. };
  997. // round 190ah: a guest's LYNX SHARE restarted during a session: the project it had is open again
  998. live->onRejoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  999. if (safe == nullptr)
  1000. return;
  1001. const auto* host = song.session.find (session::hostTag);
  1002. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  1003. safe->startNewProject (std::move (song), {});
  1004. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  1005. safe->updateTitle();
  1006. };
  1007. engine.onSessionUndoSkipped = [] (const juce::StringArray& skipped) {
  1008. ui::postHint ({ tr ("Undo left alone what someone else changed since: {0}", { skipped.joinIntoString (", ") }), {} }, 4000);
  1009. };
  1010. // round 190gh (B8): a MIDI device plugged in or out while LYNX SHARE runs (FL: "New MIDI device detected")
  1011. engine.onMidiDevicesChanged = [] (const juce::StringArray& added, const juce::StringArray& removed) {
  1012. juce::StringArray lines;
  1013. if (! added.isEmpty())
  1014. lines.add (tr ("MIDI device connected: {0}", { added.joinIntoString (", ") }));
  1015. if (! removed.isEmpty())
  1016. lines.add (tr ("MIDI device disconnected: {0}", { removed.joinIntoString (", ") }));
  1017. ui::postNotice ({ lines.joinIntoString (" · "), {} }, 5000);
  1018. };
  1019. if (startStyle.style != layoutstyle::Style::pattern)
  1020. setLayoutStyle (startStyle.style, false); // (the saved workspace layout is already this style's)
  1021. updateGamepad(); // (round 184a, S16: only when the option is on)
  1022. juce::Timer::callAfterDelay (1500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  1023. if (safe != nullptr)
  1024. safe->startLiveFromCommandLine();
  1025. });
  1026. // the keys a secondary window (tool, plugin, channel window) leaves unused run the global shortcuts, as in FL
  1027. // FL's Auto select linked modules [DECOMP FUN_00f5c340] (round 187a): a focused channel / plugin window selects its
  1028. // channel and that channel's mixer track; a mixer effect's window selects its track
  1029. setLinkedWindowFocusHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (int channel, int insert) {
  1030. if (safe == nullptr || ! ChannelRackComponent::autoSelectLinked)
  1031. return;
  1032. const auto& song = safe->engine.getSong();
  1033. if (channel >= 0 && channel < (int) song.channels.size())
  1034. {
  1035. if (safe->engine.getSelectedChannel() != channel || safe->engine.getSelectedChannels().size() != 1)
  1036. safe->engine.setSelectedChannel (channel);
  1037. insert = song.channels[(std::size_t) channel].mixerTrack;
  1038. }
  1039. if (insert >= 0 && insert < (int) song.mixer.size())
  1040. safe->mixer.selectTrack (insert);
  1041. });
  1042. simpleClickKeys.up = [this] (juce::Component* clicked) { simpleClickEnded (clicked); };
  1043. setSecondaryWindowKeyHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  1044. return safe != nullptr && safe->keyFromSecondaryWindow (key);
  1045. });
  1046. // keys over a focused plugin (rounds 181c/187a, issue #96): what it passes back plays, and with its "Typing keyboard priority" off LYNX goes first
  1047. setPluginViewPlainKeyHandler ([] (juce::Component& window) { return PluginWindows::letsHostProcessKeys (window); },
  1048. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  1049. return safe != nullptr && safe->keyFromPluginView (key, true);
  1050. },
  1051. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  1052. return safe != nullptr && safe->keyFromPluginView (key, false);
  1053. });
  1054. if (startupMark != nullptr) startupMark ("main window: live sessions, the rest of the constructor");
  1055. }
  1056. MainComponent::~MainComponent()
  1057. {
  1058. ui::keyfocus::uninstall (*this); // (round 190ng)
  1059. EffectsPanel::onHotSwapSlot = nullptr; // (round 190ce: it calls this window)
  1060. if (pluginDatabaseWatcher != nullptr) // (round 190mf: nobody watches the folder any more)
  1061. quickpick::setPluginDatabaseWatched (false);
  1062. workflowextras::bind (nullptr); // (round 190iu)
  1063. workflowextras::onChanged = nullptr;
  1064. workflowextras::tempTools().toolKey (temptool::Editor::none, 0, EditTool::pencil, EditTool::pencil, nullptr, nullptr);
  1065. engine.setControllerSurface (nullptr); // (the controllers get their closing messages)
  1066. engine.selectedMixerTrackForLinks = nullptr;
  1067. engine.onRemoteFire = nullptr;
  1068. engine.setMapMode (remotemap::Mode::off);
  1069. closeRemoteControlSettings();
  1070. gamepadInput.reset();
  1071. if (detailView != nullptr) // (round 183a: a docked Piano roll goes home while the workspace still exists)
  1072. detailView->releaseEditor();
  1073. if (simpleWorkflow != nullptr) // (round 190ds: the same for the Simple dock's Editor tab)
  1074. simpleWorkflow->releaseEditor();
  1075. setKeyboardSettingsListener (nullptr);
  1076. setTypingKeyLetters (nullptr);
  1077. juce::Desktop::getInstance().removeGlobalMouseListener (&dockClickWatcher);
  1078. juce::Desktop::getInstance().removeGlobalMouseListener (&simpleClickKeys);
  1079. workspace.onWillShow = nullptr;
  1080. engine.onSessionUndoSkipped = nullptr;
  1081. engine.onMidiDevicesChanged = nullptr;
  1082. PianoRollComponent::onSelectedKeys = nullptr;
  1083. liveui::closeChat();
  1084. liveui::setRemoteSession (nullptr, nullptr);
  1085. live.reset(); // (a session still on ends: the others are told)
  1086. setPluginViewPlainKeyHandler (nullptr, nullptr, nullptr);
  1087. setSecondaryWindowKeyHandler (nullptr);
  1088. setLinkedWindowFocusHandler (nullptr);
  1089. cancelProjectLoad(); // an open in progress uses the engine from its thread
  1090. if (sessionLock != nullptr) // a clean exit: no "LYNX did not close properly" next time
  1091. sessionMarker.deleteFile();
  1092. mixerinput::openAudioSettings = nullptr;
  1093. openMixerInsertHandler() = nullptr;
  1094. channelWrapperItemsHandler() = nullptr;
  1095. locateInBrowserHandler() = nullptr;
  1096. openInNewChannelHandler() = nullptr;
  1097. PatcherWindows::onBrowsePluginDatabase = nullptr;
  1098. EditorGlobals::get().onOptionsChanged = nullptr;
  1099. PianoRollComponent::shortcutText = nullptr;
  1100. PlaylistComponent::shortcutText = nullptr;
  1101. saveUiSettings();
  1102. workspace.saveState();
  1103. // Round 190fc (0.1.27 RC blocker B1): the Simple workflow goes while everything its Host reaches still exists. As a
  1104. // member it was destroyed after `workspace` (declared later, destroyed first), and its destructor leaves the style
  1105. // (SimpleWorkflow::left): Host::setTitleAccessory then reached the destroyed Workspace's panel frames — an access
  1106. // violation in PanelFrame::setAccessory on every close (and the setup wizard's "Restart now") in the Simple layout.
  1107. if (simpleWorkflow != nullptr)
  1108. {
  1109. playlist.onTrackEffects = nullptr;
  1110. playlist.onSimpleTrackSelected = nullptr;
  1111. playlist.onSimpleFilesDropped = nullptr;
  1112. playlist.onSimpleAddTrack = nullptr;
  1113. playlist.onExportTrack = nullptr;
  1114. simpleWorkflow.reset();
  1115. }
  1116. simpleWorkflowAliveAfterTeardown = SimpleWorkflow::alive.load();
  1117. ui::uninstallSliderContract();
  1118. ui::onTweak = nullptr;
  1119. themeui::previewStartupSound = nullptr;
  1120. onEditEventsInPianoRoll = nullptr;
  1121. PluginWindows::onGesture = nullptr;
  1122. #if JUCE_PLUGINHOST_VST3
  1123. juce::lynxVst3ParamMenuHook = nullptr;
  1124. vst3MenuEngine() = nullptr;
  1125. #endif
  1126. removeDialogTextFocus();
  1127. engine.nameAutomation = nullptr;
  1128. PluginWindows::closeAll(); // plugin UIs before the engine
  1129. PluginWindows::setDockWorkspace (nullptr); // (issue #116: the docked ones were in the workspace)
  1130. setEditorDock (nullptr);
  1131. ParametricEqWindows::closeAll();
  1132. closeAutomationEditors();
  1133. closeChannelSettings();
  1134. closeAllToolWindows(); // note tools, history, quick-add (they edit the song)
  1135. engine.removeChangeListener (this);
  1136. stopTimer();
  1137. }
  1138. void MainComponent::paint (juce::Graphics& g)
  1139. {
  1140. const uitrace::Scope trace ("MainComponent paint", true, g.getClipBounds());
  1141. if (! IconButton::paintingTileAtlas()) // (round 190mh: the FL tiles' atlas paints its backdrop with this clip edge)
  1142. lastPaintClip = g.getClipBounds();
  1143. using namespace theme;
  1144. g.fillAll (colour::bg1);
  1145. if (toolbarLook != toolbarlayout::Look::fl) // round 190iv: the Simple and Clip-launch toolbars
  1146. {
  1147. paintLookToolbar (g);
  1148. return;
  1149. }
  1150. // the toolbar: one band, its panels separated by hairlines
  1151. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  1152. g.setColour (colour::bg3);
  1153. g.fillRect (bar);
  1154. g.setColour (colour::border);
  1155. g.fillRect (bar.withHeight (1).withY (bar.getBottom() - 1));
  1156. // round 170e3: each panel sits in its own quiet well (transport, master, recording, snap and pattern, windows,
  1157. // file, meters), so the groups read at a glance; with "Separators" off, only hairlines between them
  1158. if (toolbarLayout.separators) // (the toolbar menu's "Separators")
  1159. {
  1160. for (const auto& r : panelBounds)
  1161. if (! r.isEmpty())
  1162. {
  1163. const auto well = r.toFloat().reduced (1.0f, 2.0f);
  1164. g.setColour (colour::bg1.withAlpha (0.55f));
  1165. g.fillRoundedRectangle (well, radius::lg);
  1166. g.setColour (colour::border);
  1167. g.drawRoundedRectangle (well.reduced (0.5f), radius::lg, 1.0f);
  1168. }
  1169. }
  1170. else
  1171. {
  1172. g.setColour (colour::border.brighter (0.08f));
  1173. for (auto x : dividers)
  1174. g.fillRect (x, bar.getY() + 12, 1, bar.getHeight() - 24);
  1175. }
  1176. // Pattern / Song: one switch of two halves (round 170e3), the playing mode lit
  1177. if (! modeArea.isEmpty())
  1178. {
  1179. g.setColour (colour::bg2);
  1180. g.fillRoundedRectangle (modeArea.toFloat(), radius::lg);
  1181. g.setColour (colour::borderStrong);
  1182. g.drawRoundedRectangle (modeArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  1183. }
  1184. // play, stop and record share one quiet well
  1185. if (! transportArea.isEmpty())
  1186. {
  1187. g.setColour (colour::bg2);
  1188. g.fillRoundedRectangle (transportArea.toFloat(), radius::lg);
  1189. g.setColour (colour::border);
  1190. g.drawRoundedRectangle (transportArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  1191. }
  1192. // the hint bar sits in an inset well under the menu
  1193. if (! hintBar.getBounds().isEmpty())
  1194. {
  1195. g.setColour (colour::bg1);
  1196. g.fillRoundedRectangle (hintBar.getBounds().toFloat(), radius::md);
  1197. }
  1198. // the project name, beside the menus (FL's title/hint panel: the title above the hint bar)
  1199. if (! titleArea.isEmpty())
  1200. {
  1201. // the people of a live session first (round 169b), the project's name after them
  1202. const auto people = live != nullptr ? liveui::paintPresence (g, titleArea, *live) : 0;
  1203. const auto name = projectName.isNotEmpty() ? projectName : tr ("Untitled");
  1204. g.setFont (font (type::small, true));
  1205. g.setColour (colour::textSecondary);
  1206. if (const auto rest = titleArea.withTrimmedLeft (people > 0 ? people + 10 : 0); rest.getWidth() >= 50)
  1207. g.drawFittedText ((engine.isModified() ? juce::String ("* ") : juce::String()) + name
  1208. + (engine.pluginsOff() ? " " + tr ("(third-party plugins off)") : juce::String()), // round 190ap
  1209. rest, juce::Justification::centredRight, 1, 0.8f);
  1210. }
  1211. // captions that name the snap and pattern selectors, after their icons (the magnet is a button)
  1212. g.setFont (font (type::caption - 1.0f, true));
  1213. g.setColour (colour::textDisabled);
  1214. if (! snapLabelArea.isEmpty())
  1215. if (snapLabelArea.getWidth() > rowHeight + 20) // (the narrowest toolbar keeps only the magnet)
  1216. g.drawText (tr ("SNAP"), snapLabelArea.withTrimmedLeft (rowHeight + 1), juce::Justification::centredLeft, true);
  1217. if (! patternLabelArea.isEmpty())
  1218. {
  1219. const auto iconBox = patternLabelArea.withWidth (rowHeight).toFloat();
  1220. icons::draw (g, Icon::pattern, iconBox.withSizeKeepingCentre (14.0f, 14.0f), colour::textDisabled);
  1221. if (patternLabelArea.getWidth() > rowHeight + 20)
  1222. g.drawText (tr ("PATTERN"), patternLabelArea.withTrimmedLeft (rowHeight + 1), juce::Justification::centredLeft, true);
  1223. }
  1224. }
  1225. void MainComponent::resized()
  1226. {
  1227. using toolbarlayout::Group;
  1228. if (const auto size = toolbarlayout::effectiveIconSize (toolbarLayout.iconSize, getWidth()); size != appliedIconSize)
  1229. applyIconSizing (size);
  1230. dividers.clear();
  1231. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  1232. auto toolbar = bar.reduced (8, toolbarLayout.visible ? 5 : 3);
  1233. const auto row1 = toolbar.getY(), row2 = toolbar.getY() + rowHeight + 2, h = rowHeight;
  1234. auto big = h + 14; // transport buttons: big, centred on both rows (round 170e3)
  1235. auto bigWidth = h + 14;
  1236. int gap = 17; // a divider and the space around it (13 when compact)
  1237. const auto grow = h - toolbarlayout::rowHeight (toolbarlayout::IconSize::medium); // wider panels for bigger rows
  1238. // panel widths
  1239. auto& lf = getLookAndFeel();
  1240. auto measureMenu = [&] {
  1241. int w = 0;
  1242. for (const auto& name : getMenuBarNames())
  1243. w += lf.getMenuBarItemWidth (menuBar, 0, name);
  1244. return w;
  1245. };
  1246. menuBar.getProperties().set ("lynxTightMenuBar", false);
  1247. int menuWidth = measureMenu();
  1248. if (menuWidth > 390) // translated menu titles (German, Russian...): English stays as it was
  1249. {
  1250. menuBar.getProperties().set ("lynxTightMenuBar", true);
  1251. menuWidth = measureMenu();
  1252. }
  1253. // round 190iv: the Simple and Clip-launch layouts lay their own toolbar out (core/ToolbarLayout.h Look); FL's below
  1254. if (toolbarLook != toolbarlayout::Look::fl)
  1255. {
  1256. if (toolbarLook == toolbarlayout::Look::simple)
  1257. layoutSimpleToolbar (bar, menuWidth);
  1258. else
  1259. layoutLiveControlBar (bar, menuWidth);
  1260. layoutUnderToolbar();
  1261. return;
  1262. }
  1263. const auto modeWidth = juce::jmax (patternModeButton.getIdealWidth (h - 2), songModeButton.getIdealWidth (h - 2));
  1264. int tempoWidth = 96 + grow, timeWidth = 140 + grow;
  1265. const int gridWidth = 148;
  1266. // the snap and pattern captions: an icon (the magnet button / the pattern icon) and the longer of the two names
  1267. const juce::Font captionFont (theme::font (theme::type::caption - 1.0f, true));
  1268. int captionWidth = h + 3 + juce::jlimit (30, 80, juce::roundToInt (juce::jmax (juce::GlyphArrangement::getStringWidth (captionFont, tr ("SNAP")),
  1269. juce::GlyphArrangement::getStringWidth (captionFont, tr ("PATTERN"))))) + 6;
  1270. std::array<int, toolbarlayout::groupCount> widths {};
  1271. const int tapWidth = juce::roundToInt (h * 0.8f); // the tempo tapper, right of the tempo (round 170e3)
  1272. widths[(std::size_t) Group::transport] = modeWidth + 8 + 3 * (bigWidth + 4) + 4 + tempoWidth + 2 + tapWidth + 4 + timeWidth;
  1273. widths[(std::size_t) Group::master] = 2 * (h + 26) + 4; // two big knobs side by side (round 170e3)
  1274. widths[(std::size_t) Group::record] = 5 * h + 8; // five per row (round 170e3)
  1275. widths[(std::size_t) Group::snap] = captionWidth + gridWidth;
  1276. widths[(std::size_t) Group::windows] = 3 * h + 4;
  1277. widths[(std::size_t) Group::file] = 4 * h + 6; // (round 190mv: + FL's audio editor button)
  1278. widths[(std::size_t) Group::meters] = 118;
  1279. widths[(std::size_t) Group::output] = 116 + grow * 2;
  1280. widths[(std::size_t) Group::chord] = 96; // (FL's panel: 96 px)
  1281. widths[(std::size_t) Group::multilink] = h; // one button (FL's MultiLinkBtn)
  1282. widths[(std::size_t) Group::key] = 112; // "Key" over "C# harmonic minor" (round 184a S11; the name shrinks to fit)
  1283. widths[(std::size_t) Group::link] = toolbar::LinkToggle::idealWidth (h); // "Link" / "2 Links" and its arrow (round 190gl)
  1284. const auto room = toolbar.getWidth();
  1285. // room for most hints on two lines; on a very wide window the hint bar takes more (round 170e3)
  1286. auto minHint = juce::jmax (menuWidth + 8, 320);
  1287. const auto maxHint = room >= 3000 ? 1000 : 620;
  1288. auto visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1289. // round 190nk (0.1.30 release QA): the 0.1.30 toolbar grew (FL's hint and Last tweaked column, bigger transport
  1290. // tiles, round 190mv's audio-editor button as a fourth File column), so at 1920 px the default toolbar dropped the
  1291. // output scope and the Chord panel that 0.1.29 and FL show there (on Windows the meters were clipped too). Before
  1292. // a whole panel goes, the audio-editor column goes (an audio editor still opens from the Master's effect slots), then
  1293. // round 181b's tighter displays and gaps are used; whichever keeps the most panels wins, the wider form on a tie.
  1294. fileWide = true;
  1295. const auto shownCount = [] (const std::array<bool, toolbarlayout::groupCount>& v) { return (int) std::count (v.begin(), v.end(), true); };
  1296. {
  1297. auto narrowFile = widths;
  1298. narrowFile[(std::size_t) Group::file] = 3 * h + 4;
  1299. const auto threeColumns = toolbarlayout::fit (toolbarLayout, narrowFile, gap, room, minHint);
  1300. if (shownCount (threeColumns) > shownCount (visible))
  1301. {
  1302. widths = narrowFile;
  1303. visible = threeColumns;
  1304. fileWide = false;
  1305. }
  1306. }
  1307. // round 181b: the Chord detection panel is on the default toolbar, as in FL. At 1920 px it misses by about 90 px:
  1308. // tighter displays and gaps make the room (they get wider again when there is more); all the panels stay.
  1309. // (Round 190nk: also for the output scope and the meters, and with a three-column File panel if that keeps more.)
  1310. const auto dropped = [&] (Group g) { return toolbarLayout.isShown (g) && ! visible[(std::size_t) g]; };
  1311. if (toolbarLayout.visible && visible[(std::size_t) Group::record]
  1312. && (dropped (Group::chord) || dropped (Group::output) || dropped (Group::meters)))
  1313. {
  1314. auto tighter = widths;
  1315. tighter[(std::size_t) Group::transport] -= 12 + 36; // the tempo and the song position, as narrow as the compact ones
  1316. tighter[(std::size_t) Group::snap] -= 16;
  1317. tighter[(std::size_t) Group::chord] = 88;
  1318. auto fits = toolbarlayout::fit (toolbarLayout, tighter, 13, room, minHint);
  1319. auto tighterFileWide = fileWide;
  1320. if (fileWide)
  1321. {
  1322. auto tighter3 = tighter;
  1323. tighter3[(std::size_t) Group::file] = 3 * h + 4;
  1324. if (const auto fits3 = toolbarlayout::fit (toolbarLayout, tighter3, 13, room, minHint); shownCount (fits3) > shownCount (fits))
  1325. {
  1326. tighter = tighter3;
  1327. fits = fits3;
  1328. tighterFileWide = false;
  1329. }
  1330. }
  1331. if (shownCount (fits) > shownCount (visible))
  1332. {
  1333. widths = tighter;
  1334. tempoWidth -= 12;
  1335. timeWidth -= 36;
  1336. gap = 13;
  1337. visible = fits;
  1338. fileWide = tighterFileWide;
  1339. }
  1340. }
  1341. // round 170e3: rather than dropping the recording switches on a narrow window (1280-1440 px), the panels get
  1342. // tighter: four switches per row (the typing piano and the MIDI light go; Ctrl+T and the View menu keep the piano),
  1343. // a narrower snap box and displays
  1344. compactRecord = false;
  1345. narrowSnap = false;
  1346. if (toolbarLayout.visible && toolbarLayout.isShown (Group::record) && ! visible[(std::size_t) Group::record])
  1347. {
  1348. compactRecord = true;
  1349. const auto before = 3 * (bigWidth + 4) + tempoWidth + timeWidth;
  1350. big = h + 6;
  1351. bigWidth = h + 4;
  1352. tempoWidth = 84 + grow;
  1353. timeWidth = 104 + grow;
  1354. widths[(std::size_t) Group::transport] -= before - (3 * (bigWidth + 4) + tempoWidth + timeWidth);
  1355. widths[(std::size_t) Group::master] = 92; // the knobs over each other, as before
  1356. widths[(std::size_t) Group::record] = 4 * h + 6;
  1357. widths[(std::size_t) Group::snap] -= 16;
  1358. gap = 13;
  1359. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1360. // round 170e5: still too narrow (1280 px): the snap and pattern captions keep only their icons, the hint
  1361. // column only the menu's width, tighter displays and gaps; the recording switches stay
  1362. if (! visible[(std::size_t) Group::record])
  1363. {
  1364. const auto icons = h + 4;
  1365. widths[(std::size_t) Group::snap] -= captionWidth - icons;
  1366. captionWidth = icons;
  1367. tempoWidth -= 6;
  1368. timeWidth -= 8;
  1369. widths[(std::size_t) Group::transport] -= 14;
  1370. minHint = menuWidth + 8;
  1371. gap = 11;
  1372. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1373. }
  1374. // and still (1280 px, measured: the switches missed it by a few px): a narrower snap box, tight gaps; then
  1375. // the window buttons go before the recording switches (F5-F9 and the View menu open the same windows)
  1376. if (! visible[(std::size_t) Group::record])
  1377. {
  1378. widths[(std::size_t) Group::snap] -= 24;
  1379. narrowSnap = true;
  1380. gap = 8;
  1381. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1382. }
  1383. if (! visible[(std::size_t) Group::record])
  1384. {
  1385. auto narrow = toolbarLayout;
  1386. for (auto& e : narrow.entries)
  1387. if (e.group == Group::windows)
  1388. e.shown = false;
  1389. visible = toolbarlayout::fit (narrow, widths, gap, room, minHint);
  1390. }
  1391. }
  1392. if (! toolbarLayout.visible) // Ctrl+F11: only the menu and the hint bar, on one row
  1393. visible.fill (false);
  1394. panelBounds = {};
  1395. int used = 0;
  1396. for (int i = 0; i < toolbarlayout::groupCount; ++i)
  1397. used += visible[(std::size_t) i] ? widths[(std::size_t) i] + gap : 0;
  1398. auto hintWidth = juce::jlimit (juce::jmin (minHint, juce::jmax (160, room - used)), maxHint, room - used);
  1399. // round 170e3: the spare room goes to useful things first (a wider output monitor, snap and pattern boxes, song
  1400. // position and hint bar), then a little air between the panels, so no dead zone opens anywhere on a wide window
  1401. auto spare = juce::jmax (0, room - used - hintWidth);
  1402. auto grant = [&spare] (int share, int most) {
  1403. const auto g = juce::jmax (0, juce::jmin (most, spare * share / 100));
  1404. spare -= g;
  1405. return g;
  1406. };
  1407. if (visible[(std::size_t) Group::output])
  1408. widths[(std::size_t) Group::output] += grant (40, 900);
  1409. if (visible[(std::size_t) Group::snap])
  1410. widths[(std::size_t) Group::snap] += grant (20, 220);
  1411. if (const auto more = grant (15, 120); more > 0)
  1412. {
  1413. timeWidth += more;
  1414. widths[(std::size_t) Group::transport] += more;
  1415. }
  1416. hintWidth += grant (25, 500);
  1417. const auto shownGroups = (int) std::count (visible.begin(), visible.end(), true);
  1418. // at most twice the normal gap between the panels; what is still left goes to the output monitor and the hint bar
  1419. const auto extra = toolbarlayout::extraGap (spare, shownGroups, gap);
  1420. spare -= extra * shownGroups;
  1421. if (spare > 0)
  1422. {
  1423. const auto toOutput = visible[(std::size_t) Group::output] ? spare / 2 : 0;
  1424. widths[(std::size_t) Group::output] += toOutput;
  1425. hintWidth += spare - toOutput;
  1426. spare = 0;
  1427. }
  1428. auto take = [&toolbar] (int width) { return toolbar.removeFromLeft (juce::jmin (width, toolbar.getWidth())); };
  1429. auto divide = [&] {
  1430. take (gap / 2 + extra / 2);
  1431. dividers.push_back (toolbar.getX());
  1432. take (gap - gap / 2 + extra - extra / 2);
  1433. };
  1434. auto hide = [] (std::initializer_list<juce::Component*> components) {
  1435. for (auto* c : components)
  1436. {
  1437. c->setVisible (false);
  1438. c->setBounds ({});
  1439. }
  1440. };
  1441. auto put = [] (juce::Component& c, juce::Rectangle<int> r) {
  1442. c.setVisible (true);
  1443. c.setBounds (r);
  1444. };
  1445. // a block of icon buttons, three per row on both rows
  1446. auto grid = [&] (juce::Rectangle<int> panel, std::initializer_list<juce::Component*> buttons, int columns = 3) {
  1447. int i = 0;
  1448. for (auto* b : buttons)
  1449. {
  1450. const auto x = panel.getX() + (i % columns) * (h + 2);
  1451. put (*b, juce::Rectangle<int> (x, i < columns ? row1 : row2, h, h));
  1452. ++i;
  1453. }
  1454. };
  1455. // 1. the menu (and the project name beside it) over the hint bar; always first
  1456. if (! toolbarLayout.visible)
  1457. {
  1458. const auto row = toolbar.withHeight (h);
  1459. const auto menu = row.withWidth (juce::jmin (menuWidth + 8, row.getWidth()));
  1460. put (menuBar, menu);
  1461. titleArea = {};
  1462. placeHintBar (row.withTrimmedLeft (menu.getWidth() + 12).withWidth (juce::jmin (900, row.getWidth() - menu.getWidth() - 12)).reduced (0, 1));
  1463. fixedToolbarArea = bar;
  1464. }
  1465. else
  1466. {
  1467. auto column = take (hintWidth);
  1468. const auto menu = column.withY (row1).withHeight (h).removeFromLeft (juce::jmin (menuWidth + 8, column.getWidth()));
  1469. put (menuBar, menu);
  1470. titleArea = column.withY (row1).withHeight (h).withTrimmedLeft (menu.getWidth() + 12).withTrimmedRight (4);
  1471. if (titleArea.getWidth() < 60)
  1472. titleArea = {};
  1473. placeHintBar (column.withY (row2).withHeight (h).reduced (0, 1));
  1474. fixedToolbarArea = juce::Rectangle<int> (column.getX() - 4, 0, column.getWidth() + 8, toolbarHeight);
  1475. }
  1476. snapLabelArea = patternLabelArea = transportArea = modeArea = {};
  1477. for (const auto& entry : toolbarLayout.entries)
  1478. {
  1479. const auto group = entry.group;
  1480. if (! visible[(std::size_t) group])
  1481. {
  1482. switch (group)
  1483. {
  1484. case Group::transport:
  1485. hide ({ &patternModeButton, &songModeButton, &playButton, &stopButton, &recordButton, &tempoDisplay, &tapTempoButton, &timeDisplay, &songPosition });
  1486. break;
  1487. case Group::master: hide ({ &masterVolume, &masterPitch }); break;
  1488. case Group::record: hide ({ &metronomeButton, &typingPianoButton, &recordMenuButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton, &stepEditButton, &punchButton, &midiLight }); break;
  1489. case Group::snap: hide ({ &gridBox, &snapToggleButton, &patternBox, &newPatternButton, &patternMenuButton }); break;
  1490. case Group::windows:
  1491. for (auto& b : panelButtons)
  1492. hide ({ &b });
  1493. hide ({ &pluginPickerButton });
  1494. break;
  1495. case Group::file: hide ({ &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &audioEditorButton }); break;
  1496. case Group::meters: hide ({ &perfMeter }); break;
  1497. case Group::output: hide ({ &output }); break;
  1498. case Group::chord: hide ({ &chordPanel }); break;
  1499. case Group::multilink: hide ({ &multilinkButton }); break;
  1500. case Group::key: hide ({ &keyPanel }); break;
  1501. case Group::link: hide ({ &linkToggle }); break;
  1502. case Group::count_: break;
  1503. }
  1504. continue;
  1505. }
  1506. if (toolbarlayout::rightAligned (group) && spare > 0)
  1507. {
  1508. take (spare);
  1509. spare = 0;
  1510. }
  1511. divide();
  1512. auto panel = take (widths[(std::size_t) group]);
  1513. panelBounds[(std::size_t) group] = juce::Rectangle<int> (panel.getX() - 5, 0, panel.getWidth() + 10, toolbarHeight);
  1514. switch (group)
  1515. {
  1516. case Group::transport: // Pattern/Song switch, play, stop, record, tempo, time display with the song position under it
  1517. {
  1518. auto mode = panel.removeFromLeft (modeWidth);
  1519. modeArea = mode.withY (row1).withHeight (2 * h + 2).expanded (3, 2);
  1520. put (patternModeButton, mode.withY (row1).withHeight (h).reduced (0, 1));
  1521. put (songModeButton, mode.withY (row2).withHeight (h).reduced (0, 1));
  1522. panel.removeFromLeft (8);
  1523. const auto y = panel.getCentreY() - big / 2;
  1524. transportArea = juce::Rectangle<int> (panel.getX(), y, 3 * bigWidth + 2 * 4, big);
  1525. for (auto* b : { &playButton, &stopButton, &recordButton })
  1526. {
  1527. put (*b, juce::Rectangle<int> (panel.getX(), y, bigWidth, big).reduced (0, 3));
  1528. panel.removeFromLeft (bigWidth + 4);
  1529. }
  1530. panel.removeFromLeft (4);
  1531. const auto displays = juce::Rectangle<int> (panel.getX(), row1 + 3, panel.getWidth(), 2 * h - 6);
  1532. const auto displayHeight = displays.getHeight() - 10;
  1533. put (tempoDisplay, displays.withWidth (tempoWidth).withHeight (displayHeight));
  1534. put (tapTempoButton, displays.withTrimmedLeft (tempoWidth + 2).withWidth (tapWidth).withHeight (displayHeight));
  1535. put (timeDisplay, displays.withTrimmedLeft (tempoWidth + 2 + tapWidth + 4).withWidth (timeWidth).withHeight (displayHeight));
  1536. put (songPosition, displays.withTop (displays.getY() + displayHeight + 1).withWidth (tempoWidth + 2 + tapWidth + 4 + timeWidth));
  1537. break;
  1538. }
  1539. case Group::master: // master volume beside master pitch, each a big knob with its name and value under it
  1540. {
  1541. if (compactRecord)
  1542. {
  1543. put (masterVolume, panel.withY (row1).withHeight (h).reduced (0, 1));
  1544. put (masterPitch, panel.withY (row2).withHeight (h).reduced (0, 1));
  1545. break;
  1546. }
  1547. const auto both = panel.withY (row1).withHeight (2 * h + 2);
  1548. put (masterVolume, both.withWidth (both.getWidth() / 2 - 2));
  1549. put (masterPitch, both.withTrimmedLeft (both.getWidth() / 2 + 2));
  1550. break;
  1551. }
  1552. case Group::record: // the recording switches (round 170e3, as FL's recording panel): metronome, wait for input, count-in,
  1553. // blend and the typing piano over loop record, step edit, punch, the recording options menu and the MIDI light
  1554. if (compactRecord)
  1555. {
  1556. hide ({ &typingPianoButton, &midiLight });
  1557. grid (panel, { &metronomeButton, &waitInputButton, &countInButton, &blendButton,
  1558. &loopRecordButton, &stepEditButton, &punchButton, &recordMenuButton }, 4);
  1559. }
  1560. else
  1561. grid (panel, { &metronomeButton, &waitInputButton, &countInButton, &blendButton, &typingPianoButton,
  1562. &loopRecordButton, &stepEditButton, &punchButton, &recordMenuButton, &midiLight }, 5);
  1563. break;
  1564. case Group::snap: // global snap over the pattern selector, each with its name
  1565. {
  1566. auto first = juce::Rectangle<int> (panel.getX(), row1, panel.getWidth(), h);
  1567. snapLabelArea = first.removeFromLeft (captionWidth);
  1568. put (snapToggleButton, snapLabelArea.withWidth (h));
  1569. put (gridBox, first.reduced (0, 1));
  1570. auto second = juce::Rectangle<int> (panel.getX(), row2, panel.getWidth(), h);
  1571. patternLabelArea = second.removeFromLeft (captionWidth);
  1572. put (patternMenuButton, second.removeFromRight (h));
  1573. if (narrowSnap) // (the pattern box keeps room for a name)
  1574. {
  1575. put (newPatternButton, patternLabelArea.withWidth (h));
  1576. patternLabelArea = {};
  1577. }
  1578. else
  1579. {
  1580. put (newPatternButton, second.removeFromRight (h));
  1581. second.removeFromRight (2);
  1582. }
  1583. put (patternBox, second.reduced (0, 1));
  1584. break;
  1585. }
  1586. case Group::windows: // the windows and the plugin picker
  1587. grid (panel, { &panelButtons[(std::size_t) Panel::playlist], &panelButtons[(std::size_t) Panel::channelRack],
  1588. &panelButtons[(std::size_t) Panel::pianoRoll], &panelButtons[(std::size_t) Panel::mixer],
  1589. &panelButtons[(std::size_t) Panel::browser], &pluginPickerButton });
  1590. break;
  1591. case Group::file: // new, open, save over export, undo, redo
  1592. grid (panel, { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton });
  1593. if (fileWide)
  1594. put (audioEditorButton, juce::Rectangle<int> (panel.getX() + 3 * (h + 2), row1, h, h)); // (round 190mv, DF-35)
  1595. else
  1596. hide ({ &audioEditorButton }); // (round 190nk: no room for a fourth column)
  1597. break;
  1598. case Group::meters: put (perfMeter, panel.withY (row1).withHeight (2 * h + 2)); break;
  1599. case Group::output: put (output, panel.withY (row1).withHeight (2 * h + 2)); break;
  1600. case Group::chord: put (chordPanel, panel.withY (row1).withHeight (2 * h + 2)); break;
  1601. case Group::multilink: put (multilinkButton, panel.withY (row1).withHeight (h)); break;
  1602. case Group::key: put (keyPanel, panel.withY (row1).withHeight (2 * h + 2)); break;
  1603. case Group::link: put (linkToggle, panel.withY (row1 + h / 2 + 1).withHeight (h).reduced (0, 1)); break; // (centred on the two rows)
  1604. case Group::count_: break;
  1605. }
  1606. }
  1607. layoutUnderToolbar();
  1608. placeExtendedHint(); // round 190mr (DF-49)
  1609. }
  1610. void MainComponent::layoutUnderToolbar()
  1611. {
  1612. // the toolbar's edit mode: its overlay over the toolbar, and its tray between the toolbar and the windows
  1613. const auto tray = toolbarEditor != nullptr ? toolbar::EditOverlay::trayHeight : 0;
  1614. if (toolbarEditor != nullptr)
  1615. {
  1616. toolbarEditor->setBounds (0, 0, getWidth(), toolbarHeight + tray);
  1617. toolbarEditor->setToolbarHeight (toolbarHeight);
  1618. toolbarEditor->toFront (false);
  1619. }
  1620. auto below = getLocalBounds().withTrimmedTop (toolbarHeight + tray);
  1621. if (updateBar.isVisible())
  1622. updateBar.setBounds (below.removeFromTop (updater::UpdateBar::height));
  1623. if (remoteControlBar.isVisible())
  1624. remoteControlBar.setBounds (below.removeFromTop (24));
  1625. workspace.setBounds (below);
  1626. if (danceStage != nullptr)
  1627. {
  1628. danceStage->setBounds (getLocalBounds());
  1629. danceStage->toFront (false);
  1630. }
  1631. if (setupOverlay != nullptr)
  1632. {
  1633. hostSetupOverlayNatively();
  1634. nativechild::place (*setupOverlay, *this, getLocalBounds());
  1635. setupOverlay->toFront (false);
  1636. }
  1637. layoutMapMode(); // (round 190ef)
  1638. if (next3Card != nullptr || tipCard != nullptr) // (round 190np)
  1639. placeOnboardingCards();
  1640. }
  1641. void MainComponent::hostSetupOverlayNatively()
  1642. {
  1643. // issue #116: in front of the native panels and docked plugin windows too (a native child window of its own, showing
  1644. // what is under it); without a native window yet, a plain overlay until there is one
  1645. if (setupOverlay == nullptr || ! nativechild::dockingEnabled() || nativechild::isAttached (*setupOverlay) || getPeer() == nullptr)
  1646. return;
  1647. removeChildComponent (setupOverlay.get());
  1648. if (auto host = nativechild::makeOverlayHost (setupOverlay, *this))
  1649. {
  1650. nativechild::forwardUnusedKeys (*host);
  1651. setupOverlay = std::move (host);
  1652. return;
  1653. }
  1654. addAndMakeVisible (*setupOverlay);
  1655. }
  1656. // --- toolbar layout ------------------------------------------------------------------------------
  1657. // The toolbar's rows and icons, and the editors' tool strips, for one icon size (round 170e3: the size in effect can be
  1658. // one step above the chosen one on a very wide window, toolbarlayout::effectiveIconSize).
  1659. void MainComponent::applyIconSizing (toolbarlayout::IconSize size)
  1660. {
  1661. appliedIconSize = size;
  1662. rowHeight = toolbarlayout::rowHeight (size);
  1663. toolbarHeight = toolbarLayout.visible ? 2 * rowHeight + 12 : rowHeight + 6; // (round 170e3: room for the panel wells)
  1664. if (toolbarLook == toolbarlayout::Look::live) // round 190iv: Live's menu row over its 38 px control bar
  1665. toolbarHeight = toolbarlayout::livebar::menuRow + (toolbarLayout.visible ? toolbarlayout::livebar::band : 2);
  1666. const auto fraction = toolbarlayout::iconFraction (size), maxPx = toolbarlayout::iconMaxPx (size);
  1667. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &audioEditorButton, &recordMenuButton, &newPatternButton,
  1668. &patternMenuButton, &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &snapToggleButton,
  1669. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton })
  1670. b->setIconSizing (fraction, maxPx);
  1671. for (auto& b : panelButtons)
  1672. b.setIconSizing (fraction, maxPx);
  1673. for (auto* b : { &playButton, &stopButton, &recordButton }) // solid transport glyphs on big buttons (round 170e3)
  1674. b->setIconSizing (0.42f, maxPx + 2.0f);
  1675. applyFlTiles(); // (round 190jo: the tiles' glyph box follows the row height)
  1676. ToolStrip::iconSize = size;
  1677. pianoRoll.resized();
  1678. playlist.resized();
  1679. }
  1680. void MainComponent::setToolbarLayout (const toolbarlayout::Layout& layout, bool save)
  1681. {
  1682. const auto scaleChanged = layout.uiScale != toolbarLayout.uiScale;
  1683. if (save && layout.isShown (toolbarlayout::Group::key) != toolbarLayout.isShown (toolbarlayout::Group::key))
  1684. keyPanelFollowsStyle = false; // shown or hidden by hand (round 184a S11): the layout decides from now on
  1685. if (save && layout.isShown (toolbarlayout::Group::link) != toolbarLayout.isShown (toolbarlayout::Group::link))
  1686. linkToggleFollowsStyle = false; // (round 190gl, the same for the Link toggle)
  1687. toolbarLayout = layout;
  1688. applyIconSizing (toolbarlayout::effectiveIconSize (toolbarLayout.iconSize, getWidth()));
  1689. if (save && scaleChanged)
  1690. {
  1691. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  1692. // the windows grow with the zoom: keep their title bars and close buttons on the screen (round 163)
  1693. juce::Timer::callAfterDelay (200, [] { fitAllWindowsOnScreen(); });
  1694. }
  1695. resized();
  1696. repaint();
  1697. if (toolbarEditor != nullptr)
  1698. toolbarEditor->layoutChanged();
  1699. if (save)
  1700. saveUiSettings();
  1701. }
  1702. void MainComponent::showLinkToggle (bool on)
  1703. {
  1704. if (toolbarLayout.isShown (toolbarlayout::Group::link) == on)
  1705. return;
  1706. auto layout = toolbarLayout;
  1707. layout.setShown (toolbarlayout::Group::link, on);
  1708. setToolbarLayout (layout, true); // (by hand: the layout style stops deciding)
  1709. }
  1710. juce::PopupMenu MainComponent::makeToolbarMenu()
  1711. {
  1712. using toolbarlayout::Group;
  1713. juce::PopupMenu menu;
  1714. // FL's toolbar menu (Edit, Separators, Hide, Presets), then LYNX's direct switches per panel
  1715. menu.addSectionHeader (tr ("Toolbar"));
  1716. menu.addItem (tr ("Edit toolbar (drag panels to move, add or remove them)"), toolbarLook == toolbarlayout::Look::fl, toolbarEditor != nullptr,
  1717. [this] { setToolbarEditing (toolbarEditor == nullptr); });
  1718. menu.addItem (tr ("Separators"), true, toolbarLayout.separators, [this] {
  1719. auto layout = toolbarLayout;
  1720. layout.separators = ! layout.separators;
  1721. setToolbarLayout (layout);
  1722. });
  1723. menu.addItem (tr ("Hide the toolbar panels") + shortcutText ("view.toolbar"), true, ! toolbarLayout.visible, [this] {
  1724. auto layout = toolbarLayout;
  1725. layout.visible = ! layout.visible;
  1726. setToolbarLayout (layout);
  1727. });
  1728. juce::PopupMenu presets;
  1729. const auto current = toolbarlayout::matchingPreset (toolbarLayout);
  1730. for (int p = 0; p < toolbarlayout::presetCount; ++p)
  1731. presets.addItem (tr (toolbarlayout::presetName ((toolbarlayout::Preset) p)), true, current == p, [this, p] {
  1732. auto layout = toolbarlayout::applyPreset (toolbarLayout, (toolbarlayout::Preset) p);
  1733. layout.visible = true;
  1734. setToolbarLayout (layout);
  1735. });
  1736. menu.addSubMenu (tr ("Presets"), presets);
  1737. menu.addSectionHeader (tr ("Panels"));
  1738. for (const auto& entry : toolbarLayout.entries)
  1739. {
  1740. const auto group = entry.group;
  1741. menu.addItem (tr (toolbarlayout::groupName (group)), true, entry.shown, [this, group] {
  1742. auto layout = toolbarLayout;
  1743. layout.setShown (group, ! layout.isShown (group));
  1744. layout.visible = true;
  1745. setToolbarLayout (layout);
  1746. });
  1747. }
  1748. // FL 2026's View › Toolbars › "Hint bar" (round 190mr, DF-49, capture 190mr A2): the floating Extended Hint Panel
  1749. menu.addItem (tr ("Hint bar (extended hint panel)"), true, extendedHint != nullptr, [this] { showExtendedHint (extendedHint == nullptr); });
  1750. menu.addSeparator();
  1751. menu.addItem (tr ("Show detected MIDI chords near the hint bar"), true, chordShowNearHint, [this] {
  1752. chordShowNearHint = ! chordShowNearHint;
  1753. chordNearHint.setVisible (false);
  1754. saveUiSettings();
  1755. });
  1756. menu.addSeparator();
  1757. juce::PopupMenu sizes;
  1758. const char* sizeNames[] = { TR_NOOP ("Small icons"), TR_NOOP ("Medium icons"), TR_NOOP ("Large icons") };
  1759. for (int i = 0; i < 3; ++i)
  1760. sizes.addItem (tr (sizeNames[i]), true, (int) toolbarLayout.iconSize == i, [this, i] {
  1761. auto layout = toolbarLayout;
  1762. layout.iconSize = (toolbarlayout::IconSize) i;
  1763. setToolbarLayout (layout);
  1764. });
  1765. menu.addSubMenu (tr ("Icon size"), sizes);
  1766. juce::PopupMenu scales;
  1767. for (auto percent : toolbarlayout::uiScales)
  1768. scales.addItem (juce::String (percent) + "%", true, toolbarLayout.uiScale == percent, [this, percent] {
  1769. auto layout = toolbarLayout;
  1770. layout.uiScale = percent;
  1771. setToolbarLayout (layout);
  1772. });
  1773. menu.addSubMenu (tr ("UI scale"), scales);
  1774. menu.addSeparator();
  1775. menu.addItem (tr ("Customize toolbar..."), [this] { showCustomizeToolbar(); });
  1776. menu.addItem (tr ("Reset toolbar to default"), ! toolbarLayout.isDefault(), false, [this] {
  1777. setToolbarLayout (toolbarlayout::Layout::makeDefault());
  1778. });
  1779. return menu;
  1780. }
  1781. void MainComponent::setToolbarEditing (bool editing)
  1782. {
  1783. if (editing == (toolbarEditor != nullptr))
  1784. return;
  1785. if (editing && toolbarLook != toolbarlayout::Look::fl) // (round 190iv: the panels are FL's toolbar's; the other looks set theirs)
  1786. return;
  1787. if (! editing)
  1788. {
  1789. removeChildComponent (toolbarEditor.get());
  1790. toolbarEditor.reset();
  1791. resized();
  1792. repaint();
  1793. return;
  1794. }
  1795. if (! toolbarLayout.visible) // editing shows the panels
  1796. {
  1797. auto layout = toolbarLayout;
  1798. layout.visible = true;
  1799. setToolbarLayout (layout);
  1800. }
  1801. toolbar::EditOverlay::Host host;
  1802. host.layout = [this] { return toolbarLayout; };
  1803. host.setLayout = [this] (const toolbarlayout::Layout& layout) { setToolbarLayout (layout); };
  1804. host.panels = [this] { return panelBounds; };
  1805. host.fixedArea = [this] { return fixedToolbarArea; };
  1806. host.snapshot = [this] (juce::Rectangle<int> area) {
  1807. // the panel as it looks, without the edit overlay on it
  1808. if (toolbarEditor != nullptr)
  1809. toolbarEditor->setVisible (false);
  1810. auto image = createComponentSnapshot (area, true);
  1811. if (toolbarEditor != nullptr)
  1812. toolbarEditor->setVisible (true);
  1813. return image;
  1814. };
  1815. host.done = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  1816. // after the click that asked for it
  1817. juce::MessageManager::callAsync ([safe] {
  1818. if (safe != nullptr)
  1819. safe->setToolbarEditing (false);
  1820. });
  1821. };
  1822. toolbarEditor = std::make_unique<toolbar::EditOverlay> (std::move (host), toolbarHeight);
  1823. addAndMakeVisible (*toolbarEditor);
  1824. resized();
  1825. repaint();
  1826. if (isShowing())
  1827. toolbarEditor->grabKeyboardFocus();
  1828. }
  1829. void MainComponent::runUndoStep (undokeys::Step step)
  1830. {
  1831. if (step != undokeys::Step::none)
  1832. undoRedo (step == undokeys::Step::redo);
  1833. }
  1834. void MainComponent::flUndo()
  1835. {
  1836. // FL's default: undo, or redo when something is undone ("undo/redo on the same shortcut"); "Alternate undo mode":
  1837. // every press one more step back (core/UndoKeys.h)
  1838. runUndoStep (undokeys::undoKey (alternateUndo, engine.canUndo(), engine.canRedo()));
  1839. }
  1840. void MainComponent::flUndoBackwards()
  1841. {
  1842. // FL's Undo backwards: one more step back; "Alternate undo mode" swaps the two shortcuts, so there it is the
  1843. // undo/redo key (round 190b)
  1844. runUndoStep (undokeys::backwardsKey (alternateUndo, engine.canUndo(), engine.canRedo()));
  1845. }
  1846. void MainComponent::undoRedo (bool redo)
  1847. {
  1848. // FL says in the hint bar what was undone and the undo level ("Undone: ... Level 2/3")
  1849. if (redo ? ! engine.canRedo() : ! engine.canUndo())
  1850. return;
  1851. const auto label = engine.getHistoryLabel (engine.getHistoryPosition() + (redo ? 1 : 0));
  1852. if (redo)
  1853. engine.redo();
  1854. else
  1855. engine.undo();
  1856. // FL's General › "Show undo history in the browser when undoing changes" (off as in FL; round 190mr, DF-135): the
  1857. // Browser shows Current project › History on an undo
  1858. if (! redo && flsettings::options().historyOnUndo.load())
  1859. {
  1860. if (! workspace.isPanelVisible (Panel::browser))
  1861. workspace.show (Panel::browser);
  1862. browser.showHistory();
  1863. }
  1864. ui::Hint h;
  1865. h.text = (redo ? tr ("Redone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) })
  1866. : tr ("Undone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) }));
  1867. h.value = tr ("Level {0}/{1}", { juce::String (engine.getHistoryPosition() + 1), juce::String (engine.getHistorySize()) });
  1868. ui::postHint (h, 2500);
  1869. }
  1870. ui::Hint MainComponent::hintAt (juce::Point<int> p)
  1871. {
  1872. ui::Hint h;
  1873. if (p.y < toolbarHeight)
  1874. {
  1875. h.text = tr ("Toolbar: [RMB] toolbar menu (edit the panels: move, add, remove; presets; hide with Ctrl+F11)");
  1876. h.hasMenu = true;
  1877. }
  1878. return h;
  1879. }
  1880. void MainComponent::showToolbarMenu()
  1881. {
  1882. makeToolbarMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1883. }
  1884. void MainComponent::showCustomizeToolbar()
  1885. {
  1886. auto panel = std::make_unique<toolbar::CustomizePanel> (toolbarLayout);
  1887. panel->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] (const toolbarlayout::Layout& layout) {
  1888. if (safe != nullptr)
  1889. safe->setToolbarLayout (layout);
  1890. };
  1891. juce::DialogWindow::LaunchOptions options;
  1892. options.content.setOwned (fitContentToScreen (std::move (panel)).release());
  1893. options.dialogTitle = tr ("Customize toolbar");
  1894. options.dialogBackgroundColour = theme::colour::bg2;
  1895. options.useNativeTitleBar = true;
  1896. options.resizable = false;
  1897. options.escapeKeyTriggersCloseButton = true;
  1898. if (auto* dialog = options.launchAsync())
  1899. keepAboveMainWindow (*dialog);
  1900. }
  1901. void MainComponent::mouseDown (const juce::MouseEvent& e)
  1902. {
  1903. // a right-click on the toolbar's background (between the panels): show / hide groups, icon size, customize
  1904. if (e.mods.isPopupMenu() && e.y < toolbarHeight)
  1905. showToolbarMenu();
  1906. }
  1907. juce::Rectangle<int> MainComponent::getToolStripAreaForSnapshot (bool playlistStrip)
  1908. {
  1909. auto& editor = playlistStrip ? (juce::Component&) playlist : (juce::Component&) pianoRoll;
  1910. if (! editor.isVisible() || editor.getParentComponent() == nullptr || ! isParentOf (&editor))
  1911. return {};
  1912. const auto area = getLocalArea (&editor, editor.getLocalBounds());
  1913. return area.withHeight (40).withWidth (juce::jmin (area.getWidth(), 900)).getIntersection (getLocalBounds());
  1914. }
  1915. // --- keys --------------------------------------------------------------------------------------
  1916. keys::Context MainComponent::focusContext() const
  1917. {
  1918. if (pianoRollKeysHere()) // (round 183a: docked in the Clip-launch workflow's detail view)
  1919. return keys::Context::pianoRoll;
  1920. switch (workspace.getFocused())
  1921. {
  1922. case Panel::playlist: return keys::Context::playlist;
  1923. case Panel::channelRack: return keys::Context::channelRack;
  1924. case Panel::pianoRoll: return keys::Context::pianoRoll;
  1925. case Panel::mixer: return keys::Context::mixer;
  1926. case Panel::browser: return keys::Context::browser;
  1927. }
  1928. return keys::Context::global;
  1929. }
  1930. void MainComponent::dragOperationStarted (const juce::DragAndDropTarget::SourceDetails&)
  1931. {
  1932. // a drop on a window above this one (the Sampler's waveform, a plugin...) lands there, not on the panel under it
  1933. matchWindowOrderToScreen();
  1934. }
  1935. bool MainComponent::shouldDropFilesWhenDraggedExternally (const juce::DragAndDropTarget::SourceDetails& details, juce::StringArray& files,
  1936. bool& canMoveFiles)
  1937. {
  1938. return externaldrag::shouldDropFiles (details, &engine.getSong(), files, canMoveFiles);
  1939. }
  1940. bool MainComponent::keyPressed (const juce::KeyPress& key)
  1941. {
  1942. const workflowextras::TempToolHold::Scope toolKey (workflowextras::tempTools(), key.getKeyCode()); // round 190iu (issue #191.1)
  1943. if (mapKeyPressed (key)) // round 190ef: the map modes' keys and the key mappings (Clip-launch layout only)
  1944. return true;
  1945. // round 190fo: while the Simple dock shows a Sampler track's pads, V B N M / F G H J / R T Y U / 4 5 6 7 play them
  1946. if (simpleWorkflow != nullptr && ! key.getModifiers().isAnyModifierKeyDown())
  1947. if (const auto padChannel = simpleWorkflow->padChannelForKey (key.getKeyCode()); padChannel >= 0)
  1948. {
  1949. if (! heldKeys.hasTag (key.getKeyCode()))
  1950. heldKeys.press (padChannel, simplepads::padKey, 0.8f, key.getKeyCode());
  1951. return true;
  1952. }
  1953. const auto chord = chordFromKeyPress (key);
  1954. // 1. the typing piano: the keys its layout takes (notes, FL's LOCK) win over the shortcuts; FL's FREE keys don't
  1955. const auto typed = typingKey (key);
  1956. if (typed.taken)
  1957. {
  1958. const auto code = key.getKeyCode();
  1959. if (! heldKeys.hasTag (code) && typingLaunches.count (code) == 0) // key repeat: the notes are already sounding
  1960. {
  1961. // FL sends the typing keyboard's notes as MIDI channel 1 (FUN_011828c0 -> FUN_01181620 channel 0): with
  1962. // "MIDI channel used for playlist live mode" = 1 and Performance mode on, they launch the Playlist's clips
  1963. // (what "Layout Performance mode" is for), else they play the selected channels
  1964. if (engine.typingNotesLaunchClips())
  1965. {
  1966. for (auto note : typed.notes)
  1967. if (perf::Command c; typingPerformance.note (note, true, c))
  1968. engine.performanceCommand (c);
  1969. typingLaunches[code] = typed.notes;
  1970. }
  1971. else
  1972. {
  1973. // round 190ds: Scale keys / Chord pad / Lock to key (core/ScaleKeys.h): the white keys play the project
  1974. // key's degrees or chords; nothing changes in Keys mode without the lock, or with no project key
  1975. auto notes = typed.notes;
  1976. const auto& mode = scalekeys::current();
  1977. if (mode.mode != scalekeys::Mode::keys || mode.lockToKey)
  1978. {
  1979. const auto zRow = keys::typingPianoKey ('Z', typingOctave, 0, 0).notes; // (FL's own layout: Z = C)
  1980. const auto baseC = zRow.empty() ? 60 : zRow.front();
  1981. std::vector<int> mapped;
  1982. for (auto note : typed.notes)
  1983. for (auto n : scalekeys::typedNotes (engine.getSong(), mode, mode.mode == scalekeys::Mode::keys ? note : note - typingRoot, baseC))
  1984. if (std::find (mapped.begin(), mapped.end(), n) == mapped.end())
  1985. mapped.push_back (n);
  1986. notes = std::move (mapped);
  1987. }
  1988. for (auto c : engine.getSelectedChannels())
  1989. for (auto note : notes) // (a chord layout's key plays several)
  1990. heldKeys.press (c, note, 0.8f, code);
  1991. }
  1992. }
  1993. return true;
  1994. }
  1995. const auto pianoKeys = typingPiano && ! isPlainKey (chord); // (a FREE plain key is a shortcut as with the piano off)
  1996. // issue #218 (round 190ng): Esc gives the keys back when a drop-down or button holds them (ui/KeyFocus.h)
  1997. if (key.isKeyCode (juce::KeyPress::escapeKey) && ! key.getModifiers().isAnyModifierKeyDown() && ui::keyfocus::releaseOnEscape (*this))
  1998. return true;
  1999. // round 190ce: Esc ends hot-swap (the reference's key for it) before it means anything else
  2000. if (key.isKeyCode (juce::KeyPress::escapeKey) && ! key.getModifiers().isAnyModifierKeyDown() && browser.isHotSwapping())
  2001. {
  2002. browser.endHotSwap();
  2003. return true;
  2004. }
  2005. // 2. a key the user gave an action himself (Options › Shortcuts) wins over the panels' built-in keys
  2006. // (issue #12: Metronome on 'C' did nothing while the Playlist, whose Knife is 'C', had the focus)
  2007. if (const auto own = keyMap.findUserBound (chord, focusContext(), pianoKeys); ! own.empty() && runAction (own))
  2008. return true;
  2009. // round 190ih: Live's keys in the Clip-launch layout (core/LiveKeys.h); in the other layouts none is taken
  2010. if (const auto live = livekeys::commandFor (chord, layoutStyle); live != livekeys::Command::none
  2011. && dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) == nullptr && runLiveKey (live))
  2012. return true;
  2013. // round 190ef: B is the reference's Draw Mode switch in the Clip-launch layout (core/SessionKeys.h); in the other
  2014. // layouts it stays the Playlist's and Piano roll's brush tool
  2015. if (key.getKeyCode() == 'B' || key.getKeyCode() == 'b')
  2016. if (isPlainKey (chord) && sessionkeys::defaultKeyActs (sessionkeys::Command::drawMode)
  2017. && dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) == nullptr)
  2018. {
  2019. drawmode::toggle();
  2020. return true;
  2021. }
  2022. // (round 190iv's Tab = Session ↔ Arrangement is round 190ih's livekeys::Command::toggleView above, which answers first
  2023. // in the Clip-launch layout; its setClipGridView refreshes 190iv's view selector. One handler kept: rollup 0.1.30)
  2024. // 3. the focused panel's own keys
  2025. const auto focused = workspace.getFocused();
  2026. const auto panelShown = workspace.isPanelVisible (focused);
  2027. if (((panelShown && focused == Panel::pianoRoll) || pianoRollKeysHere()) && pianoRoll.handleKey (key))
  2028. return true;
  2029. if (panelShown && focused == Panel::playlist && ! pianoRollKeysHere() && playlist.handleKey (key))
  2030. return true;
  2031. // issue #195, LYNX extra (off by default): REAPER's W = Home, where nothing above took the key (the typing keyboard
  2032. // and the user's own keys come first; core/TransportEdit.h)
  2033. if (transportedit::wKeyGoesToStart (transportedit::wGoesToStart(), key.getKeyCode(), key.getModifiers().isAnyModifierKeyDown(), false,
  2034. dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) != nullptr)
  2035. && runAction ("transport.toStart"))
  2036. return true;
  2037. // 4. the key map
  2038. if (const auto action = keyMap.find (chord, focusContext(), pianoKeys); ! action.empty() && runAction (action))
  2039. return true;
  2040. // issue #217 (round 190ng): Esc that nothing above used closes the focused panel, as FL 2026 (core/EscClose.h)
  2041. if (key.isKeyCode (juce::KeyPress::escapeKey) && ! key.getModifiers().isAnyModifierKeyDown() && focused != Panel::browser
  2042. && escclose::closesPanel (escclose::enabled(), layoutStyle == layoutstyle::Style::pattern, panelShown))
  2043. {
  2044. workspace.hide (focused);
  2045. refreshPanelButtons();
  2046. return true;
  2047. }
  2048. // 5. issue #182: in the Browser, a typed character no key above took jumps to the row that starts with it (the
  2049. // typing piano, FL's L / R and the hot-swap Q keep their keys)
  2050. return panelShown && focused == Panel::browser && browser.typeToJump (key);
  2051. }
  2052. bool MainComponent::runLiveKey (livekeys::Command command)
  2053. {
  2054. using C = livekeys::Command;
  2055. switch (command)
  2056. {
  2057. case C::toggleView: // Session ↔ Arrangement (from "Both": the Session view)
  2058. if (clipGridView == nullptr)
  2059. return false;
  2060. setClipGridView (shownGridView == PlaylistArea::GridView::grid ? PlaylistArea::GridView::song : PlaylistArea::GridView::grid);
  2061. return true;
  2062. case C::metronome: return runAction ("transport.metronome");
  2063. case C::arrangementRecord: return runAction ("transport.record");
  2064. case C::sessionRecord:
  2065. if (clipGridView == nullptr)
  2066. return false;
  2067. engine.toggleSessionRecord (clipGridSelection (*clipGridView).second);
  2068. return true;
  2069. case C::backToArrangement:
  2070. engine.launcherCommand ({ launcher::Command::Type::backToArrangement });
  2071. return true;
  2072. case C::computerKeyboard: return runAction ("view.typingPiano");
  2073. case C::browser: return runAction ("panel.browser");
  2074. case C::follow: return runAction ("playlist.follow");
  2075. case C::consolidate: return runAction ("tools.consolidateSelection");
  2076. case C::continuePlay: // Live: playback goes on from the point where it stopped (not from where it started)
  2077. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn())
  2078. return true;
  2079. if (stoppedAtTicks >= 0.0)
  2080. engine.seek (stoppedAtTicks);
  2081. notePlayStart (true);
  2082. transportPaused = false;
  2083. engine.startPlayback();
  2084. return true;
  2085. case C::none: break;
  2086. }
  2087. return false;
  2088. }
  2089. bool MainComponent::isPlainKey (const keys::Chord& chord) noexcept
  2090. {
  2091. return (chord.mods & (keys::ctrl | keys::alt | keys::shift)) == 0;
  2092. }
  2093. keys::TypingKey MainComponent::typingKey (const juce::KeyPress& key) const
  2094. {
  2095. if (! typingPiano || ! isPlainKey (chordFromKeyPress (key)))
  2096. return {};
  2097. // the key's place (FL's table goes by scan code): a German keyboard's Y, left of X, is the Z row's first key
  2098. const auto place = keys::typingpiano::physicalKey (key.getKeyCode(), [] (int code) { return scanCodeOfKeyCode (code); });
  2099. return keys::typingPianoKey (keys::letterOfKeyCode (place), typingOctave, typingRoot, typingLayout);
  2100. }
  2101. void MainComponent::releaseTypingLaunches (bool all)
  2102. {
  2103. for (auto it = typingLaunches.begin(); it != typingLaunches.end();)
  2104. if (all || ! juce::KeyPress::isKeyCurrentlyDown (it->first))
  2105. {
  2106. for (auto note : it->second)
  2107. if (perf::Command c; typingPerformance.note (note, false, c))
  2108. engine.performanceCommand (c);
  2109. it = typingLaunches.erase (it);
  2110. }
  2111. else
  2112. ++it;
  2113. }
  2114. bool MainComponent::keyFromSecondaryWindow (const juce::KeyPress& key)
  2115. {
  2116. // Issue #179: while a modal dialog is open (Rename pattern, Export, a question...) LYNX is blocked as FL is: the keys the
  2117. // dialog leaves unused don't run the main window's shortcuts. F4 in "Rename pattern" opened one more rename window on
  2118. // every press (FL's dialog takes the key and nothing happens).
  2119. if (modalDialogOpen())
  2120. return false;
  2121. // (round 165q / issue #12) a text field keeps its typing keys; the rest runs the global actions
  2122. const auto typingIntoText = dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) != nullptr;
  2123. const auto chord = chordFromKeyPress (key);
  2124. // issue #117: the typing piano plays from Sytrus's window (any LYNX window) too; its release is polled (timer)
  2125. if (keys::KeyMap::secondaryWindowPlaysNote (typingKey (key).taken, typingIntoText))
  2126. return keyPressed (key);
  2127. const auto action = keyMap.findFromSecondaryWindow (chord, typingIntoText, typingPiano && (! isPlainKey (chord) || typingKey (key).taken));
  2128. return ! action.empty() && runAction (action);
  2129. }
  2130. bool MainComponent::keyFromPluginView (const juce::KeyPress& key, bool optionOn)
  2131. {
  2132. // the typing piano as over the main window (its release is polled, MainComponent::keyStateChanged). With the
  2133. // plugin's "Typing keyboard priority" off (LYNX first) the shortcuts run too; keys that do nothing here stay the plugin's.
  2134. if (typingKey (key).taken)
  2135. return keyPressed (key);
  2136. return optionOn && keyFromSecondaryWindow (key);
  2137. }
  2138. bool MainComponent::runAction (const std::string& id)
  2139. {
  2140. auto is = [&id] (const char* name) { return id == name; };
  2141. if (id.rfind ("view.detail", 0) == 0) // round 183a: Clip-launch workflow only (false: the chord falls through as before)
  2142. return runDetailAction (id);
  2143. // Round 190ce: the Browser's collections (the number keys on its selected row), hot-swap, the Device View's 0 key
  2144. if (id.rfind ("browser.collection", 0) == 0 && id.size() == 19 && id.back() >= '1' && id.back() <= '7')
  2145. {
  2146. browser.toggleCollectionOnSelection (id.back() - '1');
  2147. return true;
  2148. }
  2149. if (id == "browser.clearCollections")
  2150. {
  2151. browser.clearCollectionsOnSelection();
  2152. return true;
  2153. }
  2154. if (id == "view.hotSwap")
  2155. {
  2156. // (round 190ck: the default Q only in the Ableton-style layout, core/HotSwap.h keyActsInLayout)
  2157. if (! hotswap::keyActsInLayout (layoutStyle, keyMap.isDefault ("view.hotSwap")))
  2158. return false;
  2159. if (browser.isHotSwapping())
  2160. {
  2161. browser.endHotSwap();
  2162. return true;
  2163. }
  2164. // the Device View's selected device when it shows one, else the selected channel
  2165. auto target = detailView != nullptr ? detailView->selectedDeviceTarget() : hotswap::Target();
  2166. if (! target.active())
  2167. target = hotswap::targetOfChannel (engine.getSong(), engine.getSelectedChannel());
  2168. if (! target.active())
  2169. return false;
  2170. toggleHotSwap (target);
  2171. return true;
  2172. }
  2173. // issue #219 (round 190ng): the main snap on / off (FL's Backspace in the Playlist and the Piano roll; any key the user
  2174. // gives "snap.toggle" from any window)
  2175. if (id == "playlist.snapToggle" || id == "pianoRoll.snapToggle" || id == "snap.toggle")
  2176. {
  2177. EditorGlobals::get().toggleGrid();
  2178. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  2179. return true;
  2180. }
  2181. if (id == "rack.follow")
  2182. {
  2183. auto& g = EditorGlobals::get();
  2184. g.setFollowingView (EditorGlobals::FollowView::channelRack, ! g.isFollowingView (EditorGlobals::FollowView::channelRack));
  2185. rackFollowButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  2186. return true;
  2187. }
  2188. // round 190iu (issue #191.1, FL): a tool key held down is a temporary tool; letting go returns to the one before
  2189. const auto toolKey = [] (temptool::Editor editor, EditTool before, EditTool chosen, std::function<EditTool()> now, std::function<void (EditTool)> back) {
  2190. auto& hold = workflowextras::tempTools();
  2191. hold.toolKey (editor, hold.keyBeingHandled(), before, chosen, std::move (now), std::move (back));
  2192. };
  2193. if (id.rfind ("pianoRoll.", 0) == 0)
  2194. {
  2195. const auto before = pianoRoll.currentTool();
  2196. if (pianoRoll.runKeyAction (id)) // tools, slide, channel keys
  2197. {
  2198. if (id.rfind ("pianoRoll.tool.", 0) == 0)
  2199. toolKey (temptool::Editor::pianoRoll, before, pianoRoll.currentTool(), [this] { return pianoRoll.currentTool(); },
  2200. [this] (EditTool t) { pianoRoll.setToolForSnapshot (t); });
  2201. return true;
  2202. }
  2203. }
  2204. if (id.rfind ("playlist.tool.", 0) == 0)
  2205. {
  2206. const auto before = playlist.currentTool();
  2207. if (playlist.runKeyAction (id))
  2208. {
  2209. toolKey (temptool::Editor::playlist, before, playlist.currentTool(), [this] { return playlist.currentTool(); },
  2210. [this] (EditTool t) { playlist.setToolForSnapshot (t); });
  2211. return true;
  2212. }
  2213. }
  2214. if (is ("transport.playStop")) playStop();
  2215. else if (is ("transport.pause")) playPause();
  2216. else if (is ("transport.playFromStart")) playFromStart();
  2217. else if (is ("transport.toStart") || is ("playlist.toStart") || is ("pianoRoll.toStart")) moveToStart(); // (issue #195)
  2218. else if (is ("transport.toggleMode")) toggleMode();
  2219. else if (is ("transport.nextMarker")) engine.jumpToNextMarker (true);
  2220. else if (is ("transport.previousMarker")) engine.jumpToNextMarker (false);
  2221. else if (is ("view.typingPiano")) toggleTypingPiano();
  2222. else if (is ("options.multilink")) engine.setMultilink (! engine.isMultilinkOn());
  2223. else if (is ("view.toolbar"))
  2224. {
  2225. auto layout = toolbarLayout;
  2226. layout.visible = ! layout.visible;
  2227. setToolbarLayout (layout);
  2228. }
  2229. else if (is ("panel.playlist")) togglePanel (Panel::playlist);
  2230. else if (is ("panel.channelRack")) togglePanel (Panel::channelRack);
  2231. else if (is ("panel.pianoRoll"))
  2232. {
  2233. togglePanel (Panel::pianoRoll);
  2234. if (workspace.isPanelVisible (Panel::pianoRoll))
  2235. pianoRoll.scrollToNotes();
  2236. }
  2237. else if (is ("panel.browser")) togglePanel (Panel::browser);
  2238. else if (is ("panel.mixer")) togglePanel (Panel::mixer);
  2239. else if (is ("panel.maximisePlaylist"))
  2240. {
  2241. workspace.toggleMaximised (Panel::playlist);
  2242. refreshPanelButtons();
  2243. }
  2244. else if (is ("pattern.next")) selectPattern (stepPattern (engine.getSong(), 1));
  2245. else if (is ("pattern.previous")) selectPattern (stepPattern (engine.getSong(), -1));
  2246. else if (is ("pattern.nextEmpty")) nextEmptyPattern();
  2247. else if (is ("pattern.firstEmpty")) { engine.editSong ([] (Song& s) { gotoFirstEmptyPattern (s); }); showRenamePattern (engine.getSong().currentPattern); }
  2248. else if (is ("pattern.nextEmptyNoName")) engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  2249. else if (is ("pattern.delete")) deleteCurrentPattern();
  2250. else if (is ("pattern.rename")) showRenamePattern (engine.getSong().currentPattern);
  2251. else if (is ("pattern.insert")) insertPatternHere();
  2252. else if (is ("pattern.clone")) clonePatternNow();
  2253. else if (is ("pattern.moveUp")) movePatternNow (-1);
  2254. else if (is ("pattern.moveDown")) movePatternNow (1);
  2255. else if (id.rfind ("pattern.select", 0) == 0) selectPattern (std::stoi (id.substr (14)) - 1);
  2256. else if (is ("view.pluginPicker")) togglePluginPicker();
  2257. else if (is ("view.projectPicker")) toggleProjectPicker();
  2258. else if (is ("panel.quickAdd"))
  2259. {
  2260. // FL's F8 opens the plugin picker or closes it (FLEngine 0xebf510, round 167o)
  2261. if (auto* open = findToolWindow ("quickadd"))
  2262. closeToolWindowOf (*open->getContentComponent());
  2263. else
  2264. showQuickAdd();
  2265. }
  2266. else if (is ("edit.history")) showHistory();
  2267. else if (is ("tools.stopSound")) engine.stopSound();
  2268. else if (is ("browser.search"))
  2269. {
  2270. showPanel (Panel::browser);
  2271. browser.focusSearch();
  2272. }
  2273. else if (is ("transport.record")) toggleRecording();
  2274. else if (is ("record.quickAudio")) quickRecordAudio();
  2275. else if (is ("transport.metronome"))
  2276. {
  2277. engine.getTransport().metronome.store (! engine.getTransport().metronome.load());
  2278. refreshModeButton();
  2279. saveUiSettings(); // FL keeps it (ToolbarForm "MetronomeBtn", issue #152)
  2280. }
  2281. else if (is ("record.countIn"))
  2282. {
  2283. // FL's Ctrl+P (issue #152): off <-> on at the length chosen last (it was always 1 bar), kept between sessions
  2284. auto o = engine.getRecordOptions();
  2285. o.countInBars = countin::toggled (o.countInBars, o.countInLength);
  2286. engine.setRecordOptions (o);
  2287. refreshRecordOptionButtons();
  2288. saveUiSettings();
  2289. }
  2290. else if (is ("record.captureMidi")) // round 170d (Ableton's Capture MIDI, Logic's Capture as Recording)
  2291. {
  2292. // round 190ef / 190em: in the Clip-launch layout with the clip grid on screen, the phrase goes to the ARMED track
  2293. // (Live 12.4.16, live check 190ei; no armed track: the grid's selected track), in the selected scene's slot as a
  2294. // new clip that is launched at once, or into the clip that track plays
  2295. if (isClipLaunchWorkflow() && clipGridView != nullptr && clipGridView->isShowing())
  2296. {
  2297. auto [track, scene] = clipGridSelection (*clipGridView);
  2298. for (int t = 0; t < launcher::maxTracks; ++t)
  2299. if (engine.isGridTrackArmed (t))
  2300. {
  2301. track = t;
  2302. break;
  2303. }
  2304. int placed = -1;
  2305. bool into = false;
  2306. const auto r = engine.captureMidiToSlot (track, scene, placed, into);
  2307. if (r.notes > 0 && placed >= 0)
  2308. ui::postHint ({ into ? tr ("Capture MIDI: {0} notes put in the playing clip", { juce::String (r.notes) })
  2309. : tr ("Capture MIDI: {0} notes put in a new clip", { juce::String (r.notes) }), {}, false, false }, 4000);
  2310. else
  2311. ui::postHint ({ tr ("Capture MIDI: nothing to capture (play some notes first, without recording)"), {}, false, false }, 4000);
  2312. return true;
  2313. }
  2314. const auto r = engine.captureMidi();
  2315. if (r.notes > 0)
  2316. ui::postHint ({ tr ("Capture MIDI: {0} notes put in the pattern", { juce::String (r.notes) }), {}, false, false }, 4000);
  2317. else
  2318. ui::postHint ({ tr ("Capture MIDI: nothing to capture (play some notes first, without recording)"), {}, false, false }, 4000);
  2319. }
  2320. else if (is ("record.waitForInput"))
  2321. {
  2322. auto o = engine.getRecordOptions();
  2323. o.waitForInput = ! o.waitForInput;
  2324. engine.setRecordOptions (o);
  2325. refreshRecordOptionButtons();
  2326. }
  2327. else if (is ("record.blend") || is ("record.loop") || is ("record.punch") || is ("record.punchIn") || is ("record.punchOut"))
  2328. {
  2329. auto o = engine.getRecordOptions();
  2330. if (is ("record.blend"))
  2331. o.mode = o.mode == RecordMode::overdub ? RecordMode::replace : RecordMode::overdub;
  2332. else if (is ("record.loop"))
  2333. o.loopRecord = ! o.loopRecord;
  2334. else if (is ("record.punch"))
  2335. {
  2336. o.punchLoopRegion = ! o.punchLoopRegion;
  2337. if (o.punchLoopRegion) // (the one switch: both ends, round 163's punch)
  2338. o.punchIn = o.punchOut = true;
  2339. }
  2340. else // round 190lx (DL-61): Live's Punch-In / Punch-Out switches, each on its own
  2341. {
  2342. auto in = o.punchLoopRegion && o.punchIn, out = o.punchLoopRegion && o.punchOut;
  2343. (is ("record.punchIn") ? in : out) = ! (is ("record.punchIn") ? in : out);
  2344. o.punchLoopRegion = in || out;
  2345. if (o.punchLoopRegion)
  2346. o.punchIn = in, o.punchOut = out;
  2347. }
  2348. engine.setRecordOptions (o);
  2349. refreshRecordOptionButtons();
  2350. saveUiSettings();
  2351. }
  2352. else if (is ("record.stepEdit"))
  2353. {
  2354. engine.setStepEdit (! engine.isStepEdit());
  2355. stepSeekTick = stepPrevTick = -1.0; // starts at the position shown now
  2356. refreshRecordOptionButtons();
  2357. }
  2358. else if (is ("rack.graphEditor")) rack.toggleGraphLanes();
  2359. else if (is ("rack.pianoRollView"))
  2360. {
  2361. rack.setPianoRollView (! rack.isPianoRollView());
  2362. saveUiSettings();
  2363. }
  2364. else if (is ("view.audioEditor")) openAudioEditorForSelection();
  2365. else if (is ("channel.soloSelected")) rack.solo (engine.getSelectedChannel());
  2366. else if (is ("automation.lastTweaked"))
  2367. {
  2368. // FL's Add › Automation for last tweaked parameter (round 143) from a key (round 190an): LYNX's own controls
  2369. // and a hosted plugin's parameters alike (AudioEngine::noteTweaked keeps the last moved one)
  2370. if (const auto t = engine.getLastTweaked (0))
  2371. createAutomationClip (engine, *t);
  2372. else
  2373. ui::postHint ({ tr ("Automation for last tweaked parameter"), tr ("Last tweaked: none") }, 3000);
  2374. }
  2375. else if (is ("view.tempoTapper")) openTempoTapper (engine);
  2376. else if (is ("view.sampleBrowser")) toggleSampleBrowser();
  2377. else if (is ("view.pluginDatabase"))
  2378. {
  2379. showPanel (Panel::browser);
  2380. browser.showPluginDatabase();
  2381. }
  2382. else if (is ("view.midiSettings") || is ("view.projectInfo"))
  2383. {
  2384. // FL's F10 / F11 (round 167o, issue #23): the same key closes Settings showing that page; on another page it
  2385. // switches in place
  2386. const auto page = is ("view.midiSettings") ? SettingsPage::midi : SettingsPage::info;
  2387. const auto shown = shownSettingsPage();
  2388. switch (keys::settingsKeyPress (shown >= 0, shown, (int) page))
  2389. {
  2390. case keys::SettingsKey::close: closeSettings(); break;
  2391. case keys::SettingsKey::switchPage: switchSettingsPage (page); break;
  2392. case keys::SettingsKey::open: openSettings ((int) page); break;
  2393. }
  2394. }
  2395. else if (is ("view.settings"))
  2396. {
  2397. // issue #181: Ctrl+, / Cmd+, opens Settings where it was left (General at first), and closes it when open
  2398. if (shownSettingsPage() >= 0)
  2399. closeSettings();
  2400. else
  2401. openSettings (lastSettingsPage);
  2402. }
  2403. else if (is ("view.closeUnfocusedWindows")) closeUnfocusedWindows();
  2404. else if (is ("view.alignChannelEditors")) alignAllChannelEditors (engine.getSelectedChannel());
  2405. else if (is ("view.touchKeyboard")) toggleTouchKeyboard (engine);
  2406. else if (is ("view.closePluginWindows") || is ("view.closeWindows"))
  2407. {
  2408. PluginWindows::closeAll();
  2409. ParametricEqWindows::closeAll(); // every native effect / controller editor
  2410. if (is ("view.closeWindows")) // FL's F12: the editors and tool windows too (LYNX's docked panels stay)
  2411. {
  2412. closeAutomationEditors();
  2413. closeChannelSettings();
  2414. closeAllToolWindows();
  2415. closeHelp();
  2416. }
  2417. }
  2418. else if (is ("rack.groupSelected")) rack.groupSelected();
  2419. else if (is ("rack.mixerSelectors")) // round 190ld (DE-26): FL's "Show mixer track selectors"
  2420. {
  2421. ChannelRackComponent::showMixerSelectors = ! ChannelRackComponent::showMixerSelectors;
  2422. rack.updateSize();
  2423. rack.resized();
  2424. rack.repaint();
  2425. saveUiSettings();
  2426. }
  2427. else if (is ("rack.zipSelected")) rack.zipSelected(); // round 190mk (DE-38)
  2428. else if (is ("rack.unzipAll")) rack.unzipAll();
  2429. else if (is ("rack.restretchAll")) engine.restretchAll(); // round 190mp (DE-38)
  2430. else if (is ("rack.filterPrevious")) rack.stepFilterGroup (-1); // round 190ld (DE-37)
  2431. else if (is ("rack.filterNext")) rack.stepFilterGroup (1);
  2432. else if (is ("rack.rename")) // (issue #201, round 190ll)
  2433. {
  2434. if (const auto c = engine.getSelectedChannel(); c >= 0 && c < (int) engine.getSong().channels.size())
  2435. rack.rename (c);
  2436. }
  2437. else if (is ("rack.changeIcon")) // issue #220 (round 190ng): F3, the icon picker of the selected channel
  2438. {
  2439. if (const auto c = engine.getSelectedChannel(); c >= 0 && c < (int) engine.getSong().channels.size())
  2440. {
  2441. const auto mouse = juce::Desktop::getMousePosition();
  2442. ui::showTrackIconPicker ({ mouse.x, mouse.y, 1, 1 }, engine.getSong().channels[(std::size_t) c].icon, [this, targets = engine.getSelectedChannels(), c] (int icon) {
  2443. engine.editSong ([targets, c, icon] (Song& s) {
  2444. for (const auto t : targets.empty() ? std::vector<int> { c } : targets)
  2445. if (t >= 0 && t < (int) s.channels.size())
  2446. s.channels[(std::size_t) t].icon = icon;
  2447. });
  2448. });
  2449. }
  2450. }
  2451. else if (is ("rack.rotateLeft")) rack.rotateSelected (-1);
  2452. else if (is ("rack.rotateRight")) rack.rotateSelected (1);
  2453. else if (is ("browser.previous")) browser.step (-1, false);
  2454. else if (is ("browser.next")) browser.step (1, false);
  2455. else if (is ("browser.findNext")) browser.findMatch (1); // round 190lr (DF-97)
  2456. else if (is ("browser.findPrevious")) browser.findMatch (-1);
  2457. else if (is ("browser.historyBack")) browser.walkHistory (-1); // round 190lr (DF-96 / DL-102)
  2458. else if (is ("browser.historyForward")) browser.walkHistory (1);
  2459. else if (is ("browser.swapPrevious")) browser.step (-1, true);
  2460. else if (is ("browser.swapNext")) browser.step (1, true);
  2461. else if (is ("browser.load")) browser.loadSelected();
  2462. else if (is ("browser.closeFolder")) browser.openFolder (false);
  2463. else if (is ("browser.openFolder"))
  2464. {
  2465. // round 190ld (DL-98, Clip-launch only): Live's → previews a selected file; on a folder it opens it as before
  2466. if (! (layoutStyle == layoutstyle::Style::clipLaunch && browser.previewSelected()))
  2467. browser.openFolder (true);
  2468. }
  2469. else if (is ("browser.previewLive")) // round 190ld (DL-98): Live's Shift+Enter, Clip-launch only
  2470. {
  2471. if (layoutStyle != layoutstyle::Style::clipLaunch || ! browser.previewSelected())
  2472. return false;
  2473. }
  2474. else if (is ("browser.rename"))
  2475. {
  2476. if (! browser.renameSelectedPlugin()) // not a plugin: F2's global action (rename the pattern)
  2477. showRenamePattern (engine.getSong().currentPattern);
  2478. }
  2479. else if (id.rfind ("pianoRoll.", 0) == 0) return pianoRoll.runAction (id);
  2480. else if (is ("playlist.pickerPanel")) setPickerPanelOn (! pickerPanelOn);
  2481. else if (workflowextras::runAction (id)) return true; // round 190iu: its switches (Playlist menu)
  2482. else if (id.rfind ("playlist.", 0) == 0) return playlist.runAction (id);
  2483. else if (id.rfind ("mixer.", 0) == 0) return mixer.runAction (id);
  2484. else if (is ("file.new")) newProject();
  2485. else if (is ("file.open")) chooseFileToOpen();
  2486. else if (is ("file.save")) save (false);
  2487. else if (is ("file.saveAs")) save (true);
  2488. else if (is ("file.saveNewVersion")) saveNewVersion();
  2489. else if (id.rfind ("file.recent", 0) == 0) openRecent (std::atoi (id.c_str() + 11) - 1);
  2490. else if (is ("file.export")) exportAudio();
  2491. else if (is ("file.exportMaster")) showMasterDialog (engine, currentFile.getParentDirectory(), projectName);
  2492. else if (is ("file.exportMp3")) exportAudio (1);
  2493. else if (is ("file.exportMidi")) exportMidiFile();
  2494. else if (is ("tools.consolidateSelection")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), false);
  2495. else if (is ("tools.consolidateSelectionSongStart")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), true);
  2496. else if (is ("edit.undo")) flUndo();
  2497. else if (is ("edit.undoBackwards")) flUndoBackwards();
  2498. else if (is ("edit.redo")) undoRedo (true);
  2499. else if (is ("help.shortcuts"))
  2500. {
  2501. if (helpWindow != nullptr) // F1 again closes the sheet (issue #23)
  2502. closeHelp();
  2503. else
  2504. showHelp();
  2505. }
  2506. else if (is ("rack.selectPrevious")) rack.selectRelative (-1, false);
  2507. else if (is ("rack.selectNext")) rack.selectRelative (1, false);
  2508. else if (is ("rack.extendUp")) rack.selectRelative (-1, true);
  2509. else if (is ("rack.extendDown")) rack.selectRelative (1, true);
  2510. else if (is ("rack.moveUp")) rack.moveSelected (-1);
  2511. else if (is ("rack.moveDown")) rack.moveSelected (1);
  2512. else if (is ("rack.selectAll")) rack.selectAll();
  2513. else if (is ("rack.clone")) rack.cloneSelected();
  2514. else if (is ("rack.deleteSelected")) rack.deleteSelected();
  2515. else if (is ("rack.cut")) rack.cutSelected();
  2516. else if (is ("rack.copy")) rack.copySelected();
  2517. else if (is ("rack.paste")) rack.pasteSelected();
  2518. else if (is ("rack.sendToInserts")) rack.sendSelectedToInserts();
  2519. else if (id.rfind ("rack.mute", 0) == 0) rack.toggleMute (std::stoi (id.substr (9)) - 1);
  2520. else if (id.rfind ("rack.solo", 0) == 0) rack.solo (std::stoi (id.substr (9)) - 1);
  2521. else
  2522. return false;
  2523. return true;
  2524. }
  2525. bool MainComponent::keyStateChanged (bool)
  2526. {
  2527. // JUCE has no per-key "keyReleased"; check which held keys were released (each held note remembers its
  2528. // channel and key, so the selection changing meanwhile can't leave one sounding)
  2529. std::vector<int> released;
  2530. heldKeys.forEachTag ([&released] (int code) {
  2531. if (! juce::KeyPress::isKeyCurrentlyDown (code))
  2532. released.push_back (code);
  2533. });
  2534. for (auto code : released)
  2535. heldKeys.releaseTag (code);
  2536. releaseTypingLaunches (false);
  2537. // round 190ef: a mapped computer key let go: its mappings get the release (a clip in Gate mode stops)
  2538. for (auto it = heldMappedKeys.begin(); it != heldMappedKeys.end();)
  2539. if (! juce::KeyPress::isKeyCurrentlyDown (*it))
  2540. {
  2541. for (const auto& f : remotemap::keyFires (engine.getSong(), *it, false))
  2542. fireRemote (f);
  2543. it = heldMappedKeys.erase (it);
  2544. }
  2545. else
  2546. ++it;
  2547. return false;
  2548. }
  2549. // --- round 190ef: MIDI Map Mode / Key Map Mode (ui/MapMode.h, core/RemoteMap.h) ------------------------------------------
  2550. void MainComponent::setMapMode (remotemap::Mode mode)
  2551. {
  2552. if (layoutStyle != layoutstyle::Style::clipLaunch)
  2553. mode = remotemap::Mode::off;
  2554. if (mode != remotemap::Mode::off && mapOverlay == nullptr)
  2555. {
  2556. mapOverlay = std::make_unique<mapmode::Overlay> (engine, *this);
  2557. mapOverlay->onMessage = [] (const juce::String& text) { ui::postHint ({ text, {}, false, false }, 5000); };
  2558. addChildComponent (*mapOverlay);
  2559. mappingBrowser = std::make_unique<mapmode::MappingBrowser> (engine);
  2560. addChildComponent (*mappingBrowser);
  2561. }
  2562. if (mapOverlay == nullptr)
  2563. return;
  2564. const auto was = mapOverlay->getMode();
  2565. engine.setMapMode (mode);
  2566. mapOverlay->setMode (mode);
  2567. mapOverlay->setVisible (mode != remotemap::Mode::off);
  2568. mappingBrowser->setMode (mode);
  2569. mappingBrowser->setVisible (mode != remotemap::Mode::off);
  2570. if (clipGridView != nullptr) // (round 190kc: Live's Relative Session Mapping Strip under the grid)
  2571. setClipGridMapStrip (*clipGridView, mode != remotemap::Mode::off);
  2572. layoutMapMode();
  2573. syncClipLaunchSwitches();
  2574. if (mode != was)
  2575. ui::postHint ({ mode == remotemap::Mode::midi ? tr ("MIDI Map Mode: click an element, then move a control on your MIDI device (Ctrl+M ends it)")
  2576. : mode == remotemap::Mode::key ? tr ("Key Map Mode: click an element, then press a computer key (Ctrl+K ends it)")
  2577. : tr ("Map mode off: the mappings act"),
  2578. {}, false, false },
  2579. 5000);
  2580. }
  2581. void MainComponent::layoutMapMode()
  2582. {
  2583. if (mapOverlay == nullptr || ! mapOverlay->isVisible())
  2584. return;
  2585. mapOverlay->setBounds (getLocalBounds());
  2586. mapOverlay->toFront (false);
  2587. // the Mapping Browser takes the Browser's place (the reference: "available while a map mode is on"); with the Browser
  2588. // hidden, a strip at the left of the workspace
  2589. auto browserShown = browser.getWidth() > 0;
  2590. for (const juce::Component* c = &browser; c != nullptr && c != this; c = c->getParentComponent())
  2591. browserShown = browserShown && c->isVisible();
  2592. auto area = browserShown ? getLocalArea (&browser, browser.getLocalBounds())
  2593. : getLocalArea (&workspace, workspace.getLocalBounds()).removeFromLeft (juce::jmin (320, getWidth() / 3));
  2594. mappingBrowser->setBounds (area);
  2595. mappingBrowser->toFront (false);
  2596. }
  2597. bool MainComponent::mapKeyPressed (const juce::KeyPress& key)
  2598. {
  2599. if (layoutStyle != layoutstyle::Style::clipLaunch)
  2600. return false;
  2601. const auto mods = key.getModifiers();
  2602. auto code = key.getKeyCode();
  2603. if (code >= 'a' && code <= 'z')
  2604. code -= 'a' - 'A';
  2605. const auto command = mods.isCommandDown() && ! mods.isAltDown() && ! mods.isShiftDown();
  2606. if (command && code == 'M' && sessionkeys::defaultKeyActs (sessionkeys::Command::midiMapMode))
  2607. {
  2608. setMapMode (getMapMode() == remotemap::Mode::midi ? remotemap::Mode::off : remotemap::Mode::midi);
  2609. return true;
  2610. }
  2611. if (command && code == 'K' && sessionkeys::defaultKeyActs (sessionkeys::Command::keyMapMode))
  2612. {
  2613. setMapMode (getMapMode() == remotemap::Mode::key ? remotemap::Mode::off : remotemap::Mode::key);
  2614. return true;
  2615. }
  2616. const auto plain = ! mods.isCommandDown() && ! mods.isAltDown() && ! mods.isCtrlDown();
  2617. if (getMapMode() != remotemap::Mode::off && mapOverlay->selection().has_value())
  2618. {
  2619. if (plain && (code == juce::KeyPress::deleteKey || code == juce::KeyPress::backspaceKey))
  2620. {
  2621. mapOverlay->unmapSelected();
  2622. return true;
  2623. }
  2624. if (getMapMode() == remotemap::Mode::key && plain && ! mods.isShiftDown() && code != juce::KeyPress::escapeKey)
  2625. {
  2626. mapOverlay->assignKey (code);
  2627. return true;
  2628. }
  2629. }
  2630. // the key mappings act while no map mode is on; a mapped key wins over the typing keyboard and the shortcuts
  2631. if (getMapMode() == remotemap::Mode::off && plain && ! mods.isShiftDown() && ! engine.getSong().remoteMappings.empty())
  2632. {
  2633. const auto fires = remotemap::keyFires (engine.getSong(), code, true);
  2634. if (fires.empty())
  2635. return false;
  2636. if (std::find (heldMappedKeys.begin(), heldMappedKeys.end(), code) == heldMappedKeys.end()) // (not the key's repeat)
  2637. {
  2638. heldMappedKeys.push_back (code);
  2639. for (const auto& f : fires)
  2640. fireRemote (f);
  2641. }
  2642. return true;
  2643. }
  2644. return false;
  2645. }
  2646. void MainComponent::fireRemote (const remotemap::Fire& f)
  2647. {
  2648. const auto press = f.edge == remotemap::Edge::press;
  2649. const auto& t = f.target;
  2650. switch (t.action)
  2651. {
  2652. case RemoteAction::parameter:
  2653. if (press) // (a key toggles the parameter between Min and Max)
  2654. if (const auto now = engine.currentTargetValue (t.param); now >= 0.0f)
  2655. engine.applyTargetValues ({ { t.param, remotemap::keyToggle (now, f.min, f.max) } });
  2656. break;
  2657. case RemoteAction::clipSlot:
  2658. engine.launcherCommand ({ press ? launcher::Command::Type::launch : launcher::Command::Type::release, t.track, t.scene });
  2659. break;
  2660. case RemoteAction::sceneLaunch:
  2661. if (press)
  2662. engine.launcherCommand ({ launcher::Command::Type::launchScene, 0, t.scene });
  2663. break;
  2664. case RemoteAction::trackStop:
  2665. if (press)
  2666. engine.launcherCommand ({ launcher::Command::Type::stopTrack, t.track });
  2667. break;
  2668. case RemoteAction::stopAllClips:
  2669. if (press)
  2670. engine.launcherCommand ({ launcher::Command::Type::stopAll });
  2671. break;
  2672. case RemoteAction::play:
  2673. if (press && ! engine.getTransport().playing.load())
  2674. playStop();
  2675. break;
  2676. case RemoteAction::stop:
  2677. if (press && engine.getTransport().playing.load())
  2678. playStop();
  2679. break;
  2680. case RemoteAction::record:
  2681. if (press)
  2682. runAction ("transport.record");
  2683. break;
  2684. case RemoteAction::sessionRecord:
  2685. if (press && clipGridView != nullptr)
  2686. engine.toggleSessionRecord (clipGridSelection (*clipGridView).second);
  2687. break;
  2688. case RemoteAction::metronome:
  2689. if (press)
  2690. runAction ("transport.metronome");
  2691. break;
  2692. // round 190kc: the crossfader's positions (measured in Live 12.4: a press goes there; holding one position and
  2693. // pressing / releasing another snaps back to the held one, Live manual 18.5)
  2694. case RemoteAction::crossfaderLeft:
  2695. case RemoteAction::crossfaderCentre:
  2696. case RemoteAction::crossfaderRight:
  2697. {
  2698. const auto spot = t.action == RemoteAction::crossfaderLeft ? crossfader::Spot::left
  2699. : t.action == RemoteAction::crossfaderRight ? crossfader::Spot::right : crossfader::Spot::centre;
  2700. float to = engine.getSong().crossfader;
  2701. if (press)
  2702. {
  2703. to = crossfader::spotPosition (spot);
  2704. heldCrossfaderSpots.push_back (t.action);
  2705. }
  2706. else
  2707. {
  2708. heldCrossfaderSpots.erase (std::remove (heldCrossfaderSpots.begin(), heldCrossfaderSpots.end(), t.action), heldCrossfaderSpots.end());
  2709. if (heldCrossfaderSpots.empty())
  2710. break;
  2711. const auto back = heldCrossfaderSpots.back(); // (snaps back to the position still held)
  2712. to = crossfader::spotPosition (back == RemoteAction::crossfaderLeft ? crossfader::Spot::left
  2713. : back == RemoteAction::crossfaderRight ? crossfader::Spot::right : crossfader::Spot::centre);
  2714. }
  2715. engine.editLevels ([to] (Song& s) { s.crossfader = to; }, false);
  2716. break;
  2717. }
  2718. // round 190kc: Live's Relative Session Mapping Strip
  2719. case RemoteAction::sceneUp:
  2720. case RemoteAction::sceneDown:
  2721. case RemoteAction::launchSelectedScene:
  2722. case RemoteAction::launchSelectedClip:
  2723. if (clipGridView != nullptr)
  2724. clipGridRelativeSession (*clipGridView, t.action, t.track, press);
  2725. break;
  2726. case RemoteAction::cancelLaunch:
  2727. if (press)
  2728. engine.launcherCommand ({ launcher::Command::Type::cancelLaunch });
  2729. break;
  2730. }
  2731. }
  2732. juce::String MainComponent::shortcutText (const char* actionId) const
  2733. {
  2734. const auto& chords = keyMap.chordsFor (actionId);
  2735. return chords.empty() ? juce::String() : "\t" + juce::String (keys::displayString (chords.front()));
  2736. }
  2737. void MainComponent::toggleTypingPiano()
  2738. {
  2739. setTypingPiano (! typingPiano);
  2740. // say what changed in the hint bar (issue #34: people did not find the typing piano; Ctrl+T gave no feedback)
  2741. ui::Hint hint;
  2742. hint.text = typingPiano ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  2743. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)");
  2744. ui::postHint (hint, 2500);
  2745. }
  2746. void MainComponent::setTypingPiano (bool on)
  2747. {
  2748. typingPiano = on;
  2749. EditorGlobals::get().typingPiano = on; // the editors' single-letter tool keys only work while it is off
  2750. typingPianoButton.setToggleState (on, juce::dontSendNotification);
  2751. typingPianoButton.setTooltip ((on ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  2752. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)"))
  2753. + juce::String (" (") + juce::String (keys::displayString (keyMap.chordsFor ("view.typingPiano").empty() ? keys::Chord {}
  2754. : keyMap.chordsFor ("view.typingPiano").front()))
  2755. + ")");
  2756. // release anything still sounding from the keyboard
  2757. heldKeys.releaseAll();
  2758. releaseTypingLaunches (true);
  2759. }
  2760. void MainComponent::loadKeyMap()
  2761. {
  2762. keyMap.resetToDefaults();
  2763. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  2764. if (file.existsAsFile())
  2765. {
  2766. std::vector<std::string> errors;
  2767. if (! keyMap.loadJson (file.loadFileAsString().toStdString(), &errors))
  2768. juce::Logger::writeToLog ("keys.json is not a JSON object; using the default keys");
  2769. for (const auto& e : errors)
  2770. juce::Logger::writeToLog ("keys.json: " + juce::String (e));
  2771. }
  2772. auto keyOf = [this] (const std::string& id) {
  2773. const auto& chords = keyMap.chordsFor (id);
  2774. return chords.empty() ? juce::String() : juce::String (keys::displayString (chords.front()));
  2775. };
  2776. pianoRoll.refreshToolKeys (keyOf);
  2777. playlist.refreshToolKeys (keyOf);
  2778. }
  2779. // --- Browsers ------------------------------------------------------------------------------------
  2780. // The main Browser and the separate Sample browser window (round 163) act on the project the same way.
  2781. void MainComponent::addFactoryItem (const std::string& key)
  2782. {
  2783. const auto* item = factorycontent::find (key);
  2784. if (item == nullptr)
  2785. return;
  2786. const auto& song = engine.getSong();
  2787. switch (item->kind)
  2788. {
  2789. case factorycontent::Kind::sound:
  2790. {
  2791. const auto& sounds = soundlib::builtIn();
  2792. if (item->index < 0 || item->index >= (int) sounds.size())
  2793. return;
  2794. auto channel = soundlib::channelFor (sounds[(std::size_t) item->index]);
  2795. if (! channel)
  2796. return;
  2797. if (simpleWorkflow != nullptr && layoutStyle == layoutstyle::Style::simple)
  2798. {
  2799. simpletracks::Request q;
  2800. q.kind = simpletracks::Kind::instrument;
  2801. q.name = item->name;
  2802. q.channel = std::move (channel);
  2803. simpleWorkflow->add (std::move (q));
  2804. }
  2805. else
  2806. {
  2807. rack.addChannel (std::move (*channel), true);
  2808. showPanel (Panel::channelRack);
  2809. }
  2810. return;
  2811. }
  2812. case factorycontent::Kind::beat:
  2813. {
  2814. const auto bar = juce::jmax<std::int64_t> (1, song.barTicks());
  2815. const auto fromBar = (int) ((std::int64_t) engine.songPlayheadTicks() / bar);
  2816. simpletracks::Result made;
  2817. engine.editSongStructural ([item, fromBar, &made] (Song& s) { made = factorycontent::addBeat (s, *item, fromBar); });
  2818. if (made.ok() && made.track >= 0)
  2819. playlist.selectTrack (made.track);
  2820. return;
  2821. }
  2822. case factorycontent::Kind::chain:
  2823. {
  2824. const auto track = playlist.getCurrentTrack();
  2825. const auto insert = track >= 0 ? detailchain::forTrack (song, track).insert : -1;
  2826. if (insert <= 0)
  2827. {
  2828. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("LYNX content"), tr ("Select a track first: the chain goes on its effects."));
  2829. return;
  2830. }
  2831. engine.editSongStructural ([item, insert] (Song& s) { factorycontent::applyChain (s, *item, insert); });
  2832. if (simpleWorkflow != nullptr && layoutStyle == layoutstyle::Style::simple)
  2833. simpleWorkflow->showEffectsOfInsert (insert);
  2834. return;
  2835. }
  2836. }
  2837. }
  2838. void MainComponent::connectBrowser (BrowserComponent& b)
  2839. {
  2840. b.onOpenProject = [this] (const juce::File& file) { confirmDiscard ([this, file] { openFile (file); }); };
  2841. b.onLoadIntoChannel = [this] (const juce::File& file) { return rack.loadSampleIntoSelected (file); };
  2842. b.onOpenMixerPreset = [this] (const juce::File& file) {
  2843. if (! mixerpresets::isMixerPreset (file))
  2844. return false;
  2845. if (! mixer.loadPresetOnSelection (file))
  2846. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Open mixer track state"),
  2847. tr ("This file is not a mixer track state LYNX SHARE can read."));
  2848. return true;
  2849. };
  2850. // the Browser's "Current project" items (REA_rodada115)
  2851. b.onOpenPattern = [this] (int pattern) {
  2852. selectPattern (pattern);
  2853. openPianoRoll();
  2854. };
  2855. b.onPatternMenu = [this] (int pattern) {
  2856. selectPattern (pattern);
  2857. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2858. };
  2859. b.onOpenChannel = [this] (int channel) {
  2860. engine.setSelectedChannel (channel);
  2861. rack.toggleEditor (channel, true);
  2862. };
  2863. b.onOpenEffect = [this] (int track, int slot) {
  2864. showPanel (Panel::mixer);
  2865. mixer.openSlotEditor (track, slot);
  2866. };
  2867. b.onShowInsert = [this] (int track) {
  2868. showPanel (Panel::mixer);
  2869. mixer.selectTrack (track);
  2870. };
  2871. b.onOpenAutomation = [this] (int automation) { openAutomationEditor (engine, automation); };
  2872. // the Browser's Plugin database (round 142): the same targets as the quick-add palette
  2873. b.onAddInstrument = [this] (ChannelDef c) {
  2874. if (PatcherWindows::takeInstrumentFromBrowser (c)) // a Patcher's Add plugin › Browse plugin database (round 162)
  2875. return;
  2876. rack.addChannel (std::move (c), true);
  2877. showPanel (Panel::channelRack);
  2878. };
  2879. b.onAddEffect = [this] (EffectSlot slot) {
  2880. if (PatcherWindows::takeEffectFromBrowser (slot))
  2881. return;
  2882. if (! mixer.addEffectToSelected (std::move (slot)))
  2883. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  2884. tr ("The selected insert has no free effect slot."));
  2885. else
  2886. showPanel (Panel::mixer);
  2887. };
  2888. // round 190ke (owner decision D2): "LYNX content" in the Simple layout: a sound becomes an instrument track, a beat a
  2889. // Drums track at the playhead, an effect chain goes on the selected track
  2890. b.onFactoryItem = [this] (const std::string& key) { addFactoryItem (key); };
  2891. b.onPreviewVolumeChanged = [this] { saveUiSettings(); };
  2892. if (b.getRole() == BrowserComponent::Role::main) // round 190mv (DF-107): FL's Browser › View › Auto-hide
  2893. b.onAutoHideChanged = [this] {
  2894. workspace.setBrowserAutoHide (BrowserComponent::autoHide);
  2895. saveUiSettings();
  2896. };
  2897. // round 190ce: hot-swap (the main Browser only: it is the one the device buttons and the key link)
  2898. b.onHotSwapChanged = [this] {
  2899. if (detailView != nullptr)
  2900. detailView->hotSwapChanged();
  2901. };
  2902. b.onHotSwapWillReplaceInstrument = [this] (int channel) { rack.closeEditorForHotSwap (channel); };
  2903. if (b.getRole() == BrowserComponent::Role::main)
  2904. EffectsPanel::onHotSwapSlot = [this] (int track, int slot) { toggleHotSwap (hotswap::targetOfEffect (engine.getSong(), track, slot)); };
  2905. b.onHotSwapSample = [this] (int channel, const juce::File& file) { rack.assignSampleForHotSwap (channel, file); };
  2906. b.onSendToPlaylist = [this] (const juce::File& file) {
  2907. playlist.addAudioClipAtPlayhead (file);
  2908. showPanel (Panel::playlist);
  2909. };
  2910. b.onToggleSampleBrowser = [this] { toggleSampleBrowser(); };
  2911. }
  2912. void MainComponent::toggleSampleBrowser()
  2913. {
  2914. if (auto* w = findToolWindow ("sampleBrowser"))
  2915. {
  2916. w->closeButtonPressed(); // (hidden, then deleted: remembered as closed)
  2917. return;
  2918. }
  2919. openSampleBrowser();
  2920. }
  2921. void MainComponent::openSampleBrowser()
  2922. {
  2923. auto* window = openToolWindow (BrowserComponent::makeSampleBrowserContent (engine, [this] (BrowserComponent& b) { connectBrowser (b); }),
  2924. tr ("Sample browser"), "sampleBrowser");
  2925. if (window == nullptr)
  2926. return;
  2927. window->setResizable (true, false);
  2928. window->setResizeLimits (240, 260, 4000, 4000);
  2929. const auto saved = BrowserComponent::sampleBrowserBounds();
  2930. const auto area = juce::Desktop::getInstance().getDisplays().getTotalBounds (true);
  2931. if (saved.getWidth() >= 240 && saved.getHeight() >= 260 && area.intersects (saved))
  2932. window->setBounds (saved);
  2933. else if (auto* top = getTopLevelComponent())
  2934. window->setBounds (top->getScreenBounds().getRight() - 360, top->getScreenY() + 80, 340, juce::jmax (400, top->getHeight() - 160));
  2935. }
  2936. // --- UI options ----------------------------------------------------------------------------------
  2937. juce::File MainComponent::uiSettingsFile() const
  2938. {
  2939. return PluginHost::settingsFolder().getChildFile ("ui-options.txt");
  2940. }
  2941. void MainComponent::loadUiSettings()
  2942. {
  2943. juce::StringArray lines;
  2944. lines.addLines (uiSettingsFile().loadFileAsString());
  2945. // the sound in FL's order (0.1.20) wins over the old key, wherever each line is
  2946. const auto flMetronomeSound = std::any_of (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("metronomeSoundFl"); });
  2947. // "Blend recorded notes" (round 177c): see startingRecordMode() for who starts with what
  2948. {
  2949. const auto saved = std::find_if (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("recordBlend="); });
  2950. auto o = engine.getRecordOptions();
  2951. o.mode = startingRecordMode (uiSettingsFile().existsAsFile(), saved != lines.end(),
  2952. saved != lines.end() && saved->fromFirstOccurrenceOf ("=", false, false).trim() == "1");
  2953. o.countInBars = countin::startingBars (uiSettingsFile().existsAsFile()); // (issue #152; saved keys below win)
  2954. engine.setRecordOptions (o);
  2955. }
  2956. undokeys::SettingsReader undoSetting; // "Alternate undo mode" (round 190mz: two keys, read in any order)
  2957. for (const auto& line : lines)
  2958. {
  2959. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  2960. const auto on = line.fromFirstOccurrenceOf ("=", false, false).trim() == "1";
  2961. if (key == "typingPiano")
  2962. typingPiano = on;
  2963. else if (key == "typingOctave")
  2964. typingOctave = keys::typingpiano::clampOctave (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2965. else if (key == "typingRoot")
  2966. typingRoot = keys::typingpiano::clampRoot (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2967. else if (key == "typingLayout") // FL's layout name, so the list can grow
  2968. typingLayout = keys::typingpiano::layoutIndex (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2969. else if (key == "keepEditorsOpen")
  2970. ChannelRackComponent::keepEditorsOpen = on;
  2971. else if (key == "selFirstChanPatChanges")
  2972. ChannelRackComponent::selectFirstChannelWithNotes = on;
  2973. else if (key == "prPaintMode") // FL's PRPaintMode (round 189o)
  2974. PianoRollComponent::monophonicPainting = on;
  2975. else if (key == "extendedHint") // round 190mr (DF-49): FL's Extended Hint Panel and its place
  2976. showExtendedHintAfterLoad = on;
  2977. else if (key == "extendedHintAt")
  2978. {
  2979. const auto xy = juce::StringArray::fromTokens (line.fromFirstOccurrenceOf ("=", false, false), ",", {});
  2980. if (xy.size() == 2)
  2981. extendedHintOffset = { xy[0].getIntValue(), xy[1].getIntValue() };
  2982. }
  2983. else if (key == "altMeterScale") // round 190lx (DF-61): FL's "Alternate meter scale"
  2984. meterscale::alternate() = on;
  2985. else if (key == "prPreviewPlaying") // issue #183: the Piano roll's "Preview notes while playing" (off)
  2986. PianoRollComponent::previewWhilePlaying = on;
  2987. else if (key == "limitEditors") // FL's LimitEditors (round 189o; on unless saved off)
  2988. editorlimit::enabled() = on;
  2989. else if (key == "sampleAccurateAutomation") // round 190jg (core/Instruments.h; on unless saved off)
  2990. setSampleAccurateAutomation (on);
  2991. else if (key == "detachNewPlugins") // FL's General › "Detach all new plugins" (issue #116)
  2992. {
  2993. engine.setDetachNewPlugins (on);
  2994. setEditorsDetached (on); // (round 190ev: LYNX's own editor windows follow FL's option too)
  2995. }
  2996. else if (key == "autoSelectLinked")
  2997. ChannelRackComponent::autoSelectLinked = on;
  2998. else if (key == "editorsInMain") // round 190jy: Settings › General › Draw docked LYNX editors in the main window
  2999. setEditorsInMainWindow (on);
  3000. else if (key == "muteRemovedSteps")
  3001. ChannelRackComponent::muteRemovedSteps = on;
  3002. else if (key == "rackMixerSelectors") // round 190ld
  3003. ChannelRackComponent::showMixerSelectors = on;
  3004. else if (key == "rackNameAlignLeft") // round 190kd: FL's Channel name alignment
  3005. ChannelRackComponent::nameAlignLeft = on;
  3006. else if (key == "rackPreviewMute") // round 190mk (DE-33): FL's "Show a mute button on the piano roll preview"
  3007. ChannelRackComponent::previewMuteButton = on;
  3008. else if (key == "rackButtonWidth") // round 190mk (DE-39): FL's Channel button width (0 = size to fit)
  3009. rack.setButtonWidth (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3010. else if (key == "audioTrackControls") // round 190w: Playlist › View › Track headers
  3011. PlaylistComponent::showAudioTrackControls = on;
  3012. else if (key == "audioTrackLevels")
  3013. PlaylistComponent::showAudioTrackLevels = on;
  3014. else if (key == "instrumentTrackLevels")
  3015. PlaylistComponent::showInstrumentTrackLevels = on;
  3016. else if (key == "hideCollapsedGroups") // round 190jf: Playlist › View › Hide collapsed grouped tracks
  3017. PlaylistComponent::hideCollapsedGroups = on;
  3018. else if (key == "automationLanes") // round 177b: Playlist › Automation lanes
  3019. autolanes::setShown (on);
  3020. else if (key == "trackInserts") // round 190ht (issue #154): Playlist › Edit › Show insert effects on linked tracks
  3021. PlaylistComponent::showTrackInserts = on;
  3022. else if (workflowextras::readUiOption (key, on)) // round 190iu (issues #186, #191)
  3023. {
  3024. }
  3025. else if (workflowextras::readUiValue (key, line.fromFirstOccurrenceOf ("=", false, false).trim())) // round 190jq (#164)
  3026. {
  3027. }
  3028. else if (key == "pickerPanel") // issue #175: FL's Playlist menu › Picker panel › Enable
  3029. {
  3030. pickerPanelOn = on;
  3031. playlistArea.setPickerHidden (layoutStyle == layoutstyle::Style::simple || ! pickerPanelOn);
  3032. }
  3033. else if (key == "alternateUndo") // (rounds 167k-190b; round 190mz: an old 0 was the old default)
  3034. undoSetting.legacyKey (on);
  3035. else if (key == "alternateUndoMode") // round 190mz
  3036. undoSetting.currentKey (on);
  3037. else if (key == "waveSpectral") // ("waveColours", the old spectral-by-default key, is ignored)
  3038. ui::WaveformCache::spectral = on;
  3039. else if (key == "pluginStyle") // "Automatic" or a style forced on every plugin
  3040. {
  3041. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim();
  3042. skin::setForcedStyle (v.equalsIgnoreCase ("Automatic") || v.isEmpty() ? -1 : (int) skin::styleFromName (v));
  3043. }
  3044. else if (key == "pluginStyleOverrides")
  3045. skin::overridesFromString (line.fromFirstOccurrenceOf ("=", false, false).trim());
  3046. else if (key == "reducedEffects")
  3047. skin::setReducedEffects (on);
  3048. else if (key == "animationRate") // round 174e2: 0 = the display's refresh, else 60 / 30; -1 = Balanced (round 190ip)
  3049. {
  3050. const auto hz = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  3051. ui::FrameTicker::rateLimit() = hz == 30 || hz == 60 || hz == -1 ? hz : 0;
  3052. }
  3053. else if (key == "uiAnimations") // round 179a (ui/Motion.h)
  3054. ui::motion::enabled() = on;
  3055. else if (key == "artMotion")
  3056. skin::setArtMotion (on);
  3057. else if (key == "waveStereo")
  3058. ui::WaveformCache::stereo = on;
  3059. else if (key == "samplerSpectrumView") // round 190gw: the Sampler waveform menu's view switches
  3060. samplerpage::waveViews().spectrum = on;
  3061. else if (key == "samplerMultichannelView")
  3062. samplerpage::waveViews().multichannel = on;
  3063. else if (key == "noteNames")
  3064. notenames::currentStyle.store (juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  3065. else if (key == "noteFlats")
  3066. notenames::currentFlats.store (on);
  3067. else if (key == "pianoRollEveryKeyName") // (round 190jo: a new name, so the FL default reaches everybody once)
  3068. notenames::everyKey.store (on);
  3069. else if (key == "rackPlayheadColumn")
  3070. ChannelRackComponent::playheadColumn.store (on);
  3071. else if (key == "rackStepsChannelColour")
  3072. ChannelRackComponent::stepsChannelColour.store (on);
  3073. else if (key == "rackCompletePreview")
  3074. ChannelRackComponent::completePreview.store (on);
  3075. else if (key == "rememberSeekTime") // (issue #169: the old "rememberSeek" key held LYNX's old default, off; FL's is on)
  3076. EditorGlobals::get().rememberSeek = on;
  3077. else if (key == "createVariants")
  3078. EditorGlobals::get().createVariants = on;
  3079. else if (key == "plLeftResizing") // round 189g: FL's Playlist Edit / Select options
  3080. EditorGlobals::get().leftResizing = on;
  3081. else if (key == "plWheelNudging")
  3082. EditorGlobals::get().wheelNudging = on;
  3083. else if (key == "plManualFades")
  3084. EditorGlobals::get().manualFades = on;
  3085. else if (key == "plSnapFadeHandles")
  3086. EditorGlobals::get().snapFadeHandles = on;
  3087. else if (key == "plAutomationFollowsClips") // round 190cg (absent = as the layout)
  3088. EditorGlobals::get().automationFollowsClips = on ? 1 : 0;
  3089. else if (key == "followPausesOnEdit") // round 190im (absent = as the layout)
  3090. EditorGlobals::get().followPausesOnEdit = on ? 1 : 0;
  3091. else if (key == "plMagicLasso")
  3092. EditorGlobals::get().magicLasso = on;
  3093. else if (key == "prMagicLasso") // (round 190mp, DE-71)
  3094. EditorGlobals::get().pianoRollMagicLasso = on;
  3095. else if (key == "dropAudioOnHeaders") // round 189e: FL's Edit › Drop audio on track headers (DropAudioToPLMode)
  3096. {
  3097. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  3098. trackmodes::headerDropOptions().mode = v == 256 || v == 257 || v == 258 ? (trackmodes::HeaderDrop) v : trackmodes::HeaderDrop::ask;
  3099. }
  3100. else if (key == "dropLocksToContent")
  3101. trackmodes::headerDropOptions().lockToContent = on;
  3102. else if (key == "selectTracksOnDrop")
  3103. trackmodes::headerDropOptions().selectTracks = on;
  3104. else if (key == "prGridHighlights") // (round 168g: the Piano roll's View items)
  3105. PianoRollComponent::gridHighlights = on;
  3106. else if (key == "prBlackKeyRows") // (round 190mq: Scale highlighting › Black notes / Default)
  3107. PianoRollComponent::blackKeyRows = on;
  3108. else if (key == "prShowChordName")
  3109. PianoRollComponent::showChordName = on;
  3110. else if (key == "prSongBars")
  3111. PianoRollComponent::songBarsRuler = on;
  3112. else if (key == "polyPrepareOnOpen") // (round 190lo: a LYNX extra, ui/PolyEditor.h)
  3113. PolyEditorWindows::prepareOnOpen = on;
  3114. else if (key == "prKeyStyle") // (round 190j: 0 = flat, FL's; 1 = piano keys)
  3115. PianoRollComponent::keyStyle = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue() == 1 ? pianokeys::Style::piano
  3116. : pianokeys::Style::flat;
  3117. else if (key == "audioLogEnabled")
  3118. engine.getRollingLog().setEnabled (on);
  3119. else if (key == "audioLogSeconds")
  3120. {
  3121. const auto seconds = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  3122. if (seconds == 60 || seconds == 120 || seconds == 300 || seconds == 600)
  3123. engine.getRollingLog().setLengthSeconds (seconds);
  3124. }
  3125. else if (key == "audioLogPreEffects")
  3126. engine.getRollingLog().setPosition (on ? RollingAudioLog::Position::preEffects : RollingAudioLog::Position::postEffects);
  3127. else if (key == "chordDelayMs")
  3128. chordReadout.setDelayMs ((std::uint32_t) line.fromFirstOccurrenceOf ("=", false, false).trim().getLargeIntValue());
  3129. else if (key == "chordRoman")
  3130. {
  3131. auto o = chordReadout.getOptions();
  3132. o.roman = on;
  3133. chordReadout.setOptions (o);
  3134. }
  3135. else if (key == "chordNearHint")
  3136. chordShowNearHint = on;
  3137. else if (key == "keyPanelFollowsStyle")
  3138. keyPanelFollowsStyle = on;
  3139. else if (key == "linkToggleFollowsStyle")
  3140. linkToggleFollowsStyle = on;
  3141. else if (key == "stretchedClipsLoop")
  3142. setStretchedClipsLoop (on);
  3143. else if (key == "autoClipsAtPlayback")
  3144. autoclipplace::setAtPlayback (on);
  3145. else if (key == "disableTypingPriority")
  3146. pluginkeys::newPluginsHostFirst() = on;
  3147. else if (key == "clipLaunchWorkflow") // (round 181a; applied when the window is ready; "layoutStyle" wins)
  3148. startStyle.legacyFlag (on);
  3149. else if (key == "layoutStyle") // (round 184a)
  3150. startStyle.styleId (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  3151. else if (key == "lanesBeforeClipLaunch")
  3152. lanesBeforeClipLaunch = on;
  3153. else if (key == "detailHeight") // round 183a: the Clip-launch workflow's detail view
  3154. DetailView::preferredHeight = juce::jlimit (DetailView::minHeight, 2000, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3155. else if (key == "detailShown")
  3156. DetailView::shownSetting = on;
  3157. else if (key == "sessionButtonRow") // round 190iv: the clip grid's footer row in the Clip-launch layout (an option)
  3158. sessionButtonRowShown = on;
  3159. else if (key == "sceneTempoShown") // round 190ef: the clip grid's scene tempo / time signature fields
  3160. clipGridSceneTempoShown() = on;
  3161. else if (key == "sceneSelectNext") // round 190ld: Live's scene-launch preferences
  3162. clipGridSelectNextOnLaunch() = on;
  3163. else if (key == "sceneRecordOnLaunch")
  3164. clipGridRecordOnSceneLaunch() = on;
  3165. else if (key == "clipGridClassicLook") // round 190ig: the clip grid without Live's look
  3166. clipGridClassicLook() = on;
  3167. else if (key == "tallLiveLanes") // round 190jn: the Arrangement's 38 px lanes in Live's look (19 px by default)
  3168. playlistTallLiveLanes() = on;
  3169. else if (key == "infoViewShown") // round 190jn: Live's Info View in the detail view
  3170. DetailView::infoViewShown = on;
  3171. else if (key == "simpleDockHeight") // round 190bu: the Simple workflow's track dock
  3172. SimpleDock::preferredHeight = juce::jlimit (SimpleDock::minHeight, 2000, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3173. else if (key == "simpleDockShown")
  3174. SimpleDock::shownSetting = on;
  3175. else if (key == "keyboardMode") // round 190ds: the keyboards' modes (core/ScaleKeys.h)
  3176. scalekeys::current().mode = (scalekeys::Mode) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3177. else if (key == "keyboardLock")
  3178. scalekeys::current().lockToKey = on;
  3179. else if (key == "chordComplexity")
  3180. scalekeys::current().complexity = (scalekeys::Complexity) juce::jlimit (0, scalekeys::complexityCount - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3181. else if (key == "chordSpread")
  3182. scalekeys::current().spread = (scalekeys::Spread) juce::jlimit (0, scalekeys::spreadCount - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3183. else if (key == "chordStrum")
  3184. scalekeys::current().strumMs = juce::jlimit (0, scalekeys::maxStrumMs, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3185. else if (key == "chordStrumDown")
  3186. scalekeys::current().strumDown = on;
  3187. else if (key == "chordProjectSet")
  3188. scalekeys::current().projectChords = on;
  3189. else if (key == "detailDevices")
  3190. DetailView::devicesPage = on;
  3191. else if (key == "detailExtraWindowKey")
  3192. DetailView::extraWindowKey = on;
  3193. else if (key == "detailExtraSelectInMixer")
  3194. DetailView::extraSelectInMixer = on;
  3195. else if (key == "alsSessionOnPlaylist")
  3196. AudioEngine::alsSessionOnPlaylist = on;
  3197. else if (key == "simpleLargeControls") // round 190jc: View › Large controls (Simple layout)
  3198. ui::simplelook::largeControls() = on;
  3199. else if (key == "followPlaylist" || key == "followPianoRoll")
  3200. EditorGlobals::get().setFollowing (key == "followPianoRoll", on, false);
  3201. else if (key == "followChannelRack" || key == "followAudioEditor")
  3202. EditorGlobals::get().setFollowingView (key == "followChannelRack" ? EditorGlobals::FollowView::channelRack
  3203. : EditorGlobals::FollowView::audioEditor, on, false);
  3204. else if (key == "cpuRefresh") // round 190kn
  3205. toolbar::PerformanceMeter::refresh = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3206. else if (key == "cpuView") // round 190ld: FL's View voice count / View FPS
  3207. toolbar::PerformanceMeter::secondView = juce::jlimit (0, 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3208. else if (key == "scopeStereo") // FL's output panel › Oscilloscope › Stereo (round 190mv)
  3209. toolbar::OutputMonitor::stereoScope = on;
  3210. else if (key == "scopeMode")
  3211. toolbar::OutputMonitor::mode = juce::jlimit (0, toolbar::OutputMonitor::modeCount - 1,
  3212. line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3213. else if (key == "toolbarGroups")
  3214. toolbarLayout.orderFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  3215. else if (key == "toolbarIcons")
  3216. toolbarLayout.iconSize = toolbarlayout::Layout::iconSizeFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  3217. else if (key == "toolbarSeparators")
  3218. toolbarLayout.separators = on;
  3219. else if (key == "toolbarVisible")
  3220. toolbarLayout.visible = on;
  3221. else if (key == "menuDensity")
  3222. theme::menus::setCompact (line.fromFirstOccurrenceOf ("=", false, false).trim() != "comfortable");
  3223. else if (key == "uiScale")
  3224. toolbarLayout.uiScale = toolbarlayout::clampScale (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3225. else if (key == "editPatternsIn")
  3226. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3227. else if (key == "autosaveMinutes")
  3228. autosaveMinutes = prefs::clampAutosaveMinutes (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3229. else if (key == "askUnusedRecordings")
  3230. askUnusedRecordings = on;
  3231. else if (key == "messagesHidden") // FL's "Manage messages" (round 186c)
  3232. messages::setHiddenList (line.fromFirstOccurrenceOf ("=", false, false).trim());
  3233. else if (key == "backupWaitsForQuiet")
  3234. backupWaitsForQuiet = on;
  3235. else if (key == "backupLongestWait")
  3236. backupLongestWaitMinutes = prefs::clampBackupLongestWait (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3237. else if (key == "hoverValues")
  3238. hoverValues = on;
  3239. else if (key == "autosaveKeep")
  3240. autosaveKeep = prefs::clampAutosaveKeep (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3241. else if (key == "metronomeSound" && ! flMetronomeSound) // (before 0.1.20: 0 LYNX click, 1..5 hi-hat..pulse)
  3242. engine.getTransport().metronomeSound.store (metronome::soundFromLegacy (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  3243. else if (key == "tapStartsPlayback") // round 190lr (DL-49)
  3244. tapStartsPlayback = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue() != 0;
  3245. else if (key == "metronomeOnlyRec") // round 190lr (DL-47)
  3246. engine.getTransport().metronomeOnlyRecording.store (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue() != 0);
  3247. else if (key == "metronomeSoundFl") // FL's order: 0 Hi-hat, 1 Tick, 2 Beep, 3 Cowbell, 4 Pulse
  3248. engine.getTransport().metronomeSound.store (metronome::clampSound (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  3249. // FL's Settings options of round 190bx (core/FlSettings.h: resampling quality, CPU switches, auto close...)
  3250. else if (flsettings::parse (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString()))
  3251. {
  3252. }
  3253. else if (key == "renderAhead") // (round 190gq: Options › Audio settings › "Render ahead", on by default)
  3254. renderAheadOption().store (line.fromFirstOccurrenceOf ("=", false, false).trim() != "0");
  3255. else if (key == "metronomeTrack")
  3256. engine.getTransport().metronomeTrack.store (juce::jlimit (0, maxMixerTracks - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  3257. else if (key == "playTruncatedOnTransport")
  3258. engine.getTransport().playTruncatedOnTransport.store (on);
  3259. else if (key == "resetPluginsOnTransport")
  3260. engine.getTransport().resetPluginsOnTransport.store (on);
  3261. else if (key == "metronomeVolume")
  3262. engine.getTransport().metronomeVolume.store ((float) controls::clampUtilityVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue()));
  3263. else if (key == "previewVolume")
  3264. engine.setPreviewVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  3265. else if (key == "previewInTime") // the Browser's "Preview in time" (round 190aq)
  3266. engine.setPreviewInTime (on);
  3267. else if (key == "browserAutoPreview") // the Browser's "Preview files when they are selected" (round 190ce)
  3268. BrowserComponent::autoPreview = on;
  3269. else if (key == "browserAutoHide") // the Browser's "Auto-hide" (round 190mv, DF-107)
  3270. {
  3271. BrowserComponent::autoHide = on;
  3272. workspace.setBrowserAutoHide (on);
  3273. }
  3274. else if (key == "editorVolume")
  3275. engine.setEditorVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  3276. else if (key == "rackPianoRollView")
  3277. rack.setPianoRollView (on);
  3278. else if (key == "undoLevels")
  3279. engine.setUndoLevels (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3280. else if (key == "askWhatToRecord" || key == "recordNotes" || key == "recordAudio" || key == "recordStartsPlayback" || key == "disarmOnStop"
  3281. || key == "recordOffOnStop" || key == "unarmAfterRender" || key == "renderAutoClip" || key == "lowLatencyRecording"
  3282. || key == "recLatencyCompensation")
  3283. {
  3284. auto o = engine.getRecordOptions();
  3285. (key == "askWhatToRecord" ? o.askWhatToRecord : key == "recordNotes" ? o.recordNotes : key == "recordAudio" ? o.recordAudio
  3286. : key == "lowLatencyRecording" ? o.lowLatencyRecording : key == "recLatencyCompensation" ? o.latencyCompensation
  3287. : key == "disarmOnStop" ? o.disarmOnStop : key == "recordOffOnStop" ? o.recordOffOnStop : key == "unarmAfterRender" ? o.unarmAfterRender
  3288. : key == "renderAutoClip" ? o.autoCreateClip
  3289. : o.startsPlayback) = on;
  3290. engine.setRecordOptions (o);
  3291. }
  3292. else if (key == "recordAutomation" || key == "recordQuantiseAutomation" || key == "recordClips")
  3293. {
  3294. auto o = engine.getRecordOptions();
  3295. (key == "recordAutomation" ? o.recordAutomation : key == "recordClips" ? o.recordClips : o.quantiseAutomation) = on;
  3296. engine.setRecordOptions (o);
  3297. }
  3298. else if (key == "recordToStepSequencer" || key == "recordingMarkers" || key == "recordNoteEnd")
  3299. {
  3300. auto o = engine.getRecordOptions();
  3301. if (key == "recordNoteEnd")
  3302. o.noteEnd = (NoteEnd) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  3303. else
  3304. (key == "recordToStepSequencer" ? o.toStepSequencer : o.recordingMarkers) = on;
  3305. engine.setRecordOptions (o);
  3306. }
  3307. else if (key == "recordCatchWindow" || key == "recordCompensateOutput") // (round 170d)
  3308. {
  3309. auto o = engine.getRecordOptions();
  3310. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getLargeIntValue();
  3311. if (key == "recordCatchWindow")
  3312. o.catchWindow = juce::jlimit<std::int64_t> (0, ppq, v);
  3313. else
  3314. o.compensateOutput = v != 0;
  3315. engine.setRecordOptions (o);
  3316. }
  3317. else if (key == "recordPunchLoop" || key == "recordPunchEnds" || key == "recordPreRoll" || key == "recordPostRoll" || key == "recordLoop" || key == "recordLastPassPlays"
  3318. || key == "waitOnlyWhenRecording" || key == "waitRespectFilter")
  3319. {
  3320. auto o = engine.getRecordOptions();
  3321. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  3322. if (key == "waitOnlyWhenRecording") // round 190ld
  3323. o.waitOnlyWhenRecording = v != 0;
  3324. else if (key == "waitRespectFilter")
  3325. o.waitRespectFilter = v != 0;
  3326. else if (key == "recordPunchLoop")
  3327. o.punchLoopRegion = v != 0;
  3328. else if (key == "recordPunchEnds") // round 190lx (DL-61): 1 = in, 2 = out (none: both, the one switch's punch)
  3329. o.punchIn = (v & 1) != 0 || (v & 3) == 0, o.punchOut = (v & 2) != 0 || (v & 3) == 0;
  3330. else if (key == "recordLoop")
  3331. o.loopRecord = v != 0;
  3332. else if (key == "recordLastPassPlays")
  3333. o.lastLoopPassPlays = v != 0;
  3334. else
  3335. (key == "recordPreRoll" ? o.preRollBars : o.postRollBars) = juce::jlimit (0, 8, v);
  3336. engine.setRecordOptions (o);
  3337. }
  3338. else if (key == juce::String (countin::onKey.data()) || key == juce::String (countin::lengthKey.data())) // (issue #152)
  3339. {
  3340. auto o = engine.getRecordOptions();
  3341. countin::readSetting (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue(), o.countInBars, o.countInLength);
  3342. engine.setRecordOptions (o);
  3343. refreshRecordOptionButtons();
  3344. }
  3345. else if (key == "metronomeOn") // (issue #152)
  3346. {
  3347. engine.getTransport().metronome.store (on);
  3348. refreshModeButton();
  3349. }
  3350. else if (key == "recordQuantiseStarts")
  3351. {
  3352. recordQuantiseOn = on;
  3353. updateRecordQuantise();
  3354. }
  3355. else if (NewProjectDefaults::ownsKey (key.toStdString())) // (issue #170: newLinkTracks was missing from this list)
  3356. newProjectDefaults().readKey (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  3357. else if (key == "mixerWaveforms") // round 190lr (DF-60)
  3358. MixerStrips::meterWaveforms = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue() != 0;
  3359. else if (key == "mixerUsedOnly")
  3360. MixerStrips::showUsedOnly = on;
  3361. else if (key == "mixerLoudness") // round 190am (also starts the measurement)
  3362. mixer.getStripsForSnapshot().setShowLoudness (on);
  3363. else if (key == "grossBeatFlLocator") // round 190jd: Gross Beat's locator in FL's colours
  3364. gblocator::setFlStyle (on);
  3365. else if (key == "mixerStripInserts") // round 190io (issue #154 part 2)
  3366. mixer.getStripsForSnapshot().setShowStripInserts (on);
  3367. else if (key == "mixerKeepLostLinks")
  3368. MixerStrips::keepLostLinks = on;
  3369. else if (key == "mixerFollowPlaylist")
  3370. MixerStrips::followPlaylist = on;
  3371. else if (key == "mixerLayout") // FL's FXViewMode numbering (issue #52)
  3372. {
  3373. MixerStrips::layout = mixerlayout::parse (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  3374. mixer.getStripsForSnapshot().updateSize();
  3375. }
  3376. else if (key == "quantizeSongJumps")
  3377. engine.quantizeSongJumps.store (juce::jlimit (0, 5, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  3378. }
  3379. alternateUndo = undoSetting.alternate;
  3380. startup = StartupOptions::load();
  3381. browser.refreshPreviewVolume();
  3382. }
  3383. void MainComponent::saveUiSettings()
  3384. {
  3385. if (! persistent)
  3386. return;
  3387. uiSettingsFile().replaceWithText ("typingPiano=" + juce::String (typingPiano ? 1 : 0) + "\ntypingOctave=" + juce::String (typingOctave)
  3388. + "\ntypingRoot=" + juce::String (typingRoot)
  3389. + "\ntypingLayout=" + juce::String (keys::typingpiano::layoutName (typingLayout)) + "\nkeepEditorsOpen="
  3390. + juce::String (ChannelRackComponent::keepEditorsOpen ? 1 : 0)
  3391. + "\nselFirstChanPatChanges=" + juce::String (ChannelRackComponent::selectFirstChannelWithNotes ? 1 : 0)
  3392. + "\nprPaintMode=" + juce::String (PianoRollComponent::monophonicPainting ? 1 : 0)
  3393. + "\naltMeterScale=" + juce::String (meterscale::alternate() ? 1 : 0)
  3394. + "\nprPreviewPlaying=" + juce::String (PianoRollComponent::previewWhilePlaying ? 1 : 0)
  3395. + "\nlimitEditors=" + juce::String (editorlimit::enabled() ? 1 : 0)
  3396. + "\nsampleAccurateAutomation=" + juce::String (sampleAccurateAutomation() ? 1 : 0)
  3397. + "\ndetachNewPlugins=" + juce::String (engine.detachesNewPlugins() ? 1 : 0)
  3398. + "\nautoSelectLinked=" + juce::String (ChannelRackComponent::autoSelectLinked ? 1 : 0)
  3399. + "\nextendedHint=" + juce::String (extendedHint != nullptr ? 1 : 0)
  3400. + "\nextendedHintAt=" + juce::String (extendedHintOffset.x) + "," + juce::String (extendedHintOffset.y)
  3401. + "\neditorsInMain=" + juce::String (editorsInMainWindowSetting() ? 1 : 0)
  3402. + "\nmuteRemovedSteps=" + juce::String (ChannelRackComponent::muteRemovedSteps ? 1 : 0)
  3403. + "\nrackMixerSelectors=" + juce::String (ChannelRackComponent::showMixerSelectors ? 1 : 0)
  3404. + "\nrackNameAlignLeft=" + juce::String (ChannelRackComponent::nameAlignLeft ? 1 : 0)
  3405. + "\nrackButtonWidth=" + juce::String (ChannelRackComponent::buttonWidthPercent)
  3406. + "\nrackPreviewMute=" + juce::String (ChannelRackComponent::previewMuteButton ? 1 : 0)
  3407. + "\naudioTrackControls=" + juce::String (PlaylistComponent::showAudioTrackControls ? 1 : 0)
  3408. + "\naudioTrackLevels=" + juce::String (PlaylistComponent::showAudioTrackLevels ? 1 : 0)
  3409. + "\ninstrumentTrackLevels=" + juce::String (PlaylistComponent::showInstrumentTrackLevels ? 1 : 0)
  3410. + "\nhideCollapsedGroups=" + juce::String (PlaylistComponent::hideCollapsedGroups ? 1 : 0)
  3411. + "\nautomationLanes=" + juce::String (autolanes::shown() ? 1 : 0)
  3412. + "\ntrackInserts=" + juce::String (PlaylistComponent::showTrackInserts ? 1 : 0)
  3413. + workflowextras::uiOptionsText() // round 190iu
  3414. + "\npickerPanel=" + juce::String (pickerPanelOn ? 1 : 0)
  3415. + "\nalternateUndo=" + juce::String (alternateUndo ? 1 : 0) // (read by older versions)
  3416. + "\nalternateUndoMode=" + juce::String (alternateUndo ? 1 : 0)
  3417. + "\neditPatternsIn="
  3418. + juce::String (PlaylistComponent::editPatternsIn) + "\nsplash=" + juce::String (startup.splash ? 1 : 0)
  3419. + "\nstartupSound=" + juce::String (startup.sound ? 1 : 0)
  3420. + "\nwaveSpectral=" + juce::String (ui::WaveformCache::spectral ? 1 : 0)
  3421. + "\nwaveStereo=" + juce::String (ui::WaveformCache::stereo ? 1 : 0)
  3422. + "\nsamplerSpectrumView=" + juce::String (samplerpage::waveViews().spectrum ? 1 : 0)
  3423. + "\nsamplerMultichannelView=" + juce::String (samplerpage::waveViews().multichannel ? 1 : 0)
  3424. + "\nnoteNames=" + juce::String (notenames::currentStyle.load())
  3425. + "\nnoteFlats=" + juce::String (notenames::currentFlats.load() ? 1 : 0)
  3426. + "\npianoRollEveryKeyName=" + juce::String (notenames::everyKey.load() ? 1 : 0)
  3427. + "\nrackPlayheadColumn=" + juce::String (ChannelRackComponent::playheadColumn.load() ? 1 : 0)
  3428. + "\nrackStepsChannelColour=" + juce::String (ChannelRackComponent::stepsChannelColour.load() ? 1 : 0)
  3429. + "\nrackCompletePreview=" + juce::String (ChannelRackComponent::completePreview.load() ? 1 : 0)
  3430. + "\nreducedEffects=" + juce::String (skin::reducedEffects() ? 1 : 0)
  3431. + "\nanimationRate=" + juce::String (ui::FrameTicker::rateLimit())
  3432. + "\nuiAnimations=" + juce::String (ui::motion::enabled() ? 1 : 0)
  3433. + "\nartMotion=" + juce::String (skin::artMotion() ? 1 : 0)
  3434. + "\npluginStyle=" + juce::String (skin::forcedStyle() < 0 ? "Automatic" : skin::styleName ((skin::Style) skin::forcedStyle()))
  3435. + "\npluginStyleOverrides=" + skin::overridesToString()
  3436. + "\nrememberSeekTime=" + juce::String (EditorGlobals::get().rememberSeek ? 1 : 0)
  3437. + "\ncreateVariants=" + juce::String (EditorGlobals::get().createVariants ? 1 : 0)
  3438. + "\nplLeftResizing=" + juce::String (EditorGlobals::get().leftResizing ? 1 : 0)
  3439. + "\nplWheelNudging=" + juce::String (EditorGlobals::get().wheelNudging ? 1 : 0)
  3440. + "\nplManualFades=" + juce::String (EditorGlobals::get().manualFades ? 1 : 0)
  3441. + "\nplSnapFadeHandles=" + juce::String (EditorGlobals::get().snapFadeHandles ? 1 : 0)
  3442. + (EditorGlobals::get().automationFollowsClips < 0 ? juce::String()
  3443. : "\nplAutomationFollowsClips=" + juce::String (EditorGlobals::get().automationFollowsClips))
  3444. + (EditorGlobals::get().followPausesOnEdit < 0 ? juce::String()
  3445. : "\nfollowPausesOnEdit=" + juce::String (EditorGlobals::get().followPausesOnEdit))
  3446. + "\nplMagicLasso=" + juce::String (EditorGlobals::get().magicLasso ? 1 : 0)
  3447. + "\nprMagicLasso=" + juce::String (EditorGlobals::get().pianoRollMagicLasso ? 1 : 0)
  3448. + "\ndropAudioOnHeaders=" + juce::String ((int) trackmodes::headerDropOptions().mode)
  3449. + "\ndropLocksToContent=" + juce::String (trackmodes::headerDropOptions().lockToContent ? 1 : 0)
  3450. + "\nselectTracksOnDrop=" + juce::String (trackmodes::headerDropOptions().selectTracks ? 1 : 0)
  3451. + "\nprGridHighlights=" + juce::String (PianoRollComponent::gridHighlights ? 1 : 0)
  3452. + "\nprBlackKeyRows=" + juce::String (PianoRollComponent::blackKeyRows ? 1 : 0)
  3453. + "\nprShowChordName=" + juce::String (PianoRollComponent::showChordName ? 1 : 0)
  3454. + "\nprSongBars=" + juce::String (PianoRollComponent::songBarsRuler ? 1 : 0)
  3455. + "\npolyPrepareOnOpen=" + juce::String (PolyEditorWindows::prepareOnOpen ? 1 : 0)
  3456. + "\nprKeyStyle=" + juce::String ((int) PianoRollComponent::keyStyle)
  3457. + "\naudioLogEnabled=" + juce::String (engine.getRollingLog().isEnabled() ? 1 : 0)
  3458. + "\naudioLogSeconds=" + juce::String (engine.getRollingLog().lengthSeconds())
  3459. + "\naudioLogPreEffects=" + juce::String (engine.getRollingLog().getPosition() == RollingAudioLog::Position::preEffects ? 1 : 0)
  3460. + "\nchordDelayMs=" + juce::String ((std::int64_t) chordReadout.getDelayMs())
  3461. + "\nchordRoman=" + juce::String (chordReadout.getOptions().roman ? 1 : 0)
  3462. + "\nchordNearHint=" + juce::String (chordShowNearHint ? 1 : 0)
  3463. + "\nkeyPanelFollowsStyle=" + juce::String (keyPanelFollowsStyle ? 1 : 0)
  3464. + "\nlinkToggleFollowsStyle=" + juce::String (linkToggleFollowsStyle ? 1 : 0)
  3465. + "\nstretchedClipsLoop=" + juce::String (stretchedClipsLoop() ? 1 : 0)
  3466. + "\nautoClipsAtPlayback=" + juce::String (autoclipplace::atPlayback() ? 1 : 0)
  3467. + "\ndisableTypingPriority=" + juce::String (pluginkeys::newPluginsHostFirst().load() ? 1 : 0)
  3468. + "\nclipLaunchWorkflow=" + juce::String (layoutstyle::legacyClipLaunchFlag (layoutStyle) ? 1 : 0)
  3469. + "\nlayoutStyle=" + layoutstyle::id (layoutStyle)
  3470. + "\nlanesBeforeClipLaunch=" + juce::String (lanesBeforeClipLaunch ? 1 : 0)
  3471. + "\ndetailHeight=" + juce::String (DetailView::preferredHeight)
  3472. + "\ndetailShown=" + juce::String (DetailView::shownSetting ? 1 : 0)
  3473. + "\nsceneTempoShown=" + juce::String (clipGridSceneTempoShown() ? 1 : 0)
  3474. + "\nsceneSelectNext=" + juce::String (clipGridSelectNextOnLaunch() ? 1 : 0)
  3475. + "\nsceneRecordOnLaunch=" + juce::String (clipGridRecordOnSceneLaunch() ? 1 : 0)
  3476. + "\nclipGridClassicLook=" + juce::String (clipGridClassicLook() ? 1 : 0)
  3477. + "\ntallLiveLanes=" + juce::String (playlistTallLiveLanes() ? 1 : 0)
  3478. + "\ninfoViewShown=" + juce::String (DetailView::infoViewShown ? 1 : 0)
  3479. + "\nsessionButtonRow=" + juce::String (sessionButtonRowShown ? 1 : 0)
  3480. + "\nsimpleDockHeight=" + juce::String (SimpleDock::preferredHeight)
  3481. + "\nsimpleDockShown=" + juce::String (SimpleDock::shownSetting ? 1 : 0)
  3482. + "\nkeyboardMode=" + juce::String ((int) scalekeys::current().mode)
  3483. + "\nkeyboardLock=" + juce::String (scalekeys::current().lockToKey ? 1 : 0)
  3484. + "\nchordComplexity=" + juce::String ((int) scalekeys::current().complexity)
  3485. + "\nchordSpread=" + juce::String ((int) scalekeys::current().spread)
  3486. + "\nchordStrum=" + juce::String (scalekeys::current().strumMs)
  3487. + "\nchordStrumDown=" + juce::String (scalekeys::current().strumDown ? 1 : 0)
  3488. + "\nchordProjectSet=" + juce::String (scalekeys::current().projectChords ? 1 : 0)
  3489. + "\ndetailDevices=" + juce::String (DetailView::devicesPage ? 1 : 0)
  3490. + "\ndetailExtraWindowKey=" + juce::String (DetailView::extraWindowKey ? 1 : 0)
  3491. + "\ndetailExtraSelectInMixer=" + juce::String (DetailView::extraSelectInMixer ? 1 : 0)
  3492. + "\nalsSessionOnPlaylist=" + juce::String (AudioEngine::alsSessionOnPlaylist.load() ? 1 : 0)
  3493. + "\nsimpleLargeControls=" + juce::String (ui::simplelook::largeControls() ? 1 : 0)
  3494. + "\nfollowPlaylist=" + juce::String (EditorGlobals::get().isFollowing (false) ? 1 : 0)
  3495. + "\nfollowPianoRoll=" + juce::String (EditorGlobals::get().isFollowing (true) ? 1 : 0)
  3496. + "\nfollowChannelRack=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack) ? 1 : 0)
  3497. + "\nfollowAudioEditor=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor) ? 1 : 0)
  3498. + "\nscopeMode=" + juce::String (toolbar::OutputMonitor::mode)
  3499. + "\nscopeStereo=" + juce::String (toolbar::OutputMonitor::stereoScope ? 1 : 0)
  3500. + "\ncpuRefresh=" + juce::String (toolbar::PerformanceMeter::refresh)
  3501. + "\ncpuView=" + juce::String (toolbar::PerformanceMeter::secondView)
  3502. + "\ntoolbarGroups=" + juce::String (toolbarLayout.orderToString())
  3503. + "\ntoolbarIcons=" + toolbarlayout::Layout::iconSizeId (toolbarLayout.iconSize)
  3504. + "\nuiScale=" + juce::String (toolbarLayout.uiScale)
  3505. + "\nmenuDensity=" + juce::String (theme::menus::compact() ? "compact" : "comfortable")
  3506. + "\ntoolbarSeparators=" + juce::String (toolbarLayout.separators ? 1 : 0)
  3507. + "\ntoolbarVisible=" + juce::String (toolbarLayout.visible ? 1 : 0)
  3508. + "\nautosaveMinutes=" + juce::String (autosaveMinutes) + "\nautosaveKeep=" + juce::String (autosaveKeep)
  3509. + "\naskUnusedRecordings=" + juce::String (askUnusedRecordings ? 1 : 0)
  3510. + "\nmessagesHidden=" + messages::hiddenList()
  3511. + "\nbackupWaitsForQuiet=" + juce::String (backupWaitsForQuiet ? 1 : 0)
  3512. + "\nbackupLongestWait=" + juce::String (backupLongestWaitMinutes)
  3513. + "\nhoverValues=" + juce::String (hoverValues ? 1 : 0)
  3514. + "\nundoLevels=" + juce::String (engine.getUndoLevels())
  3515. + "\nmetronomeVolume=" + juce::String (engine.getTransport().metronomeVolume.load(), 2)
  3516. + "\nmetronomeSoundFl=" + juce::String (metronome::clampSound (engine.getTransport().metronomeSound.load()))
  3517. + "\nmetronomeOnlyRec=" + juce::String (engine.getTransport().metronomeOnlyRecording.load() ? 1 : 0)
  3518. + "\ntapStartsPlayback=" + juce::String (tapStartsPlayback ? 1 : 0)
  3519. + "\nmetronomeTrack=" + juce::String (engine.getTransport().metronomeTrack.load())
  3520. + "\nplayTruncatedOnTransport=" + juce::String (engine.getTransport().playTruncatedOnTransport.load() ? 1 : 0)
  3521. + "\nresetPluginsOnTransport=" + juce::String (engine.getTransport().resetPluginsOnTransport.load() ? 1 : 0)
  3522. + juce::String (flsettings::serialise())
  3523. + "\nrenderAhead=" + juce::String (renderAheadOption().load() ? 1 : 0)
  3524. + "\npreviewVolume=" + juce::String (engine.getPreviewVolume(), 2)
  3525. + "\npreviewInTime=" + juce::String (engine.isPreviewInTime() ? 1 : 0)
  3526. + "\nbrowserAutoPreview=" + juce::String (BrowserComponent::autoPreview ? 1 : 0)
  3527. + "\nbrowserAutoHide=" + juce::String (BrowserComponent::autoHide ? 1 : 0)
  3528. + "\neditorVolume=" + juce::String (engine.getEditorVolume(), 2)
  3529. + "\nrackPianoRollView=" + juce::String (rack.isPianoRollView() ? 1 : 0)
  3530. + "\naskWhatToRecord=" + juce::String (engine.getRecordOptions().askWhatToRecord ? 1 : 0)
  3531. + "\nrecordNotes=" + juce::String (engine.getRecordOptions().recordNotes ? 1 : 0)
  3532. + "\nrecordAudio=" + juce::String (engine.getRecordOptions().recordAudio ? 1 : 0)
  3533. + "\nrecordStartsPlayback=" + juce::String (engine.getRecordOptions().startsPlayback ? 1 : 0)
  3534. + "\ndisarmOnStop=" + juce::String (engine.getRecordOptions().disarmOnStop ? 1 : 0)
  3535. + "\nlowLatencyRecording=" + juce::String (engine.getRecordOptions().lowLatencyRecording ? 1 : 0)
  3536. + "\nrecordOffOnStop=" + juce::String (engine.getRecordOptions().recordOffOnStop ? 1 : 0)
  3537. + "\nunarmAfterRender=" + juce::String (engine.getRecordOptions().unarmAfterRender ? 1 : 0)
  3538. + "\nrenderAutoClip=" + juce::String (engine.getRecordOptions().autoCreateClip ? 1 : 0)
  3539. + "\nrecLatencyCompensation=" + juce::String (engine.getRecordOptions().latencyCompensation ? 1 : 0)
  3540. + "\nrecordQuantiseStarts=" + juce::String (recordQuantiseOn ? 1 : 0)
  3541. + "\nrecordNoteEnd=" + juce::String ((int) engine.getRecordOptions().noteEnd)
  3542. + "\nrecordToStepSequencer=" + juce::String (engine.getRecordOptions().toStepSequencer ? 1 : 0)
  3543. + "\nrecordingMarkers=" + juce::String (engine.getRecordOptions().recordingMarkers ? 1 : 0)
  3544. + "\nrecordAutomation=" + juce::String (engine.getRecordOptions().recordAutomation ? 1 : 0)
  3545. + "\nrecordClips=" + juce::String (engine.getRecordOptions().recordClips ? 1 : 0)
  3546. + "\nrecordQuantiseAutomation=" + juce::String (engine.getRecordOptions().quantiseAutomation ? 1 : 0)
  3547. + "\nrecordPunchLoop=" + juce::String (engine.getRecordOptions().punchLoopRegion ? 1 : 0)
  3548. + "\nrecordPunchEnds=" + juce::String ((engine.getRecordOptions().punchIn ? 1 : 0) | (engine.getRecordOptions().punchOut ? 2 : 0))
  3549. + "\nrecordLoop=" + juce::String (engine.getRecordOptions().loopRecord ? 1 : 0)
  3550. + "\nrecordLastPassPlays=" + juce::String (engine.getRecordOptions().lastLoopPassPlays ? 1 : 0)
  3551. + "\nwaitOnlyWhenRecording=" + juce::String (engine.getRecordOptions().waitOnlyWhenRecording ? 1 : 0)
  3552. + "\nwaitRespectFilter=" + juce::String (engine.getRecordOptions().waitRespectFilter ? 1 : 0)
  3553. + "\nrecordBlend=" + juce::String (engine.getRecordOptions().mode == RecordMode::overdub ? 1 : 0)
  3554. + "\nrecordPreRoll=" + juce::String (engine.getRecordOptions().preRollBars)
  3555. // FL's precount switch and duration, and the metronome switch (issue #152)
  3556. + "\n" + juce::String (countin::onKey.data()) + "=" + juce::String (engine.getRecordOptions().countInBars > 0 ? 1 : 0)
  3557. + "\n" + juce::String (countin::lengthKey.data()) + "=" + juce::String (engine.getRecordOptions().countInLength)
  3558. + "\nmetronomeOn=" + juce::String (engine.getTransport().metronome.load() ? 1 : 0)
  3559. + "\nrecordCatchWindow=" + juce::String (engine.getRecordOptions().catchWindow)
  3560. + "\nrecordCompensateOutput=" + juce::String (engine.getRecordOptions().compensateOutput ? 1 : 0)
  3561. + "\nrecordPostRoll=" + juce::String (engine.getRecordOptions().postRollBars) + "\nmixerUsedOnly=" + juce::String (MixerStrips::showUsedOnly ? 1 : 0) + "\nmixerWaveforms=" + juce::String (MixerStrips::meterWaveforms ? 1 : 0) + "\nmixerLoudness=" + juce::String (MixerStrips::showLoudness ? 1 : 0) + "\nmixerStripInserts=" + juce::String (MixerStrips::showStripInserts ? 1 : 0) + "\ngrossBeatFlLocator=" + juce::String (gblocator::flStyle() ? 1 : 0) + "\nmixerKeepLostLinks=" + juce::String (MixerStrips::keepLostLinks ? 1 : 0) + "\nmixerFollowPlaylist=" + juce::String (MixerStrips::followPlaylist ? 1 : 0) + "\nmixerLayout=" + juce::String ((int) MixerStrips::layout)
  3562. + "\nquantizeSongJumps=" + juce::String (engine.quantizeSongJumps.load()) + "\n"
  3563. + juce::String (newProjectDefaults().toText()));
  3564. }
  3565. // --- transport -----------------------------------------------------------------------------------
  3566. void MainComponent::playStop()
  3567. {
  3568. auto& transport = engine.getTransport();
  3569. if (engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting()) // pressed again: cancel
  3570. {
  3571. engine.stop();
  3572. return;
  3573. }
  3574. if (transport.playing.load())
  3575. {
  3576. // back to the remembered position: the last ruler click, else where playback started (FL, issue #169)
  3577. const auto back = stopReturn (false, true);
  3578. stoppedAtTicks = transport.positionTicks.load(); // (round 190ld: Live's Shift+Space continues from here)
  3579. engine.stop();
  3580. engine.seek ((double) back);
  3581. playStartTicks = (double) back;
  3582. transportPaused = false;
  3583. }
  3584. else
  3585. {
  3586. notePlayStart (transportPaused);
  3587. transportPaused = false;
  3588. engine.startPlayback();
  3589. // round 190np: Play in Song mode with an empty Playlist (the Pattern layout) is a confusion signal: one tip
  3590. if (onboardingOn && onboarding::songModeEmptySignal (engine.getSong().mode == PlayMode::song, engine.getSong(), layoutStyle))
  3591. maybeShowTip (onboarding::Tip::songModeEmpty, &songModeButton);
  3592. }
  3593. }
  3594. void MainComponent::playPause()
  3595. {
  3596. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting())
  3597. {
  3598. engine.stop();
  3599. transportPaused = true; // (FL's pause keeps the position and the mark)
  3600. }
  3601. else
  3602. {
  3603. notePlayStart (transportPaused);
  3604. transportPaused = false;
  3605. engine.startPlayback();
  3606. }
  3607. }
  3608. double MainComponent::positionToStartFrom() const
  3609. {
  3610. const auto& transport = engine.getTransport();
  3611. if (const auto pending = transport.seekRequest.load(); pending >= 0.0)
  3612. return pending; // a ruler click a moment ago: the audio thread hasn't moved there yet
  3613. return transport.positionTicks.load();
  3614. }
  3615. void MainComponent::notePlayStart (bool resume)
  3616. {
  3617. playStartTicks = positionToStartFrom();
  3618. if (resume && returnTicks >= 0.0)
  3619. return; // a resume after a pause: the mark stays (FL)
  3620. returnTicks = playStartTicks;
  3621. returnSongMode = engine.getSong().mode == PlayMode::song;
  3622. seekClicksSeen = EditorGlobals::get().seekMarkSerial; // (the click that put the position here is this start)
  3623. }
  3624. void MainComponent::forgetSeekMark()
  3625. {
  3626. auto& globals = EditorGlobals::get();
  3627. globals.seekMark = -1;
  3628. seekClicksSeen = globals.seekMarkSerial;
  3629. returnTicks = -1.0;
  3630. transportPaused = false;
  3631. }
  3632. std::int64_t MainComponent::stopReturn (bool alreadyStopped, bool spaceKey)
  3633. {
  3634. auto& globals = EditorGlobals::get();
  3635. if (globals.seekMarkSerial != seekClicksSeen && globals.seekMark >= 0) // a ruler click, also one made while playing
  3636. {
  3637. seekClicksSeen = globals.seekMarkSerial;
  3638. returnTicks = (double) globals.seekMark;
  3639. returnSongMode = globals.seekMarkSongMode;
  3640. }
  3641. const auto songMode = engine.getSong().mode == PlayMode::song;
  3642. const auto mark = returnTicks >= 0.0 && returnSongMode == songMode ? (std::int64_t) std::llround (returnTicks) : (std::int64_t) -1;
  3643. const auto start = returnSongMode == songMode ? (std::int64_t) std::llround (playStartTicks) : (std::int64_t) 0;
  3644. const auto target = transportedit::stopReturnTarget (alreadyStopped, globals.rememberSeek, spaceKey, mark, start);
  3645. if (alreadyStopped) // FL's second Stop: the start, and the mark is forgotten
  3646. {
  3647. returnTicks = -1.0;
  3648. globals.seekMark = -1;
  3649. seekClicksSeen = globals.seekMarkSerial;
  3650. }
  3651. return target;
  3652. }
  3653. void MainComponent::playFromStart()
  3654. {
  3655. // FL 2026's Shift+Space (measured in FL, issue #11): playing, recording, waiting or counting in -> stop at the start
  3656. // of the time selection (Song mode) or else of the song / pattern; stopped -> play from the current position, as
  3657. // Space does (a later Space goes back there).
  3658. const auto wasPlaying = engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting();
  3659. if (! wasPlaying)
  3660. {
  3661. playStop();
  3662. return;
  3663. }
  3664. engine.stop();
  3665. transportPaused = false;
  3666. const auto& song = engine.getSong();
  3667. const auto target = transportedit::shiftSpaceStopTarget (song.mode == PlayMode::song, song.hasLoop(), song.loopStart);
  3668. if (target > 0)
  3669. engine.seek ((double) target);
  3670. else
  3671. engine.rewind();
  3672. playStartTicks = (double) target;
  3673. }
  3674. void MainComponent::moveToStart()
  3675. {
  3676. // issue #195, FL's Home ("Move playback marker to start", core/TransportEdit.h): the start of the song or pattern,
  3677. // playing or stopped; it is the mark a later Stop goes back to, as a ruler click there would be (issue #169)
  3678. const auto songMode = engine.getSong().mode == PlayMode::song;
  3679. EditorGlobals::get().markSeek (0, songMode);
  3680. const auto playing = engine.getTransport().playing.load();
  3681. engine.seek (0.0);
  3682. if (! playing)
  3683. {
  3684. playStartTicks = 0.0;
  3685. transportPaused = false;
  3686. }
  3687. }
  3688. void MainComponent::stopAndRewind (bool toStart)
  3689. {
  3690. // Stop while nothing plays (the second press, or a double click) goes back to the very start even when
  3691. // "Remember seek time" sends the first Stop to the ruler mark (round 162, issue #9)
  3692. // (paused is not stopped: FL's Stop after a pause (transport state 2) still goes back to the seek mark, issue #169)
  3693. const auto alreadyStopped = toStart || ! (transportPaused || engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting());
  3694. const auto back = stopReturn (alreadyStopped, false); // (issue #169: FL's seek mark, Pattern mode too)
  3695. if (! (transportPaused || engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting()))
  3696. engine.stopWhileStopped(); // (round 190jl: FL's "Send all notes off" on a Stop while stopped)
  3697. engine.stop();
  3698. transportPaused = false;
  3699. // FL: the transport's Stop also ends a Browser sample preview (issue #11)
  3700. browser.stopPreview(); // (the engine's one preview voice: the Sample browser window's preview stops too)
  3701. // round 190jj (Simple, BandLab: "After Stop, the playhead jumps back to where recording started"): the first Stop after
  3702. // a take goes to its start
  3703. if (simpleRecordStart >= 0.0 && ! alreadyStopped && toolbarlayout::transportStates (toolbarLook).stopWhilePlaying)
  3704. {
  3705. const auto start = simpleRecordStart;
  3706. simpleRecordStart = -1.0;
  3707. engine.seek (start);
  3708. playStartTicks = start;
  3709. return;
  3710. }
  3711. simpleRecordStart = -1.0;
  3712. if (back > 0) // "Remember seek time": back to the position clicked on a ruler, or where playback started
  3713. engine.seek ((double) back);
  3714. else
  3715. engine.rewind();
  3716. playStartTicks = (double) back;
  3717. }
  3718. void MainComponent::showStopMenu()
  3719. {
  3720. auto& globals = EditorGlobals::get();
  3721. juce::PopupMenu menu;
  3722. menu.addSectionHeader (tr ("Stop"));
  3723. menu.addItem (tr ("Remember seek time: Stop goes back to the position clicked on the Playlist ruler"), true, globals.rememberSeek, [this] {
  3724. EditorGlobals::get().rememberSeek = ! EditorGlobals::get().rememberSeek;
  3725. saveUiSettings();
  3726. });
  3727. menu.addSeparator();
  3728. menu.addItem (tr ("All notes off (panic)") + "\t" + tr ("double-click"), [this] { engine.panic(); });
  3729. menu.addItem (tr ("Back to the start"), [this] { stopAndRewind (true); });
  3730. // issue #195: the LYNX extra beside FL's Home (Settings › LYNX extras, the same switch)
  3731. menu.addSeparator();
  3732. menu.addItem (tr ("W moves the playback marker to the start (as Home)"), true, transportedit::wGoesToStart(),
  3733. [] { workflowextras::setExtra ("transport.wToStart", ! transportedit::wGoesToStart()); });
  3734. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&stopButton));
  3735. }
  3736. void MainComponent::toggleMode()
  3737. {
  3738. engine.editSong ([] (Song& s) { s.mode = s.mode == PlayMode::song ? PlayMode::pattern : PlayMode::song; }, false);
  3739. }
  3740. // --- panels --------------------------------------------------------------------------------------
  3741. void MainComponent::togglePanel (Panel panel)
  3742. {
  3743. if (panel == Panel::channelRack && workflowextras::refusesChannelRack()) // round 190iu: Track-only mode
  3744. return;
  3745. workspace.toggle (panel);
  3746. refreshPanelButtons();
  3747. }
  3748. void MainComponent::fitChannelRack (bool width)
  3749. {
  3750. rack.updateSize();
  3751. const auto scrollbar = rackViewport.getScrollBarThickness();
  3752. // compact like FL's rack: at most two bars of steps are shown, longer patterns scroll sideways, so the
  3753. // rack does not cover the Playlist after a project with long patterns is opened
  3754. // and never past the desktop's right edge from where the rack is (the default layout keeps the Playlist's track
  3755. // names uncovered on a small desktop, round 167v)
  3756. const auto maxWidth = juce::jmin (juce::jmax (300, workspace.getWidth() - 16 - workspace.getPanelBounds (Panel::channelRack).getX() - scrollbar - 8), rack.widthForSteps (32));
  3757. const auto contentWidth = juce::jmin (rack.naturalWidth(), maxWidth); // the ghost steps only fill a wider rack
  3758. const auto needsHorizontal = rack.naturalWidth() > contentWidth;
  3759. workspace.fitPanelContent (Panel::channelRack, width ? contentWidth + scrollbar : 0, rack.getHeight() + (needsHorizontal ? scrollbar : 0));
  3760. fittedChannelCount = (int) engine.getSong().channels.size();
  3761. }
  3762. void MainComponent::showPanel (Panel panel)
  3763. {
  3764. if (panel == Panel::channelRack && workflowextras::refusesChannelRack()) // round 190iu: Track-only mode
  3765. return;
  3766. workspace.show (panel);
  3767. refreshPanelButtons();
  3768. }
  3769. void MainComponent::showWindowsTip()
  3770. {
  3771. const auto counter = PluginHost::settingsFolder().getChildFile ("windows-tip.txt");
  3772. const auto shown = counter.existsAsFile() ? counter.loadFileAsString().trim().getIntValue() : 0;
  3773. if (shown >= 3)
  3774. return;
  3775. counter.replaceWithText (juce::String (shown + 1));
  3776. auto key = [this] (Panel p) {
  3777. const auto chords = keyMap.chordsFor (panelAction (p));
  3778. return chords.empty() ? juce::String() : "[" + juce::String (keys::toString (chords.front())) + "] ";
  3779. };
  3780. ui::Hint hint;
  3781. hint.text = tr ("Windows: {0}Playlist {1}Channel Rack {2}Piano Roll {3}Mixer {4}Browser (or the window buttons in the toolbar; again: hide)",
  3782. { key (Panel::playlist), key (Panel::channelRack), key (Panel::pianoRoll), key (Panel::mixer), key (Panel::browser) });
  3783. ui::postHint (hint, 15000);
  3784. }
  3785. void MainComponent::refreshPanelButtons()
  3786. {
  3787. for (int i = 0; i < workspace::panelCount; ++i)
  3788. panelButtons[(std::size_t) i].setToggleState (workspace.isPanelVisible ((Panel) i), juce::dontSendNotification);
  3789. }
  3790. void MainComponent::openPianoRoll()
  3791. {
  3792. showPanel (Panel::pianoRoll);
  3793. pianoRoll.scrollToNotes();
  3794. }
  3795. void MainComponent::saveLayoutAs()
  3796. {
  3797. auto* window = new juce::AlertWindow (tr ("Save layout as"), tr ("Name of the layout:"), juce::MessageBoxIconType::NoIcon);
  3798. window->addTextEditor ("name", tr ("My layout"));
  3799. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3800. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3801. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  3802. const auto name = window->getTextEditorContents ("name").trim();
  3803. if (result == 1 && name.isNotEmpty())
  3804. workspace.saveLayoutAs (name);
  3805. }),
  3806. true);
  3807. keepAboveMainWindow (*window);
  3808. }
  3809. juce::PopupMenu MainComponent::layoutsMenu()
  3810. {
  3811. juce::PopupMenu menu;
  3812. auto files = Workspace::layoutsFolder().findChildFiles (juce::File::findFiles, false, "*.txt");
  3813. files.sort();
  3814. for (const auto& file : files)
  3815. menu.addItem (file.getFileNameWithoutExtension(), [this, file] {
  3816. workspace.loadLayout (file);
  3817. refreshPanelButtons();
  3818. });
  3819. if (files.isEmpty())
  3820. menu.addItem (tr ("(none saved yet)"), false, false, [] {});
  3821. menu.addSeparator();
  3822. menu.addItem (tr ("Open layouts folder"), [] {
  3823. Workspace::layoutsFolder().createDirectory();
  3824. Workspace::layoutsFolder().startAsProcess();
  3825. });
  3826. return menu;
  3827. }
  3828. namespace
  3829. {
  3830. // Both | Grid | Song, in the Playlist's title bar while Clip-launch workflow is on (round 181a). Round 190ef: then the
  3831. // reference's control-bar switches Draw Mode (pencil), Key and MIDI (Key / MIDI Map Mode), in its order.
  3832. class ClipGridSwitch final : public juce::Component
  3833. {
  3834. public:
  3835. static constexpr int width = 132 + 8 + 26 + 4 + 40 + 4 + 44;
  3836. // round 190iv: Draw Mode, Key and MIDI moved to Live's control bar (the Clip-launch toolbar); Both | Grid | Song stay here
  3837. static constexpr int compactWidth = 132;
  3838. std::function<void()> onDraw, onKey, onMidi;
  3839. void setStates (bool drawOn, remotemap::Mode mode)
  3840. {
  3841. draw.setToggleState (drawOn, juce::dontSendNotification);
  3842. key.setToggleState (mode == remotemap::Mode::key, juce::dontSendNotification);
  3843. midi.setToggleState (mode == remotemap::Mode::midi, juce::dontSendNotification);
  3844. }
  3845. explicit ClipGridSwitch (std::function<void (PlaylistArea::GridView)> pick)
  3846. {
  3847. addAndMakeVisible (draw);
  3848. draw.setTooltip (tr ("Draw Mode") + juce::String (sessionkeys::menuKey (sessionkeys::Command::drawMode, layoutstyle::Style::clipLaunch)).replace ("\t", " "));
  3849. draw.onClick = [this] { if (onDraw != nullptr) onDraw(); };
  3850. for (auto* b : { &key, &midi })
  3851. {
  3852. addAndMakeVisible (*b);
  3853. b->setColour (juce::TextButton::buttonOnColourId, b == &key ? theme::colour::warning : theme::colour::info);
  3854. b->setColour (juce::TextButton::textColourOnId, theme::colour::bg0);
  3855. }
  3856. key.setButtonText (trc ("@computer key: Key")); // (round 190em: a computer key, not the musical key)
  3857. key.setTooltip (tr ("Key Map Mode: map computer keys to clips, scenes, buttons and controls (Ctrl+K)"));
  3858. key.onClick = [this] { if (onKey != nullptr) onKey(); };
  3859. midi.setButtonText ("MIDI");
  3860. midi.setTooltip (tr ("MIDI Map Mode: map MIDI controls to clips, scenes, buttons and controls (Ctrl+M)"));
  3861. midi.onClick = [this] { if (onMidi != nullptr) onMidi(); };
  3862. const std::pair<juce::TextButton*, PlaylistArea::GridView> buttons[] { { &both, PlaylistArea::GridView::beside },
  3863. { &grid, PlaylistArea::GridView::grid },
  3864. { &song, PlaylistArea::GridView::song } };
  3865. both.setButtonText (tr ("Both"));
  3866. grid.setButtonText (tr ("Grid"));
  3867. song.setButtonText (tr ("Song"));
  3868. both.setToggleState (true, juce::dontSendNotification);
  3869. for (const auto& [button, view] : buttons)
  3870. {
  3871. addAndMakeVisible (*button);
  3872. button->setRadioGroupId (1181);
  3873. button->setClickingTogglesState (true);
  3874. // (the radio group also "clicks" the button it turns off)
  3875. button->onClick = [pick, view = view, button = button] {
  3876. if (button->getToggleState())
  3877. pick (view);
  3878. };
  3879. }
  3880. }
  3881. void show (PlaylistArea::GridView view)
  3882. {
  3883. (view == PlaylistArea::GridView::beside ? both : view == PlaylistArea::GridView::grid ? grid : song).setToggleState (true, juce::dontSendNotification);
  3884. }
  3885. void resized() override
  3886. {
  3887. auto r = getLocalBounds().reduced (0, 4);
  3888. const auto withSwitches = r.getWidth() >= width;
  3889. for (juce::Component* c : { (juce::Component*) &draw, (juce::Component*) &key, (juce::Component*) &midi })
  3890. c->setVisible (withSwitches);
  3891. auto switches = withSwitches ? r.removeFromRight (26 + 4 + 40 + 4 + 44) : juce::Rectangle<int>();
  3892. if (withSwitches)
  3893. r.removeFromRight (8);
  3894. const auto w = r.getWidth() / 3;
  3895. both.setBounds (r.removeFromLeft (w));
  3896. grid.setBounds (r.removeFromLeft (w));
  3897. song.setBounds (r);
  3898. draw.setBounds (switches.removeFromLeft (26));
  3899. switches.removeFromLeft (4);
  3900. key.setBounds (switches.removeFromLeft (40));
  3901. switches.removeFromLeft (4);
  3902. midi.setBounds (switches);
  3903. }
  3904. private:
  3905. juce::TextButton both, grid, song;
  3906. IconButton draw { "drawMode", Icon::draw };
  3907. juce::TextButton key, midi;
  3908. };
  3909. } // namespace
  3910. void MainComponent::syncClipLaunchSwitches()
  3911. {
  3912. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  3913. flip->setStates (drawmode::isOn(), getMapMode());
  3914. // round 190iv: the same switches in Live's control bar
  3915. drawModeButton.setToggleState (drawmode::isOn(), juce::dontSendNotification);
  3916. keyMapButton.setToggleState (getMapMode() == remotemap::Mode::key, juce::dontSendNotification);
  3917. midiMapButton.setToggleState (getMapMode() == remotemap::Mode::midi, juce::dontSendNotification);
  3918. }
  3919. void MainComponent::setSimpleLargeControls (bool on)
  3920. {
  3921. // round 190jc (owner decision 9, design190ia SG-C/SG-D): the Simple headers, the dock and the pads at touch size
  3922. if (on == ui::simplelook::largeControls())
  3923. return;
  3924. ui::simplelook::largeControls() = on;
  3925. playlist.simpleLookChanged();
  3926. if (simpleWorkflow != nullptr)
  3927. simpleWorkflow->lookChanged();
  3928. saveUiSettings();
  3929. }
  3930. void MainComponent::setLayoutStyle (layoutstyle::Style style, bool swapLayout)
  3931. {
  3932. using layoutstyle::Style;
  3933. const auto from = layoutStyle;
  3934. const auto partsReady = [this] (Style s) {
  3935. return s == Style::pattern || (s == Style::clipLaunch && clipGridView != nullptr) || (s == Style::simple && simpleWorkflow != nullptr);
  3936. };
  3937. if (style == from && partsReady (style))
  3938. return;
  3939. // each style's own parts are made the first time it is chosen (nothing of them exists in Pattern workflow)
  3940. if (style == Style::clipLaunch && clipGridView == nullptr)
  3941. {
  3942. clipGridView = makeClipGrid (engine);
  3943. clipGridSwitch = std::make_unique<ClipGridSwitch> ([this] (PlaylistArea::GridView view) { setClipGridView (view); });
  3944. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get())) // (round 190ef)
  3945. {
  3946. flip->onDraw = [] { drawmode::toggle(); };
  3947. drawmode::addListener ([safe = juce::Component::SafePointer<MainComponent> (this)] (bool) {
  3948. if (safe != nullptr)
  3949. safe->syncClipLaunchSwitches();
  3950. });
  3951. flip->onKey = [this] { setMapMode (getMapMode() == remotemap::Mode::key ? remotemap::Mode::off : remotemap::Mode::key); };
  3952. flip->onMidi = [this] { setMapMode (getMapMode() == remotemap::Mode::midi ? remotemap::Mode::off : remotemap::Mode::midi); };
  3953. }
  3954. makeDetailView();
  3955. }
  3956. if (style == Style::simple && simpleWorkflow == nullptr)
  3957. {
  3958. SimpleWorkflow::Host host;
  3959. host.setOverlay = [this] (juce::Component* c) {
  3960. // round 190fc (0.1.27 RC H2): an overlay that had the keys (Welcome, Start from, the chooser) gives them back
  3961. // to the main window when it goes; JUCE would hand them to the first child that takes keys (the dock's
  3962. // search box, the Lyrics text...), where Space typed instead of playing
  3963. auto* old = playlistArea.getOverlay();
  3964. const auto hadKeys = old != nullptr && old != c && old->hasKeyboardFocus (true);
  3965. playlistArea.setOverlay (c);
  3966. if (hadKeys && c == nullptr && isShowing())
  3967. grabKeyboardFocus();
  3968. if (onboardingOn) // (round 190np: the New-track card closed by hand on an empty song: the empty-state hint)
  3969. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  3970. if (safe != nullptr)
  3971. safe->updateEmptyHint();
  3972. });
  3973. };
  3974. host.showKeys = [this] {
  3975. if (! isTouchKeyboardOpen()) // (round 190p: a new instrument can be played at once, with the mouse too)
  3976. toggleTouchKeyboard (engine);
  3977. };
  3978. host.setTitleAccessory = [this] (juce::Component* c, int width) { workspace.setTitleAccessory (Panel::playlist, c, width); };
  3979. host.toggleLoops = [this] { // round 190lx (DS-42): the Simple title bar's Loops button
  3980. if (isLoopsDockShowing())
  3981. hideLoopsDock();
  3982. else
  3983. showLoopsDock();
  3984. };
  3985. host.showLoops = [this] {
  3986. // round 190lx (DS-42): docked on the right of the timeline and the track dock, as BandLab's Sounds panel
  3987. if (layoutStyle == layoutstyle::Style::simple)
  3988. {
  3989. showLoopsDock();
  3990. return;
  3991. }
  3992. // round gaps190kf: with the Loop Browser shown (GarageBand's loop browser: keyword buttons, scale, types)
  3993. if (findToolWindow ("sampleBrowser") == nullptr)
  3994. {
  3995. BrowserComponent::openLoopsNext = true;
  3996. toggleSampleBrowser();
  3997. BrowserComponent::openLoopsNext = false;
  3998. }
  3999. else
  4000. BrowserComponent::showLoopsInSampleBrowser();
  4001. };
  4002. // round 190ch: Lyrics / Notes, Reference match and a new project from the "Start from" list
  4003. host.toggleLyrics = [this] { toggleLyrics(); };
  4004. host.setAutomation = [this] (bool on) { playlist.setSimpleAutomation (on); }; // round 190jr
  4005. host.openProject = [this] (const juce::File& file) { openFileRequest (file); };
  4006. host.showReferenceMatch = [this] { showReferenceMatch(); };
  4007. host.startFrom = [this] (Song song) {
  4008. auto shared = std::make_shared<Song> (std::move (song));
  4009. confirmDiscard ([this, shared] { startNewProject (std::move (*shared), {}); });
  4010. };
  4011. host.trackAdded = [this] (int track) { playlist.selectTrack (track); };
  4012. host.setSideDock = [this] (juce::Component* c, int width) { playlistArea.setSideDock (c, width); };
  4013. // round 190t: the Sampler tile's start folder, the Finish dock's "Save the song as a file", the backup status
  4014. host.sampleFolder = [this] { return browser.firstSampleFolder(); };
  4015. host.exportAudio = [this] (int format) { exportAudio (format); };
  4016. host.exportOtherApps = [this] { exportForOtherApps(); };
  4017. host.saveStatus = [this] { return simpleSaveStatus(); };
  4018. host.saveStatusChanged = [this] { refreshSaveStatus(); }; // (round 190iv: the top bar's "Last saved")
  4019. host.statusForSnapshot = [this] (const juce::String& text) {
  4020. using S = toolbarlayout::SaveState;
  4021. saveStatusFrozen = true;
  4022. const auto state = text.isEmpty() ? S::fresh : text == tr ("All changes saved") ? S::saved : text == tr ("Not saved yet") ? S::unsaved : S::backedUp;
  4023. saveStatus.set (state, text.isEmpty() ? tr ("Nothing to save yet") : text);
  4024. };
  4025. // round 190bu: the dock for the selected track sits where Clip-launch's detail view does (never both)
  4026. host.setBottomDock = [this] (juce::Component* c, std::function<int (int)> heightFor) { playlistArea.setDetailView (c, std::move (heightFor)); };
  4027. host.toggleChannelWindow = [this] (int channel) { rack.toggleEditor (channel, true); };
  4028. host.selectedTrack = [this] { return playlist.getCurrentTrack(); };
  4029. host.settingsChanged = [this] { saveUiSettings(); };
  4030. // round 190ds: the dock's Editor tab docks the Piano roll (as the Clip-launch detail view does; never both)
  4031. host.dockPianoRoll = [this] (int pattern) { return dockPianoRoll (pattern); };
  4032. host.undockPianoRoll = [this] { undockPianoRoll(); };
  4033. host.setFoldToKey = [this] (bool on) {
  4034. if (const auto key = projectkey::get (engine.getSong()); on && key) // (the rows show the project key, then fold)
  4035. pianoRoll.setScale (key->root, projectkey::lynxScale (*key));
  4036. pianoRoll.setFoldToScale (on);
  4037. };
  4038. host.foldedToKey = [this] { return pianoRoll.isFoldedToScale(); };
  4039. host.openPianoRollPanel = [this] { showPanel (Panel::pianoRoll); };
  4040. workspace.onWillShow = [this] (Panel panel) { pianoRollPanelWillShow (panel); };
  4041. // round 190dv: the Welcome screen (by itself only in a real session) and the first-song tour
  4042. host.window = [this] { return static_cast<juce::Component*> (this); };
  4043. host.offerWelcome = persistent;
  4044. host.newProjectForTour = [this] (std::function<void()> then) {
  4045. auto go = [this, then] {
  4046. confirmDiscard ([this, then] {
  4047. startNewProject (makeDefaultTemplateProject (nullptr), {});
  4048. if (then)
  4049. then();
  4050. });
  4051. };
  4052. juce::AlertWindow::showYesNoCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("First-song tour"),
  4053. tr ("The tour builds a song from the start. Start it in a new project?"), tr ("New project"),
  4054. tr ("This project"), tr ("Cancel"), nullptr,
  4055. juce::ModalCallbackFunction::create ([go, then] (int result) {
  4056. if (result == 1)
  4057. go();
  4058. else if (result == 2 && then)
  4059. then();
  4060. }));
  4061. };
  4062. simpleWorkflow = std::make_unique<SimpleWorkflow> (engine, std::move (host));
  4063. playlist.onSimpleAutomationChanged = [this] (bool on) { // round 190jr: the title bar's switch follows the view
  4064. if (simpleWorkflow != nullptr)
  4065. simpleWorkflow->automationShown (on);
  4066. };
  4067. // the Simple headers' "+FX": the dock's Effects tab on that track (round 190bu; the Mixer shows the same slots)
  4068. playlist.onTrackEffects = [this] (int insert) {
  4069. if (simpleWorkflow != nullptr)
  4070. simpleWorkflow->showEffectsOfInsert (insert);
  4071. };
  4072. playlist.onSimpleTrackSelected = [this] (int track) {
  4073. if (simpleWorkflow != nullptr && layoutStyle == layoutstyle::Style::simple)
  4074. simpleWorkflow->trackSelected (track);
  4075. };
  4076. playlist.onSimpleFilesDropped = [this] (const juce::StringArray& files, std::int64_t tick) {
  4077. if (simpleWorkflow != nullptr)
  4078. simpleWorkflow->dropFiles (files, tick);
  4079. };
  4080. // round 190jc (design190ia SG-2): the round "+" under the Simple tracks opens the New-track chooser
  4081. playlist.onSimpleAddTrack = [this] {
  4082. if (simpleWorkflow != nullptr && layoutStyle == layoutstyle::Style::simple)
  4083. simpleWorkflow->showChooser();
  4084. };
  4085. // round 190fo: "Export this track" in the Simple track menu
  4086. playlist.onExportTrack = [this] (int track, bool asMidi) {
  4087. engine.capturePluginStates();
  4088. exportOneTrack (engine, track, asMidi,
  4089. currentFile != juce::File() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  4090. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled"));
  4091. };
  4092. }
  4093. if (from == Style::simple && style != Style::simple && simpleWorkflow != nullptr)
  4094. simpleWorkflow->left();
  4095. if (style != Style::simple) // (round 190lx: the Loops dock is the Simple layout's own)
  4096. hideLoopsDock();
  4097. // round 190fc (H2): every click in the Simple window leaves the keys with the main window (text fields excepted)
  4098. if (style == Style::simple)
  4099. juce::Desktop::getInstance().addGlobalMouseListener (&simpleClickKeys);
  4100. else
  4101. juce::Desktop::getInstance().removeGlobalMouseListener (&simpleClickKeys);
  4102. // the workspace layout is kept per style, so going back restores the Pattern layout exactly
  4103. const auto layoutFile = [] (Style s) { return platform::settingsFile (layoutstyle::workspaceFile (s)); };
  4104. if (persistent && swapLayout && style != from)
  4105. {
  4106. layoutFile (from).replaceWithText (workspace.getLayoutText());
  4107. if (const auto saved = layoutFile (style); saved.existsAsFile())
  4108. workspace.applyLayoutText (saved.loadFileAsString());
  4109. else if (style == Style::clipLaunch)
  4110. {
  4111. workspace.hide (Panel::channelRack); // one click away, on the toolbar
  4112. workspace.show (Panel::playlist);
  4113. }
  4114. else if (style == Style::simple)
  4115. {
  4116. // one window: the tracks and the timeline fill it; the other panels stay one click away (View, F5…F9)
  4117. for (auto panel : { Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser })
  4118. workspace.hide (panel);
  4119. workspace.show (Panel::playlist);
  4120. if (! workspace.isMaximised (Panel::playlist))
  4121. workspace.toggleMaximised (Panel::playlist);
  4122. }
  4123. refreshPanelButtons();
  4124. if (isShowing())
  4125. grabKeyboardFocus(); // (the new layout must not leave the keys in the Browser's search box)
  4126. }
  4127. // Clip-launch workflow shows the automation lanes; going back restores the user's setting
  4128. const auto clipLaunch = style == Style::clipLaunch;
  4129. if (clipLaunch != (from == Style::clipLaunch))
  4130. {
  4131. if (clipLaunch && swapLayout) // (at startup, the saved value holds)
  4132. lanesBeforeClipLaunch = autolanes::shown();
  4133. autolanes::setShown (clipLaunch || lanesBeforeClipLaunch);
  4134. playlist.repaint();
  4135. }
  4136. if (! clipLaunch && detailView != nullptr) // (round 183a: a docked Piano roll goes back to its panel)
  4137. detailView->releaseEditor();
  4138. layoutStyle = style;
  4139. const bool meterLawChanged = layoutstyle::current() != style && ! meterscale::alternate();
  4140. layoutstyle::setCurrent (style); // (round 190cm: the clip grid's and the audio editor's Ableton-style keys follow it)
  4141. if (meterLawChanged) // (round 190mf: FL's meter law in Pattern, the straight axis in the other layouts)
  4142. mixer.repaint();
  4143. BrowserComponent::layoutStyleChanged(); // (round 190ke: "LYNX content" and its tags in the Simple layout)
  4144. if (! clipLaunch && getMapMode() != remotemap::Mode::off) // (round 190ef: the map modes belong to the Clip-launch layout)
  4145. setMapMode (remotemap::Mode::off);
  4146. browser.setLiveItemMenus (clipLaunch); // (round 190cy: Live's flat collection labels in the rows' menus)
  4147. browser.setLiveLayout (clipLaunch); // (round 190iz: Live's sidebar + list; the other layouts keep FL's tabs and tree)
  4148. EditorGlobals::get().clipLaunchWorkflow = clipLaunch; // (round 190db: the audio editor's beat-time view)
  4149. EditorGlobals::get().followLayoutChanged(); // (round 190kp: a layout switch is no scroll by hand: Follow's pauses are lifted)
  4150. EditorGlobals::get().sendChangeMessage(); // (round 190el: the Piano roll's Drum Rack pad rows follow the layout)
  4151. if (clipGridView != nullptr || clipLaunch)
  4152. {
  4153. playlistArea.setClipGrid (clipLaunch ? clipGridView.get() : nullptr, PlaylistArea::GridView::beside);
  4154. shownGridView = PlaylistArea::GridView::beside;
  4155. // the detail view docks under the grid and the Playlist (round 183a); other workflows: nothing docked
  4156. if (detailView != nullptr)
  4157. detailView->setVisible (clipLaunch && DetailView::shownSetting);
  4158. playlistArea.setDetailView (clipLaunch ? detailView.get() : nullptr,
  4159. [this] (int available) { return detailView != nullptr ? detailView->heightFor (available) : 0; });
  4160. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  4161. flip->show (PlaylistArea::GridView::beside);
  4162. workspace.setTitleAccessory (Panel::playlist, clipLaunch ? clipGridSwitch.get() : nullptr, clipLaunch ? ClipGridSwitch::compactWidth : 0); // (round 190iv)
  4163. }
  4164. // the Simple workflow's track headers and no pattern picker (no-ops for the other two styles: nothing changes there)
  4165. playlist.setSimpleHeaders (style == Style::simple);
  4166. if (style != Style::simple)
  4167. playlist.setSimpleAutomation (false); // (round 190jr: the Simple automation view belongs to the Simple layout)
  4168. playlist.setLiveStyle (style == Style::clipLaunch);
  4169. playlistArea.setPickerHidden (style == Style::simple || ! pickerPanelOn);
  4170. if (style == Style::simple && simpleWorkflow != nullptr)
  4171. simpleWorkflow->entered(); // (after the grid's title accessory is gone: the Add track button takes its place)
  4172. // round 184a S11 (D15): the Key panel shows in the Simple and Clip-launch workflows, not in FL's Pattern workflow,
  4173. // until the user shows or hides it by hand
  4174. if (keyPanelFollowsStyle && toolbarLayout.isShown (toolbarlayout::Group::key) != (style != Style::pattern))
  4175. {
  4176. toolbarLayout.setShown (toolbarlayout::Group::key, style != Style::pattern);
  4177. resized();
  4178. repaint();
  4179. }
  4180. // round 190gl: the Link toggle shows in the Clip-launch workflow (the reference DAW's default "Show Link Toggle"),
  4181. // not in FL's Pattern workflow (FL has no Link) nor the Simple one, until the user shows or hides it
  4182. if (linkToggleFollowsStyle && toolbarLayout.isShown (toolbarlayout::Group::link) != (style == Style::clipLaunch))
  4183. {
  4184. toolbarLayout.setShown (toolbarlayout::Group::link, style == Style::clipLaunch);
  4185. resized();
  4186. repaint();
  4187. }
  4188. applyToolbarLook(); // round 190iv: the toolbar of this layout style (Pattern: FL's, as it was)
  4189. if (trackonly::active()) // round 190iu: Track-only mode keeps the Channel rack hidden (core/TrackOnly.h)
  4190. hidePanelForTrackOnly();
  4191. if (onboardingOn) // round 190np: another layout, another empty-state hint (and the cards' place)
  4192. {
  4193. updateEmptyHint();
  4194. placeOnboardingCards();
  4195. }
  4196. }
  4197. void MainComponent::hidePanelForTrackOnly()
  4198. {
  4199. workspace.hide (Panel::channelRack);
  4200. refreshPanelButtons();
  4201. }
  4202. void MainComponent::setPickerPanelOn (bool on)
  4203. {
  4204. // FL's Playlist menu › Picker panel › Enable (issue #175): the Playlist without its Picker column; clicked clips are
  4205. // still what the Pencil and the Brush paint (core/PaintTemplate.h). The Simple workflow never shows it.
  4206. pickerPanelOn = on;
  4207. playlistArea.setPickerHidden (layoutStyle == layoutstyle::Style::simple || ! pickerPanelOn);
  4208. saveUiSettings();
  4209. }
  4210. void MainComponent::addLayoutStyleItems (juce::PopupMenu& menu)
  4211. {
  4212. using layoutstyle::Style;
  4213. juce::PopupMenu styles;
  4214. const auto item = [this, &styles] (const juce::String& text, Style style) {
  4215. styles.addItem (text, true, layoutStyle == style, [this, style] {
  4216. setLayoutStyle (style);
  4217. saveUiSettings();
  4218. });
  4219. };
  4220. item (tr ("Pattern workflow (default)"), Style::pattern);
  4221. item (tr ("Clip-launch workflow"), Style::clipLaunch);
  4222. item (tr ("Simple workflow"), Style::simple);
  4223. workflowextras::addLayoutItems (styles, layoutStyle == Style::pattern); // round 190iu: Track-only mode
  4224. menu.addSubMenu (tr ("Layout style"), styles);
  4225. // round 183a: the detail view's items, only in Clip-launch workflow (the reference DAW's View menu [SHOT] d05)
  4226. if (isClipLaunchWorkflow() && detailView != nullptr)
  4227. {
  4228. menu.addItem (tr ("Detail view") + shortcutText ("view.detailToggle"), true, DetailView::shownSetting, [this] { runAction ("view.detailToggle"); });
  4229. menu.addItem (tr ("Clip view") + shortcutText ("view.detailClip"), true, DetailView::shownSetting && ! DetailView::devicesPage,
  4230. [this] { runAction ("view.detailClip"); });
  4231. menu.addItem (tr ("Device view") + shortcutText ("view.detailDevices"), true, DetailView::shownSetting && DetailView::devicesPage,
  4232. [this] { runAction ("view.detailDevices"); });
  4233. menu.addItem (tr ("Switch between clip view and device view") + shortcutText ("view.detailSwitch"), [this] { runAction ("view.detailSwitch"); });
  4234. }
  4235. // round 190ef: the reference's View › Scene Tempo And Time Signature
  4236. if (isClipLaunchWorkflow() && clipGridView != nullptr)
  4237. menu.addItem (tr ("Scene tempo and time signature"), true, clipGridSceneTempoShown(), [this] {
  4238. clipGridSceneTempoShown() = ! clipGridSceneTempoShown();
  4239. refreshClipGrid (*clipGridView);
  4240. saveUiSettings();
  4241. });
  4242. // round 190ig: the clip grid in Live's look (the default) or round 181a's (an option, add-never-remove); round 190jn:
  4243. // the same switch takes the Session mixer, the Arrangement, the Clip / Device View and the status strip with it
  4244. if (isClipLaunchWorkflow() && clipGridView != nullptr)
  4245. menu.addItem (tr ("Classic LYNX look in the Clip-launch layout"), true, clipGridClassicLook(), [this] {
  4246. clipGridClassicLook() = ! clipGridClassicLook();
  4247. refreshClipGrid (*clipGridView);
  4248. playlist.liveLanesChanged();
  4249. if (detailView != nullptr)
  4250. {
  4251. detailView->resized();
  4252. detailView->repaint();
  4253. }
  4254. playlistArea.resized();
  4255. saveUiSettings();
  4256. });
  4257. // round 190jn (design190ia CL-17, owner decision "go with recommended"): Live's 19 px Arrangement lanes are the
  4258. // default of Live's look; LYNX's 38 px lanes stay as this option
  4259. if (isClipLaunchWorkflow() && ! clipGridClassicLook())
  4260. menu.addItem (tr ("Tall Arrangement lanes"), true, playlistTallLiveLanes(), [this] {
  4261. playlistTallLiveLanes() = ! playlistTallLiveLanes();
  4262. playlist.liveLanesChanged();
  4263. saveUiSettings();
  4264. });
  4265. if (isClipLaunchWorkflow() && ! clipGridClassicLook() && detailView != nullptr)
  4266. menu.addItem (tr ("Info View") + shortcutText ("view.detailInfo"), true, DetailView::shownSetting && DetailView::infoViewShown,
  4267. [this] { runAction ("view.detailInfo"); });
  4268. // round 190bu: the Simple workflow's dock for the selected track (its sound and its effects)
  4269. if (layoutStyle == Style::simple && simpleWorkflow != nullptr)
  4270. menu.addItem (tr ("Track dock") + shortcutText ("view.detailToggle"), true, SimpleDock::shownSetting, [this] { runAction ("view.detailToggle"); });
  4271. }
  4272. void MainComponent::makeDetailView()
  4273. {
  4274. DetailView::Hooks h;
  4275. // the out meter: the Mixer's own level while its strips are on screen (they take the peaks), else the peaks
  4276. h.levelOf = [this] (int insert, int side) {
  4277. return mixer.metersShowing() ? mixer.shownLevel (insert, side) : engine.getMeters().takePeak (insert, side);
  4278. };
  4279. h.toggleChannelWindow = [this] (int channel) { rack.toggleEditor (channel, true); };
  4280. h.selectInMixer = [this] (int insert) { mixer.selectTrack (insert); };
  4281. h.instrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); }; // (as on the Mixer)
  4282. h.openClip = [this] (int track, int scene) { openGridClip (track, scene); };
  4283. h.dockPianoRoll = [this] (int pattern) { return dockPianoRoll (pattern); };
  4284. h.undockPianoRoll = [this] { undockPianoRoll(); };
  4285. h.selectPattern = [this] (int pattern) { selectPattern (pattern); };
  4286. h.toggleHotSwap = [this] (const hotswap::Target& target) { toggleHotSwap (target); };
  4287. h.hotSwapTarget = [this] { return browser.hotSwapTarget(); };
  4288. h.typingKeyboardOn = [this] { return typingPiano; };
  4289. // any way the Piano roll panel comes up (F7, its button, a layout) takes the docked editor back first
  4290. workspace.onWillShow = [this] (Panel panel) { pianoRollPanelWillShow (panel); };
  4291. h.layoutChanged = [this] {
  4292. if (detailView != nullptr)
  4293. detailView->setVisible (isClipLaunchWorkflow() && DetailView::shownSetting);
  4294. playlistArea.resized();
  4295. saveUiSettings();
  4296. };
  4297. detailView = std::make_unique<DetailView> (engine, std::move (h));
  4298. setClipGridSceneFieldsListener (*clipGridView, [this] { saveUiSettings(); }); // round 190ef
  4299. setClipGridPickListener (*clipGridView, [this] (int track, int scene, GridPick pick) {
  4300. if (detailView == nullptr)
  4301. return;
  4302. detailView->showSelection (track, scene);
  4303. if (pick == GridPick::openClip)
  4304. detailView->setPage (DetailView::Page::clip);
  4305. else if (pick == GridPick::openTrack)
  4306. detailView->setPage (DetailView::Page::devices);
  4307. });
  4308. const auto selected = clipGridSelection (*clipGridView);
  4309. detailView->showSelection (selected.first, selected.second);
  4310. }
  4311. // Any way the Piano roll panel comes up (F7, its button, a layout) takes a docked editor back first: from the Clip-launch
  4312. // detail view (round 183a) or the Simple dock's Editor tab (round 190ds)
  4313. void MainComponent::pianoRollPanelWillShow (Panel panel)
  4314. {
  4315. if (panel != Panel::pianoRoll || ! pianoRollDocked)
  4316. return;
  4317. undockPianoRoll();
  4318. if (detailView != nullptr)
  4319. detailView->editorTakenBack();
  4320. if (simpleWorkflow != nullptr)
  4321. simpleWorkflow->editorTakenBack();
  4322. }
  4323. juce::Component* MainComponent::dockPianoRoll (int pattern)
  4324. {
  4325. if (pattern >= 0 && pattern < (int) engine.getSong().patterns.size() && pattern != engine.getSong().currentPattern)
  4326. selectPattern (pattern);
  4327. if (! pianoRollDocked)
  4328. {
  4329. if (workspace.isPanelVisible (Panel::pianoRoll))
  4330. {
  4331. workspace.hide (Panel::pianoRoll);
  4332. refreshPanelButtons();
  4333. }
  4334. workspace.releaseContent (Panel::pianoRoll);
  4335. pianoRollDocked = true;
  4336. pianoRollDockActive = false;
  4337. pianoRoll.setDocked (true); // (a short velocity lane and the keys fitted to the notes in the short dock)
  4338. dockClickWatcher.down = [this] (const juce::MouseEvent& e) {
  4339. pianoRollDockActive = e.eventComponent != nullptr && (e.eventComponent == &pianoRoll || pianoRoll.isParentOf (e.eventComponent));
  4340. };
  4341. juce::Desktop::getInstance().addGlobalMouseListener (&dockClickWatcher);
  4342. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<PianoRollComponent> (&pianoRoll)] {
  4343. if (safe != nullptr)
  4344. safe->scrollToNotes();
  4345. });
  4346. }
  4347. return &pianoRoll;
  4348. }
  4349. void MainComponent::undockPianoRoll()
  4350. {
  4351. if (! pianoRollDocked)
  4352. return;
  4353. pianoRollDocked = false;
  4354. pianoRollDockActive = false;
  4355. pianoRoll.setDocked (false);
  4356. juce::Desktop::getInstance().removeGlobalMouseListener (&dockClickWatcher);
  4357. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll); // (its panel has it again)
  4358. }
  4359. // Round 190ce: links the Browser to `target` (showing the Browser), or ends the link when it is linked to it already.
  4360. void MainComponent::toggleHotSwap (const hotswap::Target& target)
  4361. {
  4362. if (browser.isHotSwapping() && browser.hotSwapTarget() == target)
  4363. {
  4364. browser.endHotSwap();
  4365. return;
  4366. }
  4367. showPanel (Panel::browser);
  4368. browser.beginHotSwap (target);
  4369. }
  4370. // Round 190fc (0.1.27 RC H2, the #161 family inside the app): in the Simple layout Space often did nothing after a click
  4371. // in the window. Its own controls (the dock's tabs and cards, the Lyrics and Finish buttons, the looks) take the keyboard
  4372. // focus on a click, unlike the Pattern layout's panels, and JUCE then hands the keys to whatever child takes them — the
  4373. // dock's sound search box or the Lyrics text, where Space typed a space; the Finish looks and the chooser's tiles also
  4374. // take Space as a click. FL's rule (issue #9): a click anywhere but in a text field leaves the keys with the main window,
  4375. // so Space plays. So after each click in the main window or one of its panels: unless the click was in a text field, or
  4376. // in a part that keeps its own keys (the overlays with their list and tile keys: property "lynxKeepsKeys"; a dock knob
  4377. // just clicked, for its arrow keys: "lynxClickKeepsKeys"), the main window takes the keys back from a text field, from a
  4378. // panel's control, or from nobody.
  4379. // Plugin windows, dialogs and menus are left alone.
  4380. void MainComponent::simpleClickEnded (juce::Component* clicked)
  4381. {
  4382. if (layoutStyle != layoutstyle::Style::simple || clicked == nullptr || ! isShowing())
  4383. return;
  4384. auto inside = clicked == this || isParentOf (clicked);
  4385. for (int i = 0; ! inside && i < workspace::panelCount; ++i)
  4386. {
  4387. auto& frame = workspace.getFrame ((Panel) i);
  4388. inside = &frame == clicked || frame.isParentOf (clicked);
  4389. }
  4390. if (! inside)
  4391. return;
  4392. const auto keepsKeys = [] (juce::Component* c) {
  4393. for (; c != nullptr; c = c->getParentComponent())
  4394. if ((bool) c->getProperties().getWithDefault ("lynxKeepsKeys", false))
  4395. return true;
  4396. return false;
  4397. };
  4398. const auto inTextField = [] (juce::Component* c) {
  4399. for (; c != nullptr; c = c->getParentComponent())
  4400. if (dynamic_cast<juce::TextEditor*> (c) != nullptr)
  4401. return true;
  4402. return false;
  4403. };
  4404. if (inTextField (clicked) || keepsKeys (clicked) || (bool) clicked->getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  4405. return; // (a knob clicked keeps the arrow keys until the next click elsewhere)
  4406. // now (the clicked control has acted: this listener runs after its own mouseUp, where a button's click and the Lyrics
  4407. // panel's text focus happen), and once more after what the click posted has run
  4408. const auto takeKeys = [keepsKeys, inTextField] (MainComponent* self) {
  4409. if (self == nullptr || self->layoutStyle != layoutstyle::Style::simple || ! self->isShowing()
  4410. || juce::Component::getCurrentlyModalComponent() != nullptr) // (a menu or a dialog the click opened)
  4411. return;
  4412. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  4413. if (focused != nullptr && ! inTextField (focused) && (focused == self || self->isParentOf (focused) || keepsKeys (focused)))
  4414. return; // (the main window, or a part with its own keys, has them)
  4415. self->grabKeyboardFocus();
  4416. };
  4417. takeKeys (this);
  4418. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this), takeKeys] { takeKeys (safe.getComponent()); });
  4419. }
  4420. bool MainComponent::pianoRollKeysHere() const
  4421. {
  4422. return pianoRollDocked && pianoRollDockActive && pianoRoll.isShowing();
  4423. }
  4424. bool MainComponent::runDetailAction (const std::string& id)
  4425. {
  4426. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr) // round 190bu: the same keys, the track dock
  4427. {
  4428. if (id == "view.detailToggle")
  4429. simpleWorkflow->toggleDock();
  4430. else if (id == "view.detailSwitch")
  4431. simpleWorkflow->cycleDockTab();
  4432. else
  4433. return false;
  4434. return true;
  4435. }
  4436. if (! isClipLaunchWorkflow() || detailView == nullptr) // (Pattern workflow: the keys keep their old meaning)
  4437. return false;
  4438. if (id == "view.detailToggle")
  4439. {
  4440. DetailView::shownSetting = ! DetailView::shownSetting;
  4441. detailView->setVisible (DetailView::shownSetting);
  4442. playlistArea.resized();
  4443. saveUiSettings();
  4444. }
  4445. else if (id == "view.detailClip")
  4446. detailView->setPage (DetailView::Page::clip);
  4447. else if (id == "view.detailDevices")
  4448. detailView->setPage (DetailView::Page::devices);
  4449. else if (id == "view.detailSwitch")
  4450. detailView->togglePage();
  4451. else if (id == "view.detailInfo") // (round 190jn: Live's Info View, only in its look)
  4452. {
  4453. if (! theme::livelook::active())
  4454. return false;
  4455. if (! DetailView::shownSetting) // (hidden: the detail view comes back with its Info View)
  4456. {
  4457. runDetailAction ("view.detailToggle");
  4458. if (! DetailView::infoViewShown)
  4459. detailView->toggleInfoView();
  4460. }
  4461. else
  4462. detailView->toggleInfoView();
  4463. }
  4464. else
  4465. return false;
  4466. return true;
  4467. }
  4468. void MainComponent::openGridClip (int track, int scene)
  4469. {
  4470. const auto& song = engine.getSong();
  4471. if (! song.clipGrid)
  4472. return;
  4473. const auto* clip = launcher::clipAt (*song.clipGrid, track, scene);
  4474. if (clip == nullptr)
  4475. return;
  4476. if (clip->kind == ClipKind::audio)
  4477. {
  4478. if (clip->channel >= 0 && clip->channel < (int) song.channels.size())
  4479. openAudioEditorForChannel (engine, clip->channel);
  4480. }
  4481. else if (clip->kind == ClipKind::pattern && clip->pattern >= 0 && clip->pattern < (int) song.patterns.size())
  4482. {
  4483. selectPattern (clip->pattern);
  4484. openPianoRoll();
  4485. }
  4486. }
  4487. void MainComponent::setClipGridView (PlaylistArea::GridView view)
  4488. {
  4489. shownGridView = view;
  4490. if (clipGridView != nullptr)
  4491. playlistArea.setClipGrid (clipGridView.get(), view);
  4492. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  4493. flip->show (view);
  4494. if (toolbarLook != toolbarlayout::Look::fl)
  4495. updateLookFields(); // (round 190iv: the control bar's view selector shows the new view at once)
  4496. }
  4497. void MainComponent::selectTabForSnapshot (int tab)
  4498. {
  4499. const Panel panels[] = { Panel::channelRack, Panel::pianoRoll, Panel::playlist, Panel::mixer };
  4500. const auto panel = panels[juce::jlimit (0, 3, tab)];
  4501. if (panel == Panel::pianoRoll)
  4502. {
  4503. const auto& song = engine.getSong();
  4504. std::vector<int> counts (song.channels.size(), 0);
  4505. for (const auto& n : song.activePattern().notes)
  4506. if (n.channel >= 0 && n.channel < (int) counts.size())
  4507. ++counts[(std::size_t) n.channel];
  4508. if (! counts.empty())
  4509. engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
  4510. }
  4511. // each view on its own: the panel maximized over the workspace (issue #192: a maximized panel now fills only what a
  4512. // docked Browser leaves, as FL's; here the Browser is left undocked behind it, so the pictures and --paintbench /
  4513. // --uiperf keep the whole workspace for the view, exactly as before)
  4514. workspace.resetLayout();
  4515. workspace.dockBrowser (workspace::Dock::none);
  4516. workspace.show (panel);
  4517. workspace.toggleMaximised (panel);
  4518. refreshPanelButtons();
  4519. if (panel == Panel::pianoRoll)
  4520. pianoRoll.scrollToNotes();
  4521. if (panel == Panel::playlist)
  4522. playlist.resized(); // update the scrollbars for the loaded song
  4523. if (panel == Panel::mixer)
  4524. mixer.selectFirstTrackWithEffects();
  4525. }
  4526. void MainComponent::showDesktopForSnapshot (bool extraPanels)
  4527. {
  4528. workspace.resetLayout();
  4529. if (auto* stage = dynamic_cast<DanceStage*> (danceStage.get()))
  4530. stage->update(); // (the project's dancers now: no timer runs before the picture)
  4531. if (extraPanels)
  4532. {
  4533. workspace.show (Panel::mixer);
  4534. workspace.show (Panel::pianoRoll);
  4535. pianoRoll.scrollToNotes();
  4536. workspace.show (Panel::channelRack);
  4537. }
  4538. refreshPanelButtons();
  4539. }
  4540. void MainComponent::showPanelsForSnapshot (std::initializer_list<Panel> panels)
  4541. {
  4542. workspace.resetLayout();
  4543. for (const auto panel : panels)
  4544. workspace.show (panel);
  4545. refreshPanelButtons();
  4546. }
  4547. // --- patterns ------------------------------------------------------------------------------------
  4548. void MainComponent::selectPattern (int index)
  4549. {
  4550. if (index >= 0 && index < (int) engine.getSong().patterns.size() && index != engine.getSong().currentPattern)
  4551. engine.editSong ([index] (Song& s) { s.currentPattern = index; }, false);
  4552. }
  4553. void MainComponent::stepPatternFromSelector (int delta)
  4554. {
  4555. // FL's selector goes on past the last pattern (rack ops stepPatternCreating: one new empty pattern at most)
  4556. const auto& song = engine.getSong();
  4557. const auto last = (int) song.patterns.size() - 1;
  4558. if (delta > 0 && last >= 0 && song.currentPattern + delta > last && ! isPatternEmpty (song.patterns[(std::size_t) last]))
  4559. engine.editSong ([delta] (Song& s) { s.currentPattern = stepPatternCreating (s, delta); });
  4560. else
  4561. selectPattern (stepPattern (song, delta));
  4562. }
  4563. void MainComponent::nextEmptyPattern()
  4564. {
  4565. engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  4566. showRenamePattern (engine.getSong().currentPattern);
  4567. }
  4568. void MainComponent::deleteCurrentPattern()
  4569. {
  4570. // FL's Patterns › Delete (Ctrl+Shift+Del); the last pattern stays
  4571. if (engine.getSong().patterns.size() > 1)
  4572. engine.editSong ([] (Song& s) { s.removePattern (s.currentPattern); });
  4573. }
  4574. void MainComponent::insertPatternHere()
  4575. {
  4576. engine.editSong ([] (Song& s) { insertPattern (s, s.currentPattern, newPatternName (s)); });
  4577. }
  4578. // --- window menus ------------------------------------------------------------------------------
  4579. // Each window's own items, at the top of the menu in its title bar (FL keeps an editor's options in the
  4580. // small menu at the left of its title bar). Items run the key map's actions, so they show their keys.
  4581. void MainComponent::addPanelMenuItems (Panel panel, juce::PopupMenu& menu)
  4582. {
  4583. auto action = [this] (juce::PopupMenu& m, const char* id, const juce::String& text, bool enabled = true, bool ticked = false) {
  4584. m.addItem (text + shortcutText (id), enabled, ticked, [this, id] { runAction (id); });
  4585. };
  4586. auto zoomMenu = [&action] (const juce::String& prefix) {
  4587. juce::PopupMenu zoom;
  4588. const std::pair<const char*, const char*> items[] = {
  4589. { "zoomIn", TR_NOOP ("Zoom in") }, { "zoomOut", TR_NOOP ("Zoom out") }, { "zoom1", TR_NOOP ("Zoom: one bar") },
  4590. { "zoom2", TR_NOOP ("Zoom: four bars") }, { "zoom3", TR_NOOP ("Zoom: sixteen bars") },
  4591. { "zoomAll", TR_NOOP ("Zoom to show everything") }, { "zoomSelection", TR_NOOP ("Zoom to the selection") },
  4592. { "centrePlayhead", TR_NOOP ("Centre the view on the playhead") }
  4593. };
  4594. for (const auto& [id, text] : items)
  4595. if (const auto* a = keys::findAction ((prefix + id).toStdString())) // the key map holds the id strings
  4596. action (zoom, a->id, tr (text));
  4597. return zoom;
  4598. };
  4599. switch (panel)
  4600. {
  4601. case Panel::channelRack:
  4602. {
  4603. menu.addSubMenu (tr ("Pattern"), makePatternMenu());
  4604. menu.addSeparator();
  4605. action (menu, "rack.graphEditor", tr ("Graph lanes (velocity, pan, pitch...)"), true, rack.areGraphLanesShown());
  4606. action (menu, "rack.pianoRollView", tr ("Piano-roll view of all channels"), true, rack.isPianoRollView());
  4607. action (menu, "rack.rotateLeft", tr ("Rotate the selected channels' steps left"));
  4608. action (menu, "rack.rotateRight", tr ("Rotate the selected channels' steps right"));
  4609. juce::PopupMenu sort;
  4610. sort.addItem (tr ("By name"), [this] { rack.sortChannels (ChannelSort::name); });
  4611. sort.addItem (tr ("By color"), [this] { rack.sortChannels (ChannelSort::colour); });
  4612. sort.addItem (tr ("By mixer insert"), [this] { rack.sortChannels (ChannelSort::insert); });
  4613. sort.addItem (tr ("By type"), [this] { rack.sortChannels (ChannelSort::type); });
  4614. menu.addSubMenu (tr ("Sort channels"), sort);
  4615. menu.addItem (tr ("Select unused channels"), [this] { rack.selectUnused(); });
  4616. action (menu, "rack.groupSelected", tr ("Group selected..."));
  4617. // FL 2026's next part (capture 190mf A4, fl-rack-options-menu.png): Zip selected Alt+Z, Unzip all Alt+U (round 190mk)
  4618. menu.addSeparator();
  4619. action (menu, "rack.zipSelected", tr ("Zip selected"), ! engine.getSelectedChannels().empty());
  4620. action (menu, "rack.unzipAll", tr ("Unzip all"), std::any_of (engine.getSong().channels.begin(), engine.getSong().channels.end(),
  4621. [] (const ChannelDef& c) { return c.zipped; }));
  4622. // FL's "Restretch all Ctrl+Alt+R" after a line (round 190mp, DE-38; capture 190mp A2, REA ChanRestretchMenuClick →
  4623. // FUN_00fe7510: every channel stretched offline is stretched again). Greyed with no such channel (FL in Thief)
  4624. menu.addSeparator();
  4625. action (menu, "rack.restretchAll", tr ("Restretch all"), restretchableChannels (engine.getSong()) > 0);
  4626. menu.addSectionHeader (tr ("Options")); // (FL's SSMenu: "Mute removed steps" is in its Options part)
  4627. {
  4628. // FL's "Channel button width" › 100 % ... 400 %, Custom (N%), Size to fit (round 190mk, DE-39; capture 190mk
  4629. // A2.1: radio items, before "Channel name alignment")
  4630. juce::PopupMenu widths;
  4631. const auto now = ChannelRackComponent::buttonWidthPercent;
  4632. const auto setWidth = [this] (int percent) {
  4633. rack.setButtonWidth (percent);
  4634. rack.resized();
  4635. saveUiSettings();
  4636. };
  4637. for (const auto p : { 100, 200, 300, 400 })
  4638. widths.addItem (juce::PopupMenu::Item (juce::String (p) + "%").setTicked (now == p).setAction ([setWidth, p] { setWidth (p); }));
  4639. const auto custom = now > 0 && now % 100 != 0;
  4640. widths.addItem (juce::PopupMenu::Item (tr ("Custom ({0}%)", { juce::String (custom ? now : 100) })).setTicked (custom).setAction ([this, setWidth] {
  4641. auto* window = new juce::AlertWindow (tr ("Channel button width"), tr ("Width in percent (100 to 400):"), juce::MessageBoxIconType::NoIcon);
  4642. window->addTextEditor ("percent", juce::String (juce::jmax (100, ChannelRackComponent::buttonWidthPercent)));
  4643. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4644. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4645. window->enterModalState (true, juce::ModalCallbackFunction::create ([setWidth, window] (int result) {
  4646. const auto v = window->getTextEditorContents ("percent").retainCharacters ("0123456789").getIntValue();
  4647. if (result == 1 && v > 0)
  4648. setWidth (juce::jlimit (100, 400, v));
  4649. }),
  4650. true);
  4651. keepAboveMainWindow (*window);
  4652. }));
  4653. widths.addSeparator();
  4654. widths.addItem (juce::PopupMenu::Item (tr ("Size to fit")).setTicked (now == 0).setAction ([setWidth] { setWidth (0); }));
  4655. menu.addSubMenu (tr ("Channel button width"), widths);
  4656. }
  4657. {
  4658. // FL's "Channel name alignment" › Left / Center (round 190kd; FL 2026: Options, before "Colorful channel controls",
  4659. // radio items, Center ticked by default)
  4660. juce::PopupMenu align;
  4661. const auto set = [this] (bool left) {
  4662. ChannelRackComponent::nameAlignLeft = left;
  4663. rack.repaint();
  4664. saveUiSettings();
  4665. };
  4666. align.addItem (juce::PopupMenu::Item (tr ("Left")).setTicked (ChannelRackComponent::nameAlignLeft).setAction ([set] { set (true); }));
  4667. align.addItem (juce::PopupMenu::Item (tr ("Center")).setTicked (! ChannelRackComponent::nameAlignLeft).setAction ([set] { set (false); }));
  4668. menu.addSubMenu (tr ("Channel name alignment"), align);
  4669. }
  4670. menu.addItem (tr ("Mute removed steps"), true, ChannelRackComponent::muteRemovedSteps, [this] {
  4671. ChannelRackComponent::muteRemovedSteps = ! ChannelRackComponent::muteRemovedSteps;
  4672. saveUiSettings();
  4673. });
  4674. // FL 2026's next item there (round 190ld, DE-26): the mixer track number boxes on / off (Alt+M)
  4675. menu.addItem (tr ("Show mixer track selectors") + shortcutText ("rack.mixerSelectors"), true, ChannelRackComponent::showMixerSelectors,
  4676. [this] { runAction ("rack.mixerSelectors"); });
  4677. // FL's place for it (round 190cj, seen in FL 2026: Channel rack menu > Options, after "Mute removed steps" and
  4678. // "Show mixer track selectors"; it was in Settings > General): a row's miniature shows the whole pattern
  4679. menu.addItem (tr ("Show complete piano roll preview"), true, ChannelRackComponent::completePreview.load(), [this] {
  4680. ChannelRackComponent::completePreview.store (! ChannelRackComponent::completePreview.load());
  4681. rack.repaint();
  4682. saveUiSettings();
  4683. });
  4684. // FL 2026's next item (capture 190mf A4; round 190mk, DE-33)
  4685. menu.addItem (tr ("Show a mute button on the piano roll preview"), true, ChannelRackComponent::previewMuteButton, [this] {
  4686. ChannelRackComponent::previewMuteButton = ! ChannelRackComponent::previewMuteButton;
  4687. rack.repaint();
  4688. saveUiSettings();
  4689. });
  4690. break;
  4691. }
  4692. case Panel::playlist:
  4693. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  4694. workspace.toggleMaximised (Panel::playlist);
  4695. refreshPanelButtons();
  4696. });
  4697. menu.addSeparator();
  4698. // FL's Playlist menu › Edit and › Select (round 189e: FL's items and order; the clip items below moved there)
  4699. menu.addSubMenu (tr ("Edit"), playlist.editMenu());
  4700. menu.addSubMenu (tr ("Select"), playlist.selectMenu());
  4701. menu.addSeparator();
  4702. action (menu, "playlist.ripple", tr ("Ripple editing (resizing and deleting move the later clips)"), true, playlist.isRippleOn());
  4703. action (menu, "playlist.rippleDelete", tr ("Delete the selected clips and close the gaps"));
  4704. // FL's legacy Pattern Blocks (round 170f, issue #60): FL 10's "Enable legacy pattern blocks", per project here
  4705. action (menu, "playlist.patternBlocks", tr ("Pattern blocks (current project)"), true, engine.getSong().patternBlocksOn);
  4706. action (menu, "playlist.blocksToClips", tr ("Turn pattern blocks into clips"), ! engine.getSong().blocks.empty());
  4707. action (menu, "playlist.automationLanes", tr ("Automation lanes"), true, autolanes::shown()); // round 177b
  4708. action (menu, "playlist.trackInserts", tr ("Show insert effects on linked tracks"), true, PlaylistComponent::showTrackInserts); // round 190ht
  4709. workflowextras::addPlaylistMenuItems ([&] (const char* id, const juce::String& text, bool enabled, bool ticked) { action (menu, id, text, enabled, ticked); });
  4710. action (menu, "playlist.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (false));
  4711. action (menu, "playlist.quantizeStarts", tr ("Quantize the clips' starts"));
  4712. action (menu, "playlist.quantizeHalf", tr ("Quantize the clips' starts 50% (halfway to the grid)"));
  4713. {
  4714. // (round 177d: FL's Playlist menu › Picker panel; round 190he, issue #175: its first item, Enable, Alt+P)
  4715. juce::PopupMenu pickerPanel;
  4716. action (pickerPanel, "playlist.pickerPanel", tr ("Enable"), layoutStyle != layoutstyle::Style::simple, pickerPanelOn);
  4717. pickerPanel.addSeparator();
  4718. const auto tools = picker.pickerMenu();
  4719. for (juce::PopupMenu::MenuItemIterator it (tools); it.next();)
  4720. pickerPanel.addItem (it.getItem());
  4721. menu.addSubMenu (tr ("Picker panel"), pickerPanel);
  4722. }
  4723. action (menu, "playlist.stretchMode", tr ("Stretch audio when resizing audio clips"), true, EditorGlobals::get().stretchOnResize);
  4724. {
  4725. // FL 2026's Playlist menu › View › Track headers (round 190w; [DFM] EEViewMenu, FL's defaults)
  4726. juce::PopupMenu view;
  4727. view.addSectionHeader (tr ("Track headers"));
  4728. auto option = [this, &view] (const juce::String& text, bool& setting) {
  4729. view.addItem (text, true, setting, [this, &setting] {
  4730. setting = ! setting;
  4731. playlist.headerOptionsChanged();
  4732. });
  4733. };
  4734. option (tr ("Show controls on audio tracks"), PlaylistComponent::showAudioTrackControls);
  4735. option (tr ("Show levels on audio tracks"), PlaylistComponent::showAudioTrackLevels);
  4736. option (tr ("Show levels on instrument tracks"), PlaylistComponent::showInstrumentTrackLevels);
  4737. // FL's View › "Hide collapsed grouped tracks" (round 190jf, B17; EEHideCollapsedAction)
  4738. view.addSeparator();
  4739. view.addItem (tr ("Hide collapsed grouped tracks"), true, PlaylistComponent::hideCollapsedGroups, [this] {
  4740. auto apply = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  4741. if (safe == nullptr)
  4742. return;
  4743. PlaylistComponent::hideCollapsedGroups = ! PlaylistComponent::hideCollapsedGroups;
  4744. safe->playlist.headerOptionsChanged();
  4745. safe->saveUiSettings();
  4746. };
  4747. if (PlaylistComponent::hideCollapsedGroups || platform::testMode())
  4748. {
  4749. apply();
  4750. return;
  4751. }
  4752. // FL's question before switching it on (FLEngine string "Hiding collapsed tracks|This option hides...")
  4753. auto options = juce::MessageBoxOptions()
  4754. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  4755. .withTitle (tr ("Hiding collapsed tracks"))
  4756. .withMessage (tr ("This option hides collapsed Playlist tracks. The parent track will show a down arrow icon to open hidden tracks. Proceed?"))
  4757. .withButton (tr ("Yes"))
  4758. .withButton (tr ("No"))
  4759. .withAssociatedComponent (this);
  4760. juce::AlertWindow::showAsync (options, [apply] (int result) {
  4761. if (result == 1)
  4762. apply();
  4763. });
  4764. });
  4765. menu.addSubMenu (tr ("View"), view);
  4766. }
  4767. {
  4768. juce::PopupMenu trackTools;
  4769. action (trackTools, "playlist.cloneTracks", tr ("Clone selected playlist track(s)"));
  4770. action (trackTools, "playlist.lockAllToContent", tr ("Lock all playlist tracks to content"));
  4771. action (trackTools, "playlist.unlockAllFromContent", tr ("Unlock all playlist tracks from content"));
  4772. action (trackTools, "playlist.resetEmptyTracks", tr ("Reset empty playlist tracks"));
  4773. action (trackTools, "playlist.collapseAllGroups", tr ("Collapse all grouped tracks"));
  4774. action (trackTools, "playlist.expandAllGroups", tr ("Expand all grouped tracks"));
  4775. menu.addSubMenu (tr ("Tools"), trackTools);
  4776. }
  4777. {
  4778. // FL's Playlist Tools › EERenderPLSelectionMenu, EEPLRenderAllTracksMenu, EEPLRenderAllTrackGroupsMenu (round 168e)
  4779. juce::PopupMenu consolidate;
  4780. action (consolidate, "tools.consolidateSelection", tr ("From selection start"));
  4781. action (consolidate, "tools.consolidateSelectionSongStart", tr ("From song start"));
  4782. menu.addSubMenu (tr ("Consolidate playlist selection"), consolidate);
  4783. menu.addSubMenu (tr ("Export all playlist tracks"), playlistTrackExportMenu (false));
  4784. menu.addSubMenu (tr ("Export all playlist track groups"), playlistTrackExportMenu (true));
  4785. }
  4786. menu.addSubMenu (tr ("Zoom"), zoomMenu ("playlist."));
  4787. menu.addSeparator();
  4788. // FL's Performance mode (round 165m)
  4789. action (menu, "playlist.performanceMode", tr ("Performance mode"), true, engine.getSong().performanceMode);
  4790. action (menu, "playlist.zoomPerformance", tr ("Zoom on performance clips"), engine.getSong().performanceZoneEnd() > 0);
  4791. action (menu, "playlist.perfClipProgress", tr ("Performance clip progress"), true, playlist.clipProgressShown());
  4792. action (menu, "playlist.perfTrackProgress", tr ("Performance track progress"), true, playlist.trackProgressShown());
  4793. break;
  4794. case Panel::pianoRoll:
  4795. {
  4796. juce::PopupMenu tools;
  4797. for (const auto* id : { "pianoRoll.riffMachine", "pianoRoll.chordProgression", "pianoRoll.articulate", "pianoRoll.quantize",
  4798. "pianoRoll.chop", "pianoRoll.arpeggiate", "pianoRoll.strum", "pianoRoll.flam", "pianoRoll.claw",
  4799. "pianoRoll.limit", "pianoRoll.flip", "pianoRoll.randomise", "pianoRoll.scaleLevels", "pianoRoll.lfo",
  4800. "pianoRoll.runLastScript" })
  4801. if (const auto* a = keys::findAction (id))
  4802. action (tools, a->id, tr (a->description));
  4803. menu.addSubMenu (tr ("Tools"), tools);
  4804. action (menu, "pianoRoll.quickQuantize", tr ("Quick quantize (starts and lengths)"));
  4805. action (menu, "pianoRoll.quantizeStarts", tr ("Quantize starts"));
  4806. action (menu, "pianoRoll.quantizeHalf", tr ("Quantize starts 50% (halfway to the grid)"));
  4807. action (menu, "pianoRoll.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (true));
  4808. menu.addSubMenu (tr ("Zoom"), zoomMenu ("pianoRoll."));
  4809. menu.addItem (tr ("Snap notes to the scale") + shortcutText ("pianoRoll.scaleSnap"), pianoRoll.hasScale(), pianoRoll.isScaleSnapOn(),
  4810. [this] { pianoRoll.setScaleSnap (! pianoRoll.isScaleSnapOn()); });
  4811. break;
  4812. }
  4813. case Panel::mixer:
  4814. action (menu, "mixer.moveLeft", tr ("Move the selected inserts left"));
  4815. action (menu, "mixer.moveRight", tr ("Move the selected inserts right"));
  4816. menu.addSeparator();
  4817. action (menu, "mixer.linkChannels", tr ("Link the selected channels to the selected insert"));
  4818. action (menu, "mixer.linkChannelsFrom", tr ("Link the selected channels to inserts starting from the selected one"));
  4819. action (menu, "mixer.selectLinkedChannels", tr ("Select the channels linked to the selected insert"));
  4820. break;
  4821. case Panel::browser:
  4822. action (menu, "browser.search", tr ("Search the Browser"));
  4823. browser.addViewItems (menu); // what it lists, which folders it shows (round 163)
  4824. menu.addItem (tr ("Add folder..."), [this] { browser.addUserFolder(); });
  4825. action (menu, "view.sampleBrowser", tr ("Sample browser (separate window)"));
  4826. menu.addSeparator();
  4827. // the search index (round 162, issue #9): searches read it; it follows changed folders by itself
  4828. menu.addSectionHeader (browser.searchIndexStatus());
  4829. menu.addItem (tr ("Refresh search index"), [this] { browser.refreshSearchIndex (false); });
  4830. menu.addItem (tr ("Rebuild search index"), [this] { browser.refreshSearchIndex (true); });
  4831. break;
  4832. default:
  4833. break;
  4834. }
  4835. }
  4836. // --- quick-add palette and history -------------------------------------------------------------
  4837. void MainComponent::togglePluginPicker()
  4838. {
  4839. // FL's ShowPluginPickerAction (F8): opens the picker over the main window, or closes it (REA_rodada169k §2.5)
  4840. if (pluginPickerView != nullptr)
  4841. {
  4842. auto old = std::move (pluginPickerView);
  4843. juce::MessageManager::callAsync ([keep = std::shared_ptr<juce::Component> (std::move (old))] {}); // (it may be on the stack)
  4844. return;
  4845. }
  4846. PluginPickerTargets targets;
  4847. auto safe = juce::Component::SafePointer<MainComponent> (this);
  4848. targets.addInstrument = [safe] (ChannelDef c) {
  4849. if (safe == nullptr)
  4850. return;
  4851. safe->rack.addChannel (std::move (c), true);
  4852. safe->showPanel (Panel::channelRack);
  4853. };
  4854. targets.addEffect = [safe] (EffectSlot slot) {
  4855. if (safe == nullptr)
  4856. return;
  4857. if (! safe->mixer.addEffectToSelected (std::move (slot)))
  4858. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin picker"), tr ("The selected insert has no free effect slot."));
  4859. else
  4860. {
  4861. safe->showPanel (Panel::mixer);
  4862. // FL opens the new effect's window (round 171c, its "insert effect plugin")
  4863. const auto track = safe->mixer.getSelectedTrack();
  4864. if (track >= 0 && track < (int) safe->engine.getSong().mixer.size())
  4865. safe->mixer.openSlotEditor (track, (int) safe->engine.getSong().mixer[(std::size_t) track].effects.size() - 1);
  4866. }
  4867. };
  4868. targets.close = [safe] {
  4869. if (safe != nullptr && safe->pluginPickerView != nullptr)
  4870. safe->togglePluginPicker();
  4871. };
  4872. targets.showMixer = [safe] { // (an effect dragged out of the picker: FL brings up the Mixer)
  4873. if (safe != nullptr)
  4874. safe->showPanel (Panel::mixer);
  4875. };
  4876. targets.openBrowser = [safe] (const std::string& category, bool generators) {
  4877. if (safe == nullptr)
  4878. return;
  4879. safe->showPanel (Panel::browser);
  4880. safe->browser.showPluginDatabase (category.empty() ? juce::String() : tr (category.c_str()), category.empty() ? -1 : (generators ? 1 : 0));
  4881. };
  4882. targets.dragOwner = [safe]() -> juce::Component* { return safe.getComponent(); };
  4883. pluginPickerView = makePluginPickerView (engine, std::move (targets));
  4884. // FL's picker form covers the work area of the main window's monitor, whatever the main window's size (round 175b:
  4885. // FL at 1280 × 720 in a 1920 screen still opens it over the whole screen), and lets the screen show through
  4886. const auto* top = getTopLevelComponent();
  4887. const auto& displays = juce::Desktop::getInstance().getDisplays();
  4888. const auto* display = displays.getDisplayForRect (top != nullptr ? top->getScreenBounds() : getScreenBounds());
  4889. const auto area = display != nullptr ? display->userArea : getScreenBounds();
  4890. takePluginPickerBackdrop (*pluginPickerView, area);
  4891. pluginPickerView->setBounds (area);
  4892. pluginPickerView->addToDesktop (0); // (no frame, not on the taskbar)
  4893. pluginPickerView->setVisible (true);
  4894. pluginPickerView->toFront (true);
  4895. pluginPickerView->grabKeyboardFocus();
  4896. }
  4897. void MainComponent::toggleProjectPicker()
  4898. {
  4899. // FL's Project picker (View › Project picker, Ctrl+F8; round 190my, DF-143): the Plugin picker's form over the screen
  4900. // with the project's patterns and channels; again = closed
  4901. if (projectPickerView != nullptr)
  4902. {
  4903. auto old = std::move (projectPickerView);
  4904. juce::MessageManager::callAsync ([keep = std::shared_ptr<juce::Component> (std::move (old))] {}); // (it may be on the stack)
  4905. return;
  4906. }
  4907. ProjectPickerTargets targets;
  4908. auto safe = juce::Component::SafePointer<MainComponent> (this);
  4909. targets.pickPattern = [safe] (int index) {
  4910. if (safe == nullptr)
  4911. return;
  4912. if (index < 0)
  4913. safe->newPatternButton.onClick();
  4914. else
  4915. safe->selectPattern (index);
  4916. };
  4917. targets.pickChannel = [safe] (int channel) {
  4918. if (safe == nullptr)
  4919. return;
  4920. safe->engine.setSelectedChannel (channel); // (FL, capture 190my A4: the channel's window opens)
  4921. safe->rack.showEditor (channel);
  4922. };
  4923. targets.revealPattern = [safe] (int pattern) {
  4924. if (safe == nullptr)
  4925. return;
  4926. safe->showPanel (Panel::browser);
  4927. safe->browser.revealProjectPattern (pattern);
  4928. };
  4929. targets.close = [safe] {
  4930. if (safe != nullptr && safe->projectPickerView != nullptr)
  4931. safe->toggleProjectPicker();
  4932. };
  4933. targets.dragOwner = [safe]() -> juce::Component* { return safe.getComponent(); };
  4934. projectPickerView = makeProjectPickerView (engine, std::move (targets));
  4935. const auto* top = getTopLevelComponent();
  4936. const auto& displays = juce::Desktop::getInstance().getDisplays();
  4937. const auto* display = displays.getDisplayForRect (top != nullptr ? top->getScreenBounds() : getScreenBounds());
  4938. const auto area = display != nullptr ? display->userArea : getScreenBounds();
  4939. takeProjectPickerBackdrop (*projectPickerView, area);
  4940. projectPickerView->setBounds (area);
  4941. projectPickerView->addToDesktop (0); // (no frame, not on the taskbar)
  4942. projectPickerView->setVisible (true);
  4943. projectPickerView->toFront (true);
  4944. projectPickerView->grabKeyboardFocus();
  4945. }
  4946. void MainComponent::showQuickAdd()
  4947. {
  4948. QuickAddTargets targets;
  4949. targets.effectsFirst = workspace.getFocused() == Panel::mixer;
  4950. targets.addInstrument = [this] (ChannelDef c) {
  4951. rack.addChannel (std::move (c), true);
  4952. showPanel (Panel::channelRack);
  4953. };
  4954. targets.addEffect = [this] (EffectSlot slot) {
  4955. if (! mixer.addEffectToSelected (std::move (slot)))
  4956. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Quick-add palette"),
  4957. tr ("The selected insert has no free effect slot."));
  4958. else
  4959. showPanel (Panel::mixer);
  4960. };
  4961. openToolWindow (makeQuickAddPalette (engine, std::move (targets)), tr ("Quick-add palette"), "quickadd");
  4962. }
  4963. std::unique_ptr<juce::Component> MainComponent::makeQuickAddForSnapshot()
  4964. {
  4965. QuickAddTargets targets;
  4966. targets.addInstrument = [] (ChannelDef) {};
  4967. targets.addEffect = [] (EffectSlot) {};
  4968. return makeQuickAddPalette (engine, std::move (targets));
  4969. }
  4970. // --- round 190ch: Lyrics / Notes and Reference match ------------------------------------------------------------------
  4971. bool MainComponent::isLyricsShowing() const
  4972. {
  4973. return (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr) || lyricsWindowPanel != nullptr;
  4974. }
  4975. LyricsPanel* MainComponent::getLyricsPanelForSnapshot()
  4976. {
  4977. showLyrics (false);
  4978. return static_cast<LyricsPanel*> (lyricsDock.get());
  4979. }
  4980. void MainComponent::hideLyrics()
  4981. {
  4982. if (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr)
  4983. {
  4984. static_cast<LyricsPanel&> (*lyricsDock).commit();
  4985. playlistArea.setSideDock (nullptr, 0);
  4986. }
  4987. if (lyricsWindowPanel != nullptr)
  4988. closeToolWindowOf (*lyricsWindowPanel);
  4989. }
  4990. void MainComponent::toggleLyrics()
  4991. {
  4992. if (isLyricsShowing())
  4993. hideLyrics();
  4994. else
  4995. showLyrics (false);
  4996. }
  4997. void MainComponent::showLyrics (bool floating)
  4998. {
  4999. hideLyrics();
  5000. if (floating)
  5001. {
  5002. LyricsPanel::Hooks hooks;
  5003. hooks.toggleFloating = [this] { juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  5004. if (safe != nullptr)
  5005. safe->showLyrics (false);
  5006. }); };
  5007. auto panel = std::make_unique<LyricsPanel> (engine, std::move (hooks));
  5008. panel->setFloating (true);
  5009. panel->setSize (420, 560);
  5010. lyricsWindowPanel = panel.get();
  5011. openToolWindow (std::move (panel), tr ("Lyrics and notes"), "lyrics");
  5012. return;
  5013. }
  5014. if (lyricsDock == nullptr)
  5015. {
  5016. LyricsPanel::Hooks hooks;
  5017. hooks.close = [this] { hideLyrics(); };
  5018. hooks.toggleFloating = [this] { juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  5019. if (safe != nullptr)
  5020. safe->showLyrics (true);
  5021. }); };
  5022. lyricsDock = std::make_unique<LyricsPanel> (engine, std::move (hooks));
  5023. }
  5024. // the dock on the right of the Playlist is one place: the Simple workflow's Finish dock gives way
  5025. if (simpleWorkflow != nullptr && simpleWorkflow->isFinishShowing())
  5026. simpleWorkflow->hideFinish();
  5027. static_cast<LyricsPanel&> (*lyricsDock).refresh();
  5028. if (! workspace.isPanelVisible (Panel::playlist))
  5029. {
  5030. workspace.show (Panel::playlist);
  5031. refreshPanelButtons();
  5032. }
  5033. playlistArea.setSideDock (lyricsDock.get(), LyricsPanel::width);
  5034. }
  5035. // Round 190lx (DS-42, capture 190lr B21): BandLab's Sounds panel docks on the right from the timeline's top down to the
  5036. // bottom bar, 401 px wide, and narrows the timeline and the track dock under it (the Playlist area's side dock does both).
  5037. // It shares that place with Lyrics / Notes and the Finish dock: the one shown last stays.
  5038. void MainComponent::showLoopsDock()
  5039. {
  5040. if (loopsDock == nullptr)
  5041. loopsDock = BrowserComponent::makeLoopsDock (engine, [this] (BrowserComponent& b) { connectBrowser (b); }, [this] {
  5042. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  5043. if (safe != nullptr)
  5044. safe->hideLoopsDock();
  5045. });
  5046. });
  5047. else if (auto* b = BrowserComponent::browserOfLoopsDock (loopsDock.get()))
  5048. b->setLoopsShown (true);
  5049. if (isLoopsDockShowing())
  5050. return;
  5051. if (simpleWorkflow != nullptr && simpleWorkflow->isFinishShowing())
  5052. simpleWorkflow->hideFinish();
  5053. if (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr)
  5054. static_cast<LyricsPanel&> (*lyricsDock).commit();
  5055. if (! workspace.isPanelVisible (Panel::playlist))
  5056. {
  5057. workspace.show (Panel::playlist);
  5058. refreshPanelButtons();
  5059. }
  5060. playlistArea.setSideDock (loopsDock.get(), BrowserComponent::loopsDockWidth);
  5061. }
  5062. void MainComponent::hideLoopsDock()
  5063. {
  5064. if (isLoopsDockShowing())
  5065. playlistArea.setSideDock (nullptr, 0);
  5066. }
  5067. void MainComponent::showReferenceMatch()
  5068. {
  5069. if (auto* open = findToolWindow ("referenceMatch"))
  5070. {
  5071. open->toFront (true);
  5072. return;
  5073. }
  5074. ReferenceMatchPanel::Hooks hooks;
  5075. hooks.showMaster = [this] {
  5076. workspace.show (Panel::mixer);
  5077. mixer.selectTrack (0);
  5078. refreshPanelButtons();
  5079. };
  5080. auto panel = std::make_unique<ReferenceMatchPanel> (engine, std::move (hooks));
  5081. referenceMatchPanel = panel.get();
  5082. openToolWindow (std::move (panel), tr ("Reference match"), "referenceMatch");
  5083. }
  5084. void MainComponent::commitSongNotes()
  5085. {
  5086. if (lyricsDock != nullptr)
  5087. static_cast<LyricsPanel&> (*lyricsDock).commit();
  5088. if (auto* panel = dynamic_cast<LyricsPanel*> (lyricsWindowPanel.getComponent()))
  5089. panel->commit();
  5090. }
  5091. // FL's General › Hints and warnings › "Project data size warning" (round 190mr, DF-147): a project saved larger than the
  5092. // chosen size says so once per save (FL: plugins that keep sample data in the project make it big). Off = "Don't warn me".
  5093. void MainComponent::warnIfProjectTooBig (const juce::File& file)
  5094. {
  5095. const auto limit = flsettings::options().projectSizeWarnMb.load();
  5096. const auto bytes = (long long) file.getSize();
  5097. if (! flsettings::projectTooBig (bytes, limit))
  5098. return;
  5099. platform::testModeLog ("project data size warning");
  5100. if (platform::testMode())
  5101. return;
  5102. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Project data size warning"),
  5103. tr ("{0} was saved at {1} MB, more than the {2} MB set in Settings › General › Project data size "
  5104. "warning. Audio kept inside the project (recordings in the audio editor, sliced samples) "
  5105. "makes it large; File › Export project with samples keeps such audio as files instead.",
  5106. { file.getFileName(), juce::String ((double) bytes / (1024.0 * 1024.0), 1), juce::String (limit) }));
  5107. }
  5108. // FL's toolbar (manual, Toolbar shortcut icons: "drag a sample onto the Channel Rack button to automatically reveal it";
  5109. // round 190mr, DF-34): while something is dragged inside LYNX (a Browser file, a clip, a channel), the window button under
  5110. // it shows its window in front, once each time the drag enters a button. Nothing is read while no drag runs.
  5111. void MainComponent::showExtendedHint (bool on)
  5112. {
  5113. if (on == (extendedHint != nullptr))
  5114. return;
  5115. if (! on)
  5116. extendedHint = nullptr;
  5117. else
  5118. {
  5119. auto panel = std::make_unique<ui::ExtendedHintPanel>();
  5120. panel->onMoved = [this] (juce::Point<int> at) {
  5121. extendedHintOffset = { at.x - workspace.getX(), workspace.getBottom() - (at.y + ui::ExtendedHintPanel::panelHeight) };
  5122. saveUiSettings();
  5123. };
  5124. panel->setHint (hintBar.getHint(), false);
  5125. addAndMakeVisible (*panel);
  5126. extendedHint = std::move (panel);
  5127. placeExtendedHint();
  5128. }
  5129. saveUiSettings();
  5130. }
  5131. void MainComponent::placeExtendedHint()
  5132. {
  5133. if (extendedHint == nullptr)
  5134. return;
  5135. // FL's corner: the panel's left end just past the window's edge, its bottom on the desktop's
  5136. const auto offset = extendedHintOffset.x < -1000 || extendedHintOffset.y < 0 ? juce::Point<int> (-4, 2) : extendedHintOffset;
  5137. extendedHint->setTopLeftPosition (workspace.getX() + offset.x, workspace.getBottom() - offset.y - ui::ExtendedHintPanel::panelHeight);
  5138. extendedHint->toFront (false);
  5139. }
  5140. void MainComponent::revealPanelUnderDrag()
  5141. {
  5142. if (! isDragAndDropActive())
  5143. {
  5144. dragRevealPanel = -1;
  5145. return;
  5146. }
  5147. const auto at = juce::Desktop::getMousePosition();
  5148. auto over = -1;
  5149. for (int i = 0; i < workspace::panelCount; ++i)
  5150. if (const auto& b = panelButtons[(std::size_t) i]; b.isShowing() && b.getScreenBounds().contains (at))
  5151. over = i;
  5152. if (over == std::exchange (dragRevealPanel, over) || over < 0)
  5153. return;
  5154. workspace.show ((Panel) over);
  5155. platform::testModeLog ("drag revealed panel " + juce::String (over));
  5156. }
  5157. ProjectFile::WindowLayout MainComponent::currentWindowLayout() const
  5158. {
  5159. if (! persistent && ! layoutInSaves) // (the command-line modes: no layout of their own to keep)
  5160. return {};
  5161. return { (int) layoutStyle, workspace.getLayoutText() };
  5162. }
  5163. void MainComponent::applyProjectWindowLayout (const ProjectFile::WindowLayout& layout)
  5164. {
  5165. // FL opens a project with the windows where they were saved; LYNX does so for the layout style the project was saved
  5166. // in (each style keeps a layout of its own), and only when the option is on (on, as FL)
  5167. if ((! persistent && ! layoutInSaves) || layout.text.isEmpty() || layout.style != (int) layoutStyle
  5168. || ! flsettings::options().projectWindowLayout.load())
  5169. return;
  5170. if (workspace.applyLayoutText (layout.text))
  5171. platform::testModeLog ("project window layout applied");
  5172. }
  5173. void MainComponent::refreshSongNotes()
  5174. {
  5175. if (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr)
  5176. static_cast<LyricsPanel&> (*lyricsDock).refresh();
  5177. if (auto* panel = dynamic_cast<LyricsPanel*> (lyricsWindowPanel.getComponent()))
  5178. panel->refresh();
  5179. if (auto* panel = dynamic_cast<ReferenceMatchPanel*> (referenceMatchPanel.getComponent()))
  5180. panel->refresh();
  5181. }
  5182. void MainComponent::showHistory()
  5183. {
  5184. if (auto* open = findToolWindow ("history"))
  5185. {
  5186. open->toFront (true);
  5187. return;
  5188. }
  5189. openToolWindow (makeHistoryPanel (engine), tr ("Undo history"), "history");
  5190. }
  5191. // --- recording options ---------------------------------------------------------------------------
  5192. void MainComponent::updateRecordQuantise()
  5193. {
  5194. // the global grid sets the record quantise; "none" and the zoom-dependent grids record as played
  5195. std::int64_t ticks = 0;
  5196. // (the grid is kept even with "Note start time" off: "Note end time" uses it too)
  5197. {
  5198. const auto& option = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  5199. if (option.kind == grid::Kind::ticks)
  5200. ticks = option.ticks;
  5201. else if (option.kind == grid::Kind::bar)
  5202. ticks = engine.getSong().barTicks();
  5203. }
  5204. if (engine.getRecordOptions().quantise != ticks || engine.getRecordOptions().quantiseStarts != recordQuantiseOn)
  5205. {
  5206. auto o = engine.getRecordOptions();
  5207. o.quantise = ticks;
  5208. o.quantiseStarts = recordQuantiseOn;
  5209. engine.setRecordOptions (o);
  5210. }
  5211. }
  5212. void MainComponent::addRecordQuantizeItems (juce::PopupMenu& menu)
  5213. {
  5214. const auto o = engine.getRecordOptions();
  5215. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  5216. auto options = engine.getRecordOptions();
  5217. change (options);
  5218. engine.setRecordOptions (options);
  5219. saveUiSettings();
  5220. };
  5221. // FL's record menu "Quantize" items (REA round 139), to the global snap
  5222. menu.addItem (tr ("Note start time"), ! o.toStepSequencer, recordQuantiseOn && ! o.toStepSequencer, [this] {
  5223. recordQuantiseOn = ! recordQuantiseOn;
  5224. updateRecordQuantise();
  5225. saveUiSettings();
  5226. });
  5227. menu.addItem (tr ("Note end time"), ! o.toStepSequencer, o.noteEnd == NoteEnd::quantize && ! o.toStepSequencer, [set] {
  5228. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::quantize ? NoteEnd::keepEnd : NoteEnd::quantize; });
  5229. });
  5230. menu.addItem (tr ("Leave note duration"), ! o.toStepSequencer, o.noteEnd == NoteEnd::keepLength && ! o.toStepSequencer, [set] {
  5231. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::keepLength ? NoteEnd::keepEnd : NoteEnd::keepLength; });
  5232. });
  5233. menu.addItem (tr ("Record to step sequencer"), true, o.toStepSequencer,
  5234. [set] { set ([] (AudioEngine::RecordOptions& r) { r.toStepSequencer = ! r.toStepSequencer; }); });
  5235. // FL's "Automations" (RecQuantizeAutomationsMenu, setting QuantizeAutomations; REA round 143): recorded automation
  5236. // points go to the snap
  5237. menu.addItem (tr ("Automations"), true, o.quantiseAutomation,
  5238. [set] { set ([] (AudioEngine::RecordOptions& r) { r.quantiseAutomation = ! r.quantiseAutomation; }); });
  5239. }
  5240. // The count-in lengths (the record menu's submenu, and FL's right-click on the Count-in button, round 190ld)
  5241. juce::PopupMenu MainComponent::makeCountInMenu()
  5242. {
  5243. const auto o = engine.getRecordOptions();
  5244. auto set = [this] (int bars) {
  5245. auto options = engine.getRecordOptions();
  5246. options.countInBars = bars;
  5247. engine.setRecordOptions (options);
  5248. refreshRecordOptionButtons();
  5249. saveUiSettings();
  5250. };
  5251. juce::PopupMenu countIn;
  5252. countIn.addItem (tr ("Off"), true, o.countInBars == 0, [set] { set (0); });
  5253. for (int bars : { 1, 2, 4 })
  5254. countIn.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, o.countInBars == bars, [set, bars] { set (bars); });
  5255. return countIn;
  5256. }
  5257. // FL's Wait for input right-click (round 190ld)
  5258. juce::PopupMenu MainComponent::makeWaitInputMenu()
  5259. {
  5260. const auto o = engine.getRecordOptions();
  5261. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  5262. auto options = engine.getRecordOptions();
  5263. change (options);
  5264. engine.setRecordOptions (options);
  5265. refreshRecordOptionButtons();
  5266. saveUiSettings();
  5267. };
  5268. juce::PopupMenu menu;
  5269. menu.addItem (tr ("Only when recording"), true, o.waitOnlyWhenRecording,
  5270. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitOnlyWhenRecording = ! r.waitOnlyWhenRecording; }); });
  5271. menu.addItem (tr ("Respect recording filter"), true, o.waitRespectFilter,
  5272. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitRespectFilter = ! r.waitRespectFilter; }); });
  5273. return menu;
  5274. }
  5275. void MainComponent::addRecordOptions (juce::PopupMenu& menu)
  5276. {
  5277. const auto o = engine.getRecordOptions();
  5278. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  5279. auto options = engine.getRecordOptions();
  5280. change (options);
  5281. engine.setRecordOptions (options);
  5282. refreshRecordOptionButtons();
  5283. saveUiSettings();
  5284. };
  5285. menu.addSubMenu (tr ("Count-in") + shortcutText ("record.countIn"), makeCountInMenu());
  5286. menu.addItem (tr ("Wait for the first note to start") + shortcutText ("record.waitForInput"), true, o.waitForInput,
  5287. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitForInput = ! r.waitForInput; }); });
  5288. menu.addItem (tr ("Loop record") + shortcutText ("record.loop"), true, o.loopRecord,
  5289. [set] { set ([] (AudioEngine::RecordOptions& r) { r.loopRecord = ! r.loopRecord; }); });
  5290. menu.addItem (tr ("After loop recording, only the last pass plays"), true, o.lastLoopPassPlays,
  5291. [set] { set ([] (AudioEngine::RecordOptions& r) { r.lastLoopPassPlays = ! r.lastLoopPassPlays; }); });
  5292. menu.addItem (tr ("Step edit") + shortcutText ("record.stepEdit"), true, engine.isStepEdit(), [this] { runAction ("record.stepEdit"); });
  5293. // round 170d: notes played during the count-in are kept; the ones just before the start go onto it
  5294. {
  5295. juce::PopupMenu catchMenu;
  5296. catchMenu.addItem (tr ("Off (keep their real time)"), true, o.catchWindow == 0,
  5297. [set] { set ([] (AudioEngine::RecordOptions& r) { r.catchWindow = 0; }); });
  5298. const std::pair<std::int64_t, const char*> windows[] = { { ppq / 8, TR_NOOP ("1/32 note") },
  5299. { ppq / 4, TR_NOOP ("1/16 note") },
  5300. { ppq / 2, TR_NOOP ("1/8 note") },
  5301. { ppq, TR_NOOP ("1/4 note") } };
  5302. for (const auto& [ticks, name] : windows)
  5303. catchMenu.addItem (tr (name), true, o.catchWindow == ticks,
  5304. [set, ticks = ticks] { set ([ticks] (AudioEngine::RecordOptions& r) { r.catchWindow = ticks; }); });
  5305. menu.addSubMenu (tr ("Notes played just before the start go onto it"), catchMenu);
  5306. }
  5307. menu.addItem (tr ("Played notes: compensate the output latency"), true, o.compensateOutput,
  5308. [set] { set ([] (AudioEngine::RecordOptions& r) { r.compensateOutput = ! r.compensateOutput; }); });
  5309. menu.addItem (tr ("Capture MIDI: the notes just played without recording into the pattern") + shortcutText ("record.captureMidi"),
  5310. [this] { runAction ("record.captureMidi"); });
  5311. // round 163: punch in/out on the loop region, pre-roll and post-roll (bars)
  5312. {
  5313. auto bars = [&set] (juce::PopupMenu& m, int now, std::function<void (AudioEngine::RecordOptions&, int)> apply) {
  5314. m.addItem (tr ("Off"), true, now == 0, [set, apply] { set ([apply] (AudioEngine::RecordOptions& r) { apply (r, 0); }); });
  5315. for (int n : { 1, 2, 4 })
  5316. m.addItem (n == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (n) }), true, now == n,
  5317. [set, apply, n] { set ([apply, n] (AudioEngine::RecordOptions& r) { apply (r, n); }); });
  5318. };
  5319. juce::PopupMenu pre, post;
  5320. bars (pre, o.preRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.preRollBars = n; });
  5321. bars (post, o.postRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.postRollBars = n; });
  5322. menu.addItem (tr ("Audio: punch in/out on the loop region (plays through it, keeps only the region)"), true, o.punchLoopRegion,
  5323. [set] { set ([] (AudioEngine::RecordOptions& r) { r.punchLoopRegion = ! r.punchLoopRegion; }); });
  5324. menu.addSubMenu (tr ("Audio: pre-roll (plays before the punch-in or the start position)"), pre);
  5325. menu.addSubMenu (tr ("Audio: post-roll (plays after the punch-out, then stops)"), post);
  5326. }
  5327. menu.addSeparator();
  5328. menu.addItem (tr ("Overdub: add to the pattern"), true, o.mode == RecordMode::overdub,
  5329. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::overdub; }); });
  5330. menu.addItem (tr ("Replace: a recorded channel's old notes are cleared"), true, o.mode == RecordMode::replace,
  5331. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::replace; }); });
  5332. menu.addSeparator();
  5333. {
  5334. juce::PopupMenu quantize;
  5335. addRecordQuantizeItems (quantize);
  5336. menu.addSubMenu (tr ("Quantize recorded notes to the global snap"), quantize);
  5337. }
  5338. menu.addItem (tr ("Song mode: place a pattern clip where recording starts"), true, o.placeSongClip,
  5339. [set] { set ([] (AudioEngine::RecordOptions& r) { r.placeSongClip = ! r.placeSongClip; }); });
  5340. }
  5341. void MainComponent::toggleRecording()
  5342. {
  5343. if (engine.isRecording())
  5344. {
  5345. engine.setRecording (false);
  5346. return;
  5347. }
  5348. // round 190mk (DF-6, FL): Alt+click on Record asks "What would you like to record?" even when the question is off
  5349. const auto altAsks = juce::ModifierKeys::currentModifiers.isAltDown();
  5350. if ((! engine.getRecordOptions().askWhatToRecord && ! altAsks) || ! persistent)
  5351. {
  5352. engine.setRecording (true);
  5353. if (engine.getRecordOptions().startsPlayback && ! engine.getTransport().playing.load()) // FL's "Recording starts playback"
  5354. engine.startPlayback();
  5355. checkRecordTip(); // (round 190np)
  5356. return;
  5357. }
  5358. juce::Component::SafePointer<MainComponent> safe (this);
  5359. showRecordChoiceDialog ([safe] (int choice, bool dontAsk) {
  5360. if (safe == nullptr)
  5361. return;
  5362. if (choice == recordChoiceAudioEditor)
  5363. {
  5364. openAudioEditorRecording (safe->engine);
  5365. if (! safe->engine.getTransport().playing.load())
  5366. safe->engine.play();
  5367. return;
  5368. }
  5369. auto o = safe->engine.getRecordOptions();
  5370. o.recordNotes = choice != recordChoiceAudio;
  5371. o.recordAudio = choice != recordChoiceNotes;
  5372. o.recordAutomation = choice != recordChoiceAudio;
  5373. if (dontAsk)
  5374. o.askWhatToRecord = false;
  5375. safe->engine.setRecordOptions (o);
  5376. if (dontAsk)
  5377. safe->saveUiSettings();
  5378. if (choice == recordChoiceAudio && safe->engine.getArmedInserts().empty())
  5379. safe->armSelectedInsertForAudio();
  5380. safe->engine.setRecording (true);
  5381. if (o.startsPlayback && ! safe->engine.getTransport().playing.load()) // FL's "Recording starts playback"
  5382. safe->engine.startPlayback();
  5383. safe->checkRecordTip(); // (round 190np)
  5384. });
  5385. }
  5386. // Round 163: the fastest way from "press record" to a clip on the Playlist — one key arms the selected insert (or the
  5387. // one with an input), records audio only (no question) and starts playback (count-in / pre-roll as set); pressed
  5388. // again it stops, and the take is on the Playlist.
  5389. void MainComponent::quickRecordAudio()
  5390. {
  5391. auto& transport = engine.getTransport();
  5392. if (engine.isRecording() && (transport.playing.load() || engine.isCountingIn() || engine.isWaitingForInput()))
  5393. {
  5394. engine.stop();
  5395. engine.setRecording (false);
  5396. return;
  5397. }
  5398. if (engine.getArmedInserts().empty())
  5399. armSelectedInsertForAudio();
  5400. if (engine.getArmedInserts().empty()) // no input yet: its menu is open, nothing to record
  5401. return;
  5402. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  5403. {
  5404. o.recordAudio = true;
  5405. engine.setRecordOptions (o);
  5406. }
  5407. engine.setRecording (true);
  5408. if (! transport.playing.load())
  5409. engine.startPlayback();
  5410. }
  5411. void MainComponent::oneClickRecord (int into)
  5412. {
  5413. // FL: FUN_0120d380 (round 190dx, /mnt/e/lynx-work/flpl190dx/FL-FACTS.md item 20)
  5414. const auto plan = oneclick::plan (engine.getSong(), engine.getArmedInserts(), this->mixer.getStripsForSnapshot().getSelectedTrack(),
  5415. (oneclick::Into) into);
  5416. if (plan.insert > 0)
  5417. {
  5418. showPanel (Panel::mixer);
  5419. this->mixer.selectTrack (plan.insert);
  5420. }
  5421. if (plan.loadEdison)
  5422. {
  5423. // FL loads Edison set to record on play on the selected mixer track (its "Open audio editor and record"), then plays
  5424. this->mixer.runAction ("mixer.audioEditorRecord");
  5425. if (! engine.getTransport().playing.load())
  5426. engine.startPlayback();
  5427. return;
  5428. }
  5429. if (! plan.recordOn)
  5430. return;
  5431. const auto start = [this] {
  5432. if (engine.getSong().mode != PlayMode::song) // FL switches to Song mode
  5433. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  5434. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  5435. {
  5436. o.recordAudio = true;
  5437. engine.setRecordOptions (o);
  5438. }
  5439. engine.setRecording (true);
  5440. if (! engine.getTransport().playing.load())
  5441. engine.startPlayback();
  5442. };
  5443. if (plan.armInsert && plan.askInput)
  5444. {
  5445. // FL asks for the selected mixer track's input first; nothing records until one is picked
  5446. mixerinput::showMenu (engine, plan.insert, &this->mixer, [this, insert = plan.insert, start] {
  5447. engine.setInsertArmed (insert, true);
  5448. start();
  5449. });
  5450. return;
  5451. }
  5452. if (plan.armInsert)
  5453. engine.setInsertArmed (plan.insert, true);
  5454. start();
  5455. }
  5456. void MainComponent::armSelectedInsertForAudio()
  5457. {
  5458. const auto& mixer = engine.getSong().mixer;
  5459. // the selected insert, else the first one with an input, else a free one
  5460. auto target = this->mixer.getStripsForSnapshot().getSelectedTrack();
  5461. for (int t = 1; target <= 0 && t < (int) mixer.size(); ++t)
  5462. if (mixer[(std::size_t) t].inputChannel >= 0)
  5463. target = t;
  5464. if (target <= 0)
  5465. target = engine.getSong().nextFreeInsert();
  5466. if (target <= 0 || target >= (int) mixer.size())
  5467. return;
  5468. showPanel (Panel::mixer);
  5469. this->mixer.selectTrack (target);
  5470. if (engine.isInsertArmed (target))
  5471. return;
  5472. // this menu item says "(choose its input)": without one, the input menu comes first and arms after the choice
  5473. if (mixer[(std::size_t) target].inputChannel < 0)
  5474. mixerinput::showMenu (engine, target, &this->mixer, [this, target] { engine.setInsertArmed (target, true); });
  5475. else
  5476. mixerinput::toggleArm (engine, target, &this->mixer);
  5477. }
  5478. // Round 190lr (DL-49, Live manual 9.1.2): each click on the Tap box is a beat; from the second tap the song takes the
  5479. // tapped tempo (core/ValueMath.h TapTempo, the tapper window's own rule); with "Start Playback with Tap Tempo" on, "it
  5480. // takes four taps to start song playback at the tapped tempo"
  5481. void MainComponent::liveTap()
  5482. {
  5483. const auto now = juce::Time::getMillisecondCounterHiRes();
  5484. if (const auto bpm = liveTaps.tap (now); bpm && std::abs (*bpm - engine.getSong().bpm) > 1e-9)
  5485. engine.editSong ([b = *bpm] (Song& s) { clipops::followTempo (s, b); });
  5486. if (tapStartsPlayback && liveTaps.count() == 4 && ! engine.getTransport().playing.load())
  5487. engine.play();
  5488. }
  5489. void MainComponent::showLiveTapMenu()
  5490. {
  5491. makeLiveTapMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&tapTempoButton));
  5492. }
  5493. juce::PopupMenu MainComponent::makeLiveTapMenu()
  5494. {
  5495. juce::PopupMenu menu;
  5496. menu.addItem (tr ("Start Playback with Tap Tempo"), true, tapStartsPlayback, [this] {
  5497. tapStartsPlayback = ! tapStartsPlayback;
  5498. saveUiSettings();
  5499. });
  5500. menu.addSeparator();
  5501. menu.addItem (tr ("Tempo tapper") + shortcutText ("view.tempoTapper"), [this] { openTempoTapper (engine); });
  5502. return menu;
  5503. }
  5504. void MainComponent::showMetronomeMenu()
  5505. {
  5506. makeMetronomeMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&metronomeButton));
  5507. }
  5508. juce::PopupMenu MainComponent::makeMetronomeMenu()
  5509. {
  5510. // FL 2026's right-click on the metronome button, as it is (REA round 165z-a2): the "Metronome sound" choice only,
  5511. // in FL's order. The volume trim is in Options, the count-in has its own button and the track the click plays
  5512. // through is in Settings › Audio › Mixer.
  5513. auto& transport = engine.getTransport();
  5514. juce::PopupMenu menu;
  5515. menu.addSectionHeader (tr ("Metronome sound"));
  5516. for (int i = 0; i < metronome::soundCount; ++i)
  5517. menu.addItem (tr (metronome::soundName (i)), true, metronome::clampSound (transport.metronomeSound.load()) == i, [this, i] {
  5518. engine.getTransport().metronomeSound.store (i);
  5519. saveUiSettings();
  5520. });
  5521. // round 190lr (DL-47): Live's metronome menu ends with "Enable Only While Recording" (details2_190ld capture L13);
  5522. // in the Clip-launch layout it follows FL's choice (add, never remove)
  5523. if (isClipLaunchWorkflow())
  5524. {
  5525. menu.addSeparator();
  5526. menu.addItem (tr ("Enable Only While Recording"), true, transport.metronomeOnlyRecording.load(), [this] {
  5527. auto& t = engine.getTransport();
  5528. t.metronomeOnlyRecording.store (! t.metronomeOnlyRecording.load());
  5529. saveUiSettings();
  5530. });
  5531. }
  5532. return menu;
  5533. }
  5534. void MainComponent::showTypingPianoMenu()
  5535. {
  5536. // FL 2026's right-click on the typing keyboard button (KbToMIDIPopup, measured round 168t2): Root note C..B,
  5537. // Octave 2..6 (where the Z row starts), Options › Reset, Layout (FL's .scr names and order, core/KeyMap.h).
  5538. // FL's Reset (KbToMIDIResetClick 0x121ac70) releases the held notes and puts Root note C, Octave 4 and Layout Piano back.
  5539. static const char* const names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  5540. juce::PopupMenu menu;
  5541. menu.addSectionHeader (tr ("Root note"));
  5542. for (int r = 0; r < 12; ++r)
  5543. menu.addItem (names[r], true, typingRoot == r, [this, r] { typingRoot = r; saveUiSettings(); });
  5544. menu.addSectionHeader (tr ("Octave"));
  5545. for (int o = keys::typingpiano::minOctave; o <= keys::typingpiano::maxOctave; ++o)
  5546. menu.addItem (juce::String (o), true, typingOctave == o, [this, o] { typingOctave = o; saveUiSettings(); });
  5547. menu.addSectionHeader (tr ("Options"));
  5548. menu.addItem (tr ("Reset"), [this] {
  5549. heldKeys.releaseAll();
  5550. releaseTypingLaunches (true);
  5551. typingOctave = keys::typingpiano::defaultOctave;
  5552. typingRoot = 0;
  5553. typingLayout = keys::typingpiano::pianoLayout();
  5554. saveUiSettings();
  5555. });
  5556. menu.addSectionHeader (tr ("Layout"));
  5557. for (int l = 0; l < keys::typingpiano::layoutCount(); ++l) // (FL's file names, untranslated as in FL)
  5558. menu.addItem (keys::typingpiano::layoutName (l), true, typingLayout == l, [this, l] {
  5559. heldKeys.releaseAll(); // a held key's notes belong to the old layout
  5560. releaseTypingLaunches (true);
  5561. typingLayout = l;
  5562. saveUiSettings();
  5563. });
  5564. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&typingPianoButton));
  5565. }
  5566. void MainComponent::dumpScoreLog (int minutes)
  5567. {
  5568. const auto& song = engine.getSong();
  5569. scorelog::DumpOptions options;
  5570. options.minutes = minutes;
  5571. options.bpm = song.bpm;
  5572. options.beatsPerBar = song.beatsPerBar;
  5573. options.beatUnit = song.beatUnit;
  5574. auto notes = scorelog::dump (engine.scoreLogSnapshot(), options);
  5575. // (channels deleted since the notes were played are left out)
  5576. notes.erase (std::remove_if (notes.begin(), notes.end(), [&song] (const Note& n) { return n.channel < 0 || n.channel >= (int) song.channels.size(); }),
  5577. notes.end());
  5578. if (notes.empty())
  5579. {
  5580. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Score logger"),
  5581. tr ("The score log is empty: no notes were played on a MIDI keyboard or the typing keyboard in that time."));
  5582. return;
  5583. }
  5584. auto apply = [this] (std::vector<Note> logged, bool replace) {
  5585. const auto count = logged.size();
  5586. engine.editSong ([&logged, replace] (Song& s) {
  5587. if (s.patterns.empty())
  5588. s.patterns.emplace_back();
  5589. s.currentPattern = juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern);
  5590. auto& pattern = s.activePattern();
  5591. if (replace)
  5592. pattern.notes.clear();
  5593. pattern.notes.insert (pattern.notes.end(), logged.begin(), logged.end());
  5594. pattern.sortNotes();
  5595. });
  5596. ui::postHint ({ tr ("Score log: {0} notes put in the pattern", { juce::String ((int) count) }), {}, false, false }, 4000);
  5597. };
  5598. const auto& patterns = song.patterns;
  5599. const auto current = song.currentPattern;
  5600. if (current < 0 || current >= (int) patterns.size() || patterns[(std::size_t) current].notes.empty())
  5601. {
  5602. apply (std::move (notes), false);
  5603. return;
  5604. }
  5605. auto box = juce::MessageBoxOptions()
  5606. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  5607. .withTitle (tr ("Score logger"))
  5608. .withMessage (tr ("The current pattern isn't empty. Do you want the score log to be merged, or to replace the current content?"))
  5609. .withButton (tr ("Merge"))
  5610. .withButton (tr ("Replace"))
  5611. .withButton (tr ("Cancel"));
  5612. juce::AlertWindow::showAsync (box, [apply, notes] (int result) mutable {
  5613. if (result == 1 || result == 2)
  5614. apply (std::move (notes), result == 2);
  5615. });
  5616. }
  5617. void MainComponent::showMetronomeVolume()
  5618. {
  5619. // a callout with the volume knob; the click plays at the new level at once (Transport::metronomeVolume)
  5620. struct VolumePanel final : public juce::Component
  5621. {
  5622. VolumePanel (MainComponent& m) : owner (m)
  5623. {
  5624. title.setText (tr ("Metronome volume"), juce::dontSendNotification);
  5625. title.setJustificationType (juce::Justification::centred);
  5626. addAndMakeVisible (title);
  5627. knob.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  5628. knob.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 120, 18);
  5629. knob.setRange (0.0, controls::maxUtilityVolume, 0.01);
  5630. knob.setDoubleClickReturnValue (true, 1.0);
  5631. knob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  5632. knob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  5633. knob.setValue (owner.engine.getTransport().metronomeVolume.load(), juce::dontSendNotification);
  5634. knob.onValueChange = [this] { owner.engine.getTransport().metronomeVolume.store ((float) knob.getValue()); };
  5635. knob.onDragEnd = [this] { owner.saveUiSettings(); };
  5636. ui::setHint (knob, tr ("Metronome volume: 100% is the default click level, up to 125% [2xLMB] 100%"));
  5637. addAndMakeVisible (knob);
  5638. setSize (170, 150);
  5639. }
  5640. ~VolumePanel() override { owner.saveUiSettings(); }
  5641. void resized() override
  5642. {
  5643. auto r = getLocalBounds().reduced (8);
  5644. title.setBounds (r.removeFromTop (20));
  5645. knob.setBounds (r);
  5646. }
  5647. MainComponent& owner;
  5648. juce::Label title;
  5649. juce::Slider knob;
  5650. };
  5651. juce::CallOutBox::launchAsynchronously (std::make_unique<VolumePanel> (*this), metronomeButton.getScreenBounds(), nullptr);
  5652. }
  5653. void MainComponent::openMasterAudioEditor (bool newOne)
  5654. {
  5655. // FL (capture 190mv A9): the button puts Edison into the Master's first empty slot and opens it ("Edison (Master)");
  5656. // the right button a new instance. A Master with an audio editor already opens that one on a left click.
  5657. const auto& master = engine.getSong().mixer;
  5658. if (master.empty())
  5659. return;
  5660. if (! newOne)
  5661. {
  5662. const auto& effects = master.front().effects;
  5663. for (int i = 0; i < (int) effects.size(); ++i)
  5664. if (effects[(std::size_t) i].kind == EffectKind::edison)
  5665. {
  5666. openEdisonSlot (engine, 0, i);
  5667. return;
  5668. }
  5669. }
  5670. if (const auto at = addEdisonSlot (engine, 0); at >= 0)
  5671. openEdisonSlot (engine, 0, at);
  5672. else
  5673. openAudioEditor (engine); // (a full Master: the editor window, as the track menu's item does)
  5674. }
  5675. void MainComponent::openAudioEditorForSelection()
  5676. {
  5677. const auto& song = engine.getSong();
  5678. const auto channel = engine.getSelectedChannel();
  5679. if (juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  5680. {
  5681. const auto& c = song.channels[(std::size_t) channel];
  5682. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && ! c.samplePath.empty())
  5683. {
  5684. openAudioEditorForChannel (engine, channel);
  5685. return;
  5686. }
  5687. }
  5688. openAudioEditor (engine);
  5689. }
  5690. void MainComponent::showRecordMenu()
  5691. {
  5692. buildRecordMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (recordMenuButton.isVisible() ? (juce::Component*) &recordMenuButton
  5693. : (juce::Component*) &recordButton));
  5694. }
  5695. juce::PopupMenu MainComponent::buildRecordMenu()
  5696. {
  5697. const auto o = engine.getRecordOptions();
  5698. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  5699. auto options = engine.getRecordOptions();
  5700. change (options);
  5701. engine.setRecordOptions (options);
  5702. saveUiSettings();
  5703. };
  5704. juce::PopupMenu menu;
  5705. menu.addSectionHeader (tr ("Recording filter"));
  5706. // FL's filter order (RecMenu, REA round 143): Automation, Notes, Audio
  5707. menu.addItem (tr ("Automation (the controls you move: automation clips in song mode, pattern events in pattern mode)"), true,
  5708. o.recordAutomation, [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAutomation = ! r.recordAutomation; }); });
  5709. menu.addItem (tr ("Notes (MIDI and PC keyboard) into the current pattern"), true, o.recordNotes,
  5710. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordNotes = ! r.recordNotes; }); });
  5711. menu.addItem (tr ("Audio of the armed mixer inserts (becomes Playlist clips)"), true, o.recordAudio,
  5712. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAudio = ! r.recordAudio; }); });
  5713. menu.addItem (tr ("Clips (Performance mode: the launched clips are written into the arrangement)"), true, o.recordClips,
  5714. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordClips = ! r.recordClips; }); });
  5715. menu.addItem (tr ("Ask what to record when recording starts"), true, o.askWhatToRecord,
  5716. [set] { set ([] (AudioEngine::RecordOptions& r) { r.askWhatToRecord = ! r.askWhatToRecord; }); });
  5717. // FL's "Options" section (REA round 134)
  5718. menu.addSectionHeader (tr ("Options"));
  5719. menu.addItem (tr ("Recording starts playback"), true, o.startsPlayback,
  5720. [set] { set ([] (AudioEngine::RecordOptions& r) { r.startsPlayback = ! r.startsPlayback; }); });
  5721. menu.addItem (tr ("Disarm on stop (recording switches off when playback stops)"), true, o.recordOffOnStop,
  5722. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordOffOnStop = ! r.recordOffOnStop; }); });
  5723. // LYNX's own (issue #16; FL has no such option): also in Mixer › Disk recording
  5724. menu.addItem (tr ("Disarm the inserts when recording stops"), true, o.disarmOnStop,
  5725. [set] { set ([] (AudioEngine::RecordOptions& r) { r.disarmOnStop = ! r.disarmOnStop; }); });
  5726. // LYNX's own (round 190aq, core/LowLatency.h; FL has no such switch): also in Mixer › Disk recording
  5727. menu.addItem (tr ("Low latency while recording (bypasses effects that add latency on armed or monitored inserts)"), true, o.lowLatencyRecording,
  5728. [set] { set ([] (AudioEngine::RecordOptions& r) { r.lowLatencyRecording = ! r.lowLatencyRecording; }); });
  5729. menu.addItem (tr ("Enable recording markers (Start / Stop recording markers in the Playlist)"), true, o.recordingMarkers,
  5730. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordingMarkers = ! r.recordingMarkers; }); });
  5731. // FL's "Quantize" section (REA round 139): to the global snap
  5732. menu.addSectionHeader (tr ("Quantize"));
  5733. addRecordQuantizeItems (menu);
  5734. menu.addItem (tr ("Record into the audio editor..."), [this] { openAudioEditor (engine); });
  5735. menu.addSeparator();
  5736. menu.addItem (tr ("Arm the selected mixer insert for audio (choose its input)..."), [this] { armSelectedInsertForAudio(); });
  5737. menu.addItem (tr ("Audio settings (input device)..."), [this] { openSettings ((int) SettingsPage::audio); });
  5738. menu.addItem (tr ("Open recordings folder"), [this] {
  5739. const auto folder = engine.getRecordingFolder();
  5740. folder.createDirectory();
  5741. folder.startAsProcess();
  5742. });
  5743. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  5744. menu.addSeparator();
  5745. addRecordOptions (menu);
  5746. return menu;
  5747. }
  5748. void MainComponent::refreshRecordOptionButtons()
  5749. {
  5750. auto withKey = [this] (const juce::String& text, const char* id) {
  5751. const auto key = shortcutText (id).trim();
  5752. return key.isEmpty() ? text : text + " (" + key + ")";
  5753. };
  5754. const auto o = engine.getRecordOptions();
  5755. countInButton.setToggleState (o.countInBars > 0, juce::dontSendNotification);
  5756. countInButton.setTooltip (withKey (o.countInBars > 0 ? tr ("Count-in before recording: {0} bar(s)", { juce::String (o.countInBars) })
  5757. : tr ("Count-in before recording: off"),
  5758. "record.countIn"));
  5759. blendButton.setToggleState (o.mode == RecordMode::overdub, juce::dontSendNotification);
  5760. {
  5761. const auto blend = o.mode == RecordMode::overdub;
  5762. auto tip = blend ? tr ("Blend recorded notes: on (new notes join the pattern's notes)")
  5763. : tr ("Blend recorded notes: off (a recorded channel's old notes are replaced)");
  5764. if (! o.lastLoopPassPlays)
  5765. tip << "\n" << (blend ? tr ("Loop-recorded audio: every pass plays") : tr ("Loop-recorded audio: every pass is muted"));
  5766. blendButton.setTooltip (tip);
  5767. }
  5768. waitInputButton.setToggleState (o.waitForInput, juce::dontSendNotification);
  5769. waitInputButton.setTooltip (withKey (o.waitForInput ? tr ("Recording waits for the first note: on") : tr ("Recording waits for the first note: off"),
  5770. "record.waitForInput"));
  5771. blendButton.setTooltip (withKey (blendButton.getTooltip(), "record.blend"));
  5772. loopRecordButton.setToggleState (o.loopRecord, juce::dontSendNotification);
  5773. loopRecordButton.setTooltip (withKey (o.loopRecord ? tr ("Loop record: on (recording loops: the loop region in Song mode, one take per pass; the pattern in Pattern mode)")
  5774. : tr ("Loop record: off (recording plays straight on: through the loop region, or past the pattern's end, which grows)"),
  5775. "record.loop"));
  5776. stepEditButton.setToggleState (engine.isStepEdit(), juce::dontSendNotification);
  5777. stepEditButton.setTooltip (withKey (engine.isStepEdit() ? tr ("Step edit: on (stopped, played notes go into the pattern one snap step after another)")
  5778. : tr ("Step edit: off"),
  5779. "record.stepEdit"));
  5780. if (toolbarLook == toolbarlayout::Look::live) // round 190lx (DL-61): Live's Punch-In switch, the Punch-Out one beside it
  5781. {
  5782. punchButton.setToggleState (o.punchLoopRegion && o.punchIn, juce::dontSendNotification);
  5783. punchButton.setTooltip (tr ("Punch-In switch: audio recording starts at the start of the loop region"));
  5784. ui::setHint (punchButton, punchButton.getTooltip());
  5785. punchHintLive = true;
  5786. punchOutButton.setToggleState (o.punchLoopRegion && o.punchOut, juce::dontSendNotification);
  5787. return;
  5788. }
  5789. if (std::exchange (punchHintLive, false))
  5790. setControlHints();
  5791. punchButton.setToggleState (o.punchLoopRegion, juce::dontSendNotification);
  5792. punchButton.setTooltip (withKey (o.punchLoopRegion ? tr ("Punch in/out: on (audio is kept only inside the loop region)") : tr ("Punch in/out: off"),
  5793. "record.punch"));
  5794. }
  5795. void MainComponent::clonePatternNow()
  5796. {
  5797. engine.editSong ([] (Song& s) { clonePattern (s, s.currentPattern); });
  5798. }
  5799. void MainComponent::movePatternNow (int delta)
  5800. {
  5801. engine.editSongPatternOrder ([delta] (Song& s) { movePattern (s, s.currentPattern, delta); });
  5802. }
  5803. void MainComponent::splitPatternByChannelNow()
  5804. {
  5805. int created = 0;
  5806. engine.editSong ([&created] (Song& s) { created = splitPatternByChannel (s, s.currentPattern); });
  5807. if (created == 0)
  5808. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Split by channel"), tr ("This pattern has no notes."));
  5809. }
  5810. void MainComponent::showRenamePattern (int index)
  5811. {
  5812. if (index < 0 || index >= (int) engine.getSong().patterns.size())
  5813. return;
  5814. const auto& p = engine.getSong().patterns[(std::size_t) index];
  5815. showNameAndColourDialog (tr ("Rename pattern"), juce::String::fromUTF8 (p.name.c_str()), p.colour,
  5816. [this, index] (const juce::String& name, std::uint32_t colour) {
  5817. if (index < (int) engine.getSong().patterns.size())
  5818. engine.editSong ([index, n = name.toStdString(), colour] (Song& s) {
  5819. s.patterns[(std::size_t) index].name = n;
  5820. s.patterns[(std::size_t) index].colour = colour;
  5821. });
  5822. });
  5823. }
  5824. void MainComponent::refreshToolbar()
  5825. {
  5826. const auto& song = engine.getSong();
  5827. patternBox.clear (juce::dontSendNotification);
  5828. for (std::size_t i = 0; i < song.patterns.size(); ++i)
  5829. patternBox.addItem (juce::String::fromUTF8 (song.patterns[i].name.c_str()), (int) i + 1);
  5830. patternBox.setSelectedItemIndex (song.currentPattern, juce::dontSendNotification);
  5831. swingSlider.setValue (song.swing, juce::dontSendNotification);
  5832. tempoDisplay.repaint();
  5833. refreshModeButton();
  5834. refreshRackPatternSelector();
  5835. refreshRackLengthBox();
  5836. }
  5837. void MainComponent::refreshRackPatternSelector()
  5838. {
  5839. const auto& song = engine.getSong();
  5840. const auto valid = song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size();
  5841. const auto text = valid ? juce::String::fromUTF8 (song.activePattern().name.c_str()) : juce::String();
  5842. const auto colour = valid ? PlaylistComponent::patternColour (song, song.currentPattern) : juce::Colour();
  5843. if (text != rackPatternSelector.text || colour != rackPatternSelector.colour)
  5844. {
  5845. rackPatternSelector.text = text;
  5846. rackPatternSelector.colour = colour;
  5847. rackPatternSelector.repaint();
  5848. }
  5849. }
  5850. void MainComponent::showRackPatternList()
  5851. {
  5852. const auto& song = engine.getSong();
  5853. juce::PopupMenu menu;
  5854. for (int i = 0; i < (int) song.patterns.size(); ++i)
  5855. menu.addItem (juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()), true, i == song.currentPattern, [this, i] { selectPattern (i); });
  5856. menu.addSeparator();
  5857. menu.addItem (tr ("New pattern"), [this] { newPatternButton.onClick(); });
  5858. menu.addItem (tr ("Rename and color the pattern") + shortcutText ("pattern.rename"), [this] { runAction ("pattern.rename"); });
  5859. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackPatternSelector));
  5860. }
  5861. // --- the Channel Rack's pattern length box (issue #12) ---------------------------------------------------------
  5862. int MainComponent::PatternLengthBox::stepBars (int value, int delta)
  5863. {
  5864. static const int steps[] = { 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 };
  5865. constexpr int count = (int) (sizeof (steps) / sizeof (steps[0]));
  5866. int i = 0;
  5867. while (i + 1 < count && steps[i + 1] <= value)
  5868. ++i;
  5869. if (delta < 0 && steps[i] < value) // between two steps: going down lands on the lower one
  5870. ++delta;
  5871. return steps[juce::jlimit (0, count - 1, i + delta)];
  5872. }
  5873. void MainComponent::PatternLengthBox::paint (juce::Graphics& g)
  5874. {
  5875. using namespace theme;
  5876. const auto area = getLocalBounds().toFloat();
  5877. g.setColour (hovered ? colour::bg3 : colour::bg1);
  5878. g.fillRoundedRectangle (area, radius::sm);
  5879. g.setColour (hovered ? colour::borderStrong : colour::border);
  5880. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  5881. auto r = getLocalBounds().reduced (3, 0);
  5882. // round 170e: a length icon instead of the letters "A" / "L" (unreadable); dim = automatic (from the notes)
  5883. icons::draw (g, Icon::span, r.removeFromLeft (13).toFloat().withSizeKeepingCentre (13.0f, 13.0f),
  5884. automatic ? colour::textDisabled : colour::textSecondary);
  5885. g.setFont (font (type::small, true));
  5886. g.setColour (automatic ? colour::textSecondary : colour::textPrimary);
  5887. g.drawText (juce::String (bars), r, juce::Justification::centred, false);
  5888. }
  5889. void MainComponent::PatternLengthBox::mouseDown (const juce::MouseEvent& e)
  5890. {
  5891. dragStartBars = bars;
  5892. if (e.mods.isPopupMenu() && onMenu)
  5893. onMenu();
  5894. }
  5895. void MainComponent::PatternLengthBox::mouseDrag (const juce::MouseEvent& e)
  5896. {
  5897. if (e.mods.isPopupMenu() || onSet == nullptr)
  5898. return;
  5899. // one step of the list per 14 px up (as the rack's insert number box: drag up = more)
  5900. const auto delta = -e.getDistanceFromDragStartY() / 14;
  5901. const auto value = delta == 0 ? dragStartBars : stepBars (dragStartBars, delta);
  5902. if (value != bars || automatic)
  5903. if (delta != 0)
  5904. onSet (value);
  5905. }
  5906. void MainComponent::PatternLengthBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  5907. {
  5908. if (onSet != nullptr && wheel.deltaY != 0.0f)
  5909. onSet (stepBars (bars, wheel.deltaY > 0.0f ? 1 : -1));
  5910. }
  5911. void MainComponent::refreshRackLengthBox()
  5912. {
  5913. const auto& song = engine.getSong();
  5914. if (song.currentPattern < 0 || song.currentPattern >= (int) song.patterns.size())
  5915. return;
  5916. const auto& pattern = song.activePattern();
  5917. const auto bar = song.barTicks();
  5918. const auto bars = (int) juce::jmax<std::int64_t> (1, (pattern.effectiveLength (song.meter()) + bar - 1) / bar);
  5919. const auto automatic = pattern.lengthTicks == 0;
  5920. if (bars != rackLengthBox.bars || automatic != rackLengthBox.automatic)
  5921. {
  5922. rackLengthBox.bars = bars;
  5923. rackLengthBox.automatic = automatic;
  5924. rackLengthBox.setTooltip (automatic ? tr ("Pattern length: {0} (automatic, from the notes)", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) })
  5925. : tr ("Pattern length: {0}", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) }));
  5926. rackLengthBox.repaint();
  5927. }
  5928. }
  5929. void MainComponent::showPatternLengthMenu()
  5930. {
  5931. const auto& song = engine.getSong();
  5932. const auto& pattern = song.activePattern();
  5933. const auto bar = song.barTicks();
  5934. juce::PopupMenu menu;
  5935. menu.addSectionHeader (tr ("Pattern length"));
  5936. menu.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0, [this] { rackLengthBox.onSet (0); });
  5937. for (int bars : { 1, 2, 4, 8, 16, 32 })
  5938. menu.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == bars * bar,
  5939. [this, bars] { rackLengthBox.onSet (bars); });
  5940. menu.addSeparator();
  5941. menu.addItem (tr ("Type value..."), [this] {
  5942. ui::ValueSpec spec;
  5943. spec.name = tr ("Pattern length (bars, 0 = automatic)");
  5944. spec.minimum = 0.0;
  5945. spec.maximum = 999.0;
  5946. spec.interval = 1.0;
  5947. ui::typeValue (rackLengthBox, spec, rackLengthBox.automatic ? 0.0 : (double) rackLengthBox.bars,
  5948. [this] (double v) { rackLengthBox.onSet (juce::roundToInt (v)); });
  5949. });
  5950. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackLengthBox));
  5951. }
  5952. void MainComponent::PatternSelector::paint (juce::Graphics& g)
  5953. {
  5954. using namespace theme;
  5955. auto area = getLocalBounds().toFloat();
  5956. g.setColour (hoveredPart >= 0 ? colour::bg3 : colour::bg1);
  5957. g.fillRoundedRectangle (area, radius::sm);
  5958. g.setColour (hoveredPart >= 0 ? colour::borderStrong : colour::border);
  5959. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  5960. // the pattern's colour as a thin stripe at the left of the name
  5961. if (! colour.isTransparent())
  5962. {
  5963. g.setColour (colour);
  5964. g.fillRect (juce::Rectangle<float> ((float) arrowWidth + 1.0f, 4.0f, 3.0f, (float) getHeight() - 8.0f));
  5965. }
  5966. auto arrow = [&g, this] (int part, bool left) {
  5967. const auto box = juce::Rectangle<float> (left ? 0.0f : (float) (getWidth() - arrowWidth), 0.0f, (float) arrowWidth, (float) getHeight());
  5968. const auto c = box.getCentre();
  5969. juce::Path p;
  5970. if (left)
  5971. p.addTriangle (c.x + 2.5f, c.y - 4.0f, c.x + 2.5f, c.y + 4.0f, c.x - 2.5f, c.y);
  5972. else
  5973. p.addTriangle (c.x - 2.5f, c.y - 4.0f, c.x - 2.5f, c.y + 4.0f, c.x + 2.5f, c.y);
  5974. g.setColour (hoveredPart == part ? colour::textPrimary : colour::textSecondary);
  5975. g.fillPath (p);
  5976. };
  5977. arrow (0, true);
  5978. arrow (2, false);
  5979. g.setColour (colour::textPrimary);
  5980. g.setFont (font (type::small, true));
  5981. const auto name = getLocalBounds().withTrimmedLeft (arrowWidth + 7).withTrimmedRight (arrowWidth + 14);
  5982. g.drawText (text, name, juce::Justification::centredLeft, true);
  5983. icons::draw (g, Icon::chevronDown, juce::Rectangle<float> ((float) (getWidth() - arrowWidth - 14), 0.0f, 12.0f, (float) getHeight()).reduced (1.0f, 4.0f),
  5984. hoveredPart == 1 ? colour::textPrimary : colour::textSecondary);
  5985. g.setColour (colour::border);
  5986. g.fillRect (arrowWidth, 3, 1, getHeight() - 6);
  5987. g.fillRect (getWidth() - arrowWidth - 1, 3, 1, getHeight() - 6);
  5988. }
  5989. void MainComponent::PatternSelector::mouseDown (const juce::MouseEvent& e)
  5990. {
  5991. const auto part = partAt (e.x);
  5992. namePressed = dragging = false;
  5993. appliedSteps = 0;
  5994. if (e.mods.isPopupMenu())
  5995. {
  5996. if (onMenu)
  5997. onMenu();
  5998. }
  5999. else if (part == 1)
  6000. namePressed = true; // the list opens on release unless the mouse dragged (FL's pattern selector)
  6001. else if (onStep)
  6002. onStep (part == 0 ? -1 : 1);
  6003. }
  6004. void MainComponent::PatternSelector::mouseDrag (const juce::MouseEvent& e)
  6005. {
  6006. if (! namePressed)
  6007. return;
  6008. dragging = dragging || std::abs (e.getDistanceFromDragStartY()) >= patterndrag::threshold;
  6009. if (! dragging)
  6010. return;
  6011. const auto steps = patterndrag::steps ((float) e.getDistanceFromDragStartY());
  6012. if (steps != appliedSteps && onStep)
  6013. onStep (steps - appliedSteps);
  6014. appliedSteps = steps;
  6015. }
  6016. void MainComponent::PatternSelector::mouseUp (const juce::MouseEvent&)
  6017. {
  6018. if (namePressed && ! dragging && onMenu)
  6019. onMenu();
  6020. namePressed = dragging = false;
  6021. }
  6022. void MainComponent::PatternSelector::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  6023. {
  6024. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  6025. if (const auto n = wheelSteps.take (delta); n != 0 && onStep)
  6026. onStep (n);
  6027. }
  6028. void MainComponent::PatternBox::mouseDown (const juce::MouseEvent& e)
  6029. {
  6030. pressed = dragging = false;
  6031. appliedSteps = 0;
  6032. if (! isEnabled() || e.mods.isPopupMenu())
  6033. return;
  6034. pressed = true; // the list opens on release unless the mouse dragged (FL's pattern selector)
  6035. }
  6036. void MainComponent::PatternBox::mouseDrag (const juce::MouseEvent& e)
  6037. {
  6038. if (! pressed)
  6039. return;
  6040. dragging = dragging || std::abs (e.getDistanceFromDragStartY()) >= patterndrag::threshold;
  6041. if (! dragging)
  6042. return;
  6043. const auto steps = patterndrag::steps ((float) e.getDistanceFromDragStartY());
  6044. if (steps != appliedSteps && onStep)
  6045. onStep (steps - appliedSteps);
  6046. appliedSteps = steps;
  6047. }
  6048. void MainComponent::PatternBox::mouseUp (const juce::MouseEvent&)
  6049. {
  6050. if (pressed && ! dragging)
  6051. showPopup();
  6052. pressed = dragging = false;
  6053. }
  6054. void MainComponent::PatternBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  6055. {
  6056. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  6057. if (wheel.isInertial)
  6058. return;
  6059. if (const auto n = wheelSteps.take (delta); n != 0 && onStep)
  6060. onStep (n);
  6061. }
  6062. juce::PopupMenu MainComponent::playlistTrackExportMenu (bool groups)
  6063. {
  6064. // FL: From song start... / From track start... / Time selection... (the last does nothing without a time selection)
  6065. juce::PopupMenu menu;
  6066. auto add = [&] (const juce::String& text, quickrender::Start start, bool enabled) {
  6067. menu.addItem (text, enabled, false, [this, start, groups] { exportAllPlaylistTracks (engine, projectName, start, groups); });
  6068. };
  6069. add (tr ("From song start..."), quickrender::Start::songStart, true);
  6070. add (tr ("From track start..."), quickrender::Start::clipStart, true);
  6071. add (tr ("Time selection..."), quickrender::Start::timeSelection, engine.getSong().hasLoop());
  6072. return menu;
  6073. }
  6074. juce::PopupMenu MainComponent::makePatternMenu (std::vector<int> picked)
  6075. {
  6076. const auto& song = engine.getSong();
  6077. const auto index = song.currentPattern;
  6078. const auto& pattern = song.patterns[(std::size_t) index];
  6079. auto colours = ui::colourMenu (pattern.colour, [this, index] (std::uint32_t c) {
  6080. if (index < (int) engine.getSong().patterns.size())
  6081. engine.editSong ([index, c] (Song& s) { s.patterns[(std::size_t) index].colour = c; });
  6082. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1));
  6083. juce::PopupMenu lengths;
  6084. lengths.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0,
  6085. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = 0; }); });
  6086. for (int bars : { 1, 2, 4, 8, 16, 32 })
  6087. {
  6088. const auto ticks = (std::int64_t) bars * song.barTicks();
  6089. lengths.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == ticks,
  6090. [this, index, ticks] { engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; }); });
  6091. }
  6092. juce::PopupMenu menu;
  6093. // a double-click on the title renames the pattern (issue #12)
  6094. ui::addItemHeader (menu, tr ("Pattern"), juce::String::fromUTF8 (pattern.name.c_str()), PlaylistComponent::patternColour (song, index),
  6095. [this, index] { showRenamePattern (index); });
  6096. menu.addItem (tr ("Next pattern") + shortcutText ("pattern.next"), index + 1 < (int) song.patterns.size(), false,
  6097. [this] { selectPattern (stepPattern (engine.getSong(), 1)); });
  6098. menu.addItem (tr ("Previous pattern") + shortcutText ("pattern.previous"), index > 0, false,
  6099. [this] { selectPattern (stepPattern (engine.getSong(), -1)); });
  6100. menu.addItem (tr ("First empty pattern (and name it)") + shortcutText ("pattern.firstEmpty"), [this] { runAction ("pattern.firstEmpty"); });
  6101. menu.addItem (tr ("Next empty pattern (and name it)") + shortcutText ("pattern.nextEmpty"), [this] { nextEmptyPattern(); });
  6102. menu.addItem (tr ("Next empty pattern (no naming)") + shortcutText ("pattern.nextEmptyNoName"), [this] { runAction ("pattern.nextEmptyNoName"); });
  6103. menu.addSeparator();
  6104. menu.addItem (tr ("Rename and color...") + shortcutText ("pattern.rename"), [this, index] { showRenamePattern (index); });
  6105. menu.addSubMenu (tr ("Color"), colours);
  6106. menu.addSubMenu (tr ("Length"), lengths);
  6107. menu.addItem (tr ("Insert an empty pattern before this one") + shortcutText ("pattern.insert"), [this] { insertPatternHere(); });
  6108. menu.addItem (tr ("Clone") + shortcutText ("pattern.clone"), [this] { clonePatternNow(); });
  6109. menu.addItem (tr ("Move up") + shortcutText ("pattern.moveUp"), index > 0, false, [this] { movePatternNow (-1); });
  6110. menu.addItem (tr ("Move down") + shortcutText ("pattern.moveDown"), index + 1 < (int) song.patterns.size(), false, [this] { movePatternNow (1); });
  6111. menu.addItem (tr ("Split by channel (one new pattern per channel)"), ! pattern.notes.empty(), false, [this] { splitPatternByChannelNow(); });
  6112. // FL's Patterns › PSPatQuickRenderMenu / PSPatRenderMenu / PSPatRenderReplaceMenu (PSPatQuickRenderMenuClick, tags 1 / 0 / 2;
  6113. // REA round 168e); opened from the picker, every picked pattern is rendered (round 169k)
  6114. if (picked.empty())
  6115. picked = { index };
  6116. menu.addItem (tr ("Quick render as audio clip"), [this, picked] { renderPatternsAsAudioClips (engine, picked, 1); });
  6117. menu.addItem (tr ("Render as audio clip..."), [this, picked] { renderPatternsAsAudioClips (engine, picked, 0); });
  6118. menu.addItem (tr ("Render and replace..."), [this, picked] { renderPatternsAsAudioClips (engine, picked, 2); });
  6119. juce::PopupMenu signatures;
  6120. for (int beats : { 2, 3, 4, 5, 6, 7, 8, 9, 12 })
  6121. signatures.addItem (juce::String (beats) + "/4", true, song.beatsPerBar == beats && song.beatUnit == 4,
  6122. [this, beats] { engine.editSong ([beats] (Song& s) {
  6123. s.beatsPerBar = beats;
  6124. s.beatUnit = 4;
  6125. }); });
  6126. menu.addSubMenu (tr ("Song time signature"), signatures);
  6127. menu.addSeparator();
  6128. menu.addItem (tr ("Delete pattern") + shortcutText ("pattern.delete"), song.patterns.size() > 1, false,
  6129. [this, index] { engine.editSong ([index] (Song& s) { s.removePattern (index); }); });
  6130. return menu;
  6131. }
  6132. void MainComponent::showPatternMenu()
  6133. {
  6134. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patternMenuButton));
  6135. }
  6136. // Round 190ih (PLAN R3), FL's transport while it runs, in the Pattern (FL) layout only (the Clip-launch and Simple
  6137. // layouts keep theirs): Play shows a green Pause glyph while playing (DC-10 / DF-1, details190if
  6138. // shots/fl-transport-stopped-vs-playing.png), and Record blinks while it records (DC-11: lit disc and dark disc
  6139. // alternate, shots/fl-record-armed-playing-transport.png); armed and stopped it stays lit. With Settings › Animations
  6140. // off the blink is a steady lit button (owner decision F6). On the existing 30 Hz timer; each change repaints only
  6141. // its button.
  6142. void MainComponent::updateTransportStates (bool playing)
  6143. {
  6144. const auto states = toolbarlayout::transportStates (toolbarLook); // (round 190iv's R3 merge: FL look only)
  6145. const auto simple = toolbarLook == toolbarlayout::Look::simple;
  6146. const auto countingIn = engine.isCountingIn();
  6147. // (round 190jj: BandLab's Pause shows during the count-in too)
  6148. const auto pause = states.pauseWhilePlaying && (playing || (simple && countingIn));
  6149. if (pause != shownPause)
  6150. {
  6151. shownPause = pause;
  6152. playButton.setIcon (pause ? Icon::pause : Icon::play);
  6153. playButton.setIconColourWhenOn (pause ? theme::colour::ledOn : theme::colour::accentHover);
  6154. playButton.setOnColour (pause ? juce::Colours::black.withAlpha (0.22f) : theme::colour::accent.withAlpha (0.24f)); // (FL: a dark pressed fill)
  6155. }
  6156. const auto recording = engine.isRecording();
  6157. auto lit = recording;
  6158. if (states.recordBlinks && recording && engine.getTransport().playing.load() && ui::motion::enabled())
  6159. lit = recordLitForSnapshot ? *recordLitForSnapshot : (juce::Time::getMillisecondCounter() / 250u) % 2u == 0u; // 2 blinks a second
  6160. if (recording || recordBlinkDark)
  6161. {
  6162. recordBlinkDark = recording && ! lit;
  6163. recordButton.setToggleState (lit, juce::dontSendNotification);
  6164. }
  6165. updateSimpleTransport (playing, recording, countingIn);
  6166. }
  6167. // Round 190jj (capture190ji §1d, shots/bl-d-transport-states.png; Simple layout only): BandLab's capsule while it runs —
  6168. // Back-to-start becomes Stop, the tempo / time signature / metronome grey out while it records or counts in, and the
  6169. // position where the recording started is kept for Stop. Each change touches only its widgets (the 30 Hz timer).
  6170. void MainComponent::updateSimpleTransport (bool playing, bool recording, bool countingIn)
  6171. {
  6172. const auto states = toolbarlayout::transportStates (toolbarLook);
  6173. const auto stopGlyph = ! states.stopWhilePlaying || playing || countingIn;
  6174. if (stopGlyph != shownStopGlyph)
  6175. {
  6176. shownStopGlyph = stopGlyph;
  6177. stopButton.setIcon (stopGlyph ? Icon::stop : Icon::toStart);
  6178. }
  6179. const auto lock = toolbarLook == toolbarlayout::Look::simple && recording && (playing || countingIn);
  6180. if (lock != shownRecordLock)
  6181. {
  6182. shownRecordLock = lock;
  6183. for (auto* c : std::initializer_list<juce::Component*> { &tempoDisplay, &signatureBox, &metronomeButton })
  6184. {
  6185. c->setEnabled (! lock);
  6186. c->repaint();
  6187. }
  6188. }
  6189. // where the take starts: the position the count-in counts towards, or the song position when Record joins a song
  6190. // that already plays
  6191. const auto runs = recording && (playing || countingIn);
  6192. if (runs && ! shownRecordingRuns)
  6193. simpleRecordStart = playing && ! countingIn && engine.getSong().mode == PlayMode::song ? engine.songPlayheadTicks()
  6194. : engine.getTransport().positionTicks.load();
  6195. shownRecordingRuns = runs;
  6196. }
  6197. // Round 190ih (PLAN R3, DC-9): FL's hint bar names each typing-keyboard / MIDI note as it is played and released
  6198. // ("Note on: C4 / velocity: 100", "Note off: ...", details190if shots/fl-hint-noteon.png); Pattern layout only.
  6199. void MainComponent::updateLiveNoteHint()
  6200. {
  6201. const auto note = engine.lastLiveNote();
  6202. if (note == shownLiveNote)
  6203. return;
  6204. shownLiveNote = note;
  6205. if (note == 0 || layoutStyle != layoutstyle::Style::pattern)
  6206. return;
  6207. const auto key = juce::String (notenames::keyName (livenote::key (note)));
  6208. const auto velocity = juce::String (livenote::velocity (note));
  6209. ui::postHint ({ livenote::on (note) ? tr ("Note on: {0} / velocity: {1}", { key, velocity })
  6210. : tr ("Note off: {0} / velocity: {1}", { key, velocity }), {}, false, false },
  6211. 2500);
  6212. }
  6213. void MainComponent::refreshModeButton()
  6214. {
  6215. const auto recording = engine.isRecording();
  6216. recordButton.setToggleState (recording, juce::dontSendNotification);
  6217. const auto inputs = engine.getActiveMidiInputs();
  6218. recordButton.setTooltip ((engine.isAudioRecordingArmed() ? tr ("Record while playing: notes (PC keyboard and MIDI) and input audio")
  6219. : tr ("Record while playing: notes (PC keyboard and MIDI)"))
  6220. + "\n" + tr ("MIDI inputs: {0}", { inputs.isEmpty() ? tr ("none") : inputs.joinIntoString (", ") }));
  6221. recordMenuButton.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  6222. recordMenuButton.setOnColour (theme::colour::accentMuted);
  6223. const auto songMode = engine.getSong().mode == PlayMode::song;
  6224. patternModeButton.setToggleState (! songMode, juce::dontSendNotification);
  6225. songModeButton.setToggleState (songMode, juce::dontSendNotification);
  6226. metronomeButton.setToggleState (engine.getTransport().metronome.load(), juce::dontSendNotification);
  6227. multilinkButton.setToggleState (engine.isMultilinkOn(), juce::dontSendNotification);
  6228. }
  6229. void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  6230. {
  6231. // round 190ap: the title says while third-party plugins are off; the last one switched on takes the note away
  6232. if (const auto off = engine.pluginsOff(); off != shownPluginsOff)
  6233. {
  6234. shownPluginsOff = off;
  6235. updateTitle();
  6236. }
  6237. if (const auto notice = engine.takeRecordingNotice(); notice.issue != AudioEngine::InputIssue::none && persistent)
  6238. mixerinput::explain (notice);
  6239. // round 165c: hardware inserts measured for another device setup (the device or its buffer size changed, or the project
  6240. // was measured elsewhere): a prompt that pings them on request, nothing pinged by itself (pings make clicks)
  6241. if (auto stale = engine.takeHardwareInsertNotice(); ! stale.empty() && persistent)
  6242. {
  6243. const auto count = (int) stale.size();
  6244. auto options = juce::MessageBoxOptions()
  6245. .withIconType (juce::MessageBoxIconType::InfoIcon)
  6246. .withTitle (tr ("Hardware Insert"))
  6247. .withMessage ((count == 1 ? tr ("The round trip of a hardware insert was measured for another audio setup (the device or its "
  6248. "buffer size changed), so its return is no longer lined up with the rest of the mix.")
  6249. : tr ("The round trip of {0} hardware inserts was measured for another audio setup (the device or its "
  6250. "buffer size changed), so their returns are no longer lined up with the rest of the mix.",
  6251. { juce::String (count) }))
  6252. + "\n\n" + tr ("Ping now? Each one sends a few clicks out to its gear and listens for them on its return."))
  6253. .withButton (tr ("Ping now"))
  6254. .withButton (tr ("Later"));
  6255. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), stale = std::move (stale)] (int result) {
  6256. if (result == 1 && safe != nullptr)
  6257. safe->engine.pingHardwareInserts (stale);
  6258. });
  6259. }
  6260. const auto& song = engine.getSong();
  6261. // FL's Auto select linked modules [DECOMP FUN_00ffe510 -> FUN_011e84e0] (round 187a): selecting one channel selects
  6262. // its mixer track
  6263. if (const auto selected = engine.getSelectedChannel(); selected != lastLinkedChannel)
  6264. {
  6265. lastLinkedChannel = selected;
  6266. if (ChannelRackComponent::autoSelectLinked && selected >= 0 && selected < (int) song.channels.size() && engine.getSelectedChannels().size() == 1)
  6267. if (const auto insert = song.channels[(std::size_t) selected].mixerTrack; insert >= 0 && insert < (int) song.mixer.size()
  6268. && insert != mixer.getStripsForSnapshot().getSelectedTrack())
  6269. mixer.selectTrack (insert);
  6270. }
  6271. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr)
  6272. simpleWorkflow->songChanged(); // (an empty project opens on the New track chooser)
  6273. refreshSongNotes(); // (round 190ch: the Lyrics / Notes panel and Reference match show the project's own state)
  6274. // FL's "Select first channel with notes when the pattern changes" (Settings › General, REA round 167j §5)
  6275. if (song.currentPattern != lastCurrentPattern)
  6276. {
  6277. const auto changedPattern = lastCurrentPattern >= 0;
  6278. lastCurrentPattern = song.currentPattern;
  6279. if (changedPattern && ChannelRackComponent::selectFirstChannelWithNotes)
  6280. if (const auto first = firstChannelWithNotes (song, song.currentPattern); first >= 0 && first != engine.getSelectedChannel())
  6281. engine.setSelectedChannel (first);
  6282. }
  6283. bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
  6284. for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
  6285. namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
  6286. refreshModeButton();
  6287. tempoDisplay.repaint();
  6288. // a project with other filter groups (or none): the rack's filter falls back to "All"
  6289. if (rack.getFilterGroup() >= (int) song.channelGroups.size())
  6290. rack.setFilterGroup (-1);
  6291. if (rackFilterBox.text != rack.filterName())
  6292. {
  6293. rackFilterBox.text = rack.filterName();
  6294. rackFilterBox.repaint();
  6295. }
  6296. if (rackLoopButton.getToggleState() != rack.isLoopingOn()) // (another pattern, undo)
  6297. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  6298. if ((int) song.channels.size() != fittedChannelCount && fittedChannelCount >= 0) // a row was added or removed
  6299. fitChannelRack (false);
  6300. refreshKeyPanel(); // (undo, another project; cheap: it repaints only on a change)
  6301. if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (swingSlider.getValue() - song.swing) > 1e-6)
  6302. refreshToolbar();
  6303. else
  6304. {
  6305. refreshRackPatternSelector(); // a new pattern colour
  6306. refreshRackLengthBox(); // (notes added: the automatic length grows)
  6307. }
  6308. if (onboardingOn) // round 190np: the Next-3 items and the empty-state hint follow the song
  6309. updateOnboarding();
  6310. }
  6311. // --- tempo display -------------------------------------------------------------------------------
  6312. ui::ValueSpec MainComponent::TempoDisplay::spec() const
  6313. {
  6314. ui::ValueSpec s;
  6315. s.name = tr ("Tempo");
  6316. s.minimum = minTempo;
  6317. s.maximum = maxTempo;
  6318. s.defaultValue = 130.0;
  6319. s.toText = [] (double v) { return juce::String (v, 3) + " BPM"; };
  6320. s.target = AutomationTarget { AutomationTargetKind::tempo, 0 };
  6321. return s;
  6322. }
  6323. void MainComponent::TempoDisplay::setBpm (double bpm)
  6324. {
  6325. bpm = controls::clampTempo (bpm);
  6326. if (std::abs (bpm - engine.getSong().bpm) > 1e-9)
  6327. engine.editSong ([bpm] (Song& s) { clipops::followTempo (s, bpm); });
  6328. engine.getLink().proposeTempo (bpm); // (round 190gl: the peers follow; also when the project already had this tempo)
  6329. repaint();
  6330. }
  6331. bool MainComponent::TempoDisplay::isOnDecimals (int x) const
  6332. {
  6333. return decimalX > 0 && x > decimalX;
  6334. }
  6335. void MainComponent::TempoDisplay::paint (juce::Graphics& g)
  6336. {
  6337. using namespace theme;
  6338. if (look != toolbarlayout::Look::fl)
  6339. {
  6340. // round 190iv: BandLab's "120 bpm" segment of the tempo capsule (the capsule is drawn behind) / Live's "167.00" box
  6341. const auto box = getLocalBounds();
  6342. const auto tempo = linksync::displayTempo (engine.shownTempo());
  6343. const auto rounded = std::round (tempo * 100.0) / 100.0;
  6344. if (look == toolbarlayout::Look::live)
  6345. {
  6346. g.setColour (dragging ? juce::Colour (0xff1e1e1e) : isMouseOver() ? juce::Colour (0xff464646) : juce::Colour (0xff363636));
  6347. g.fillRect (box);
  6348. g.setColour (juce::Colour (0xffb5b5b5));
  6349. g.setFont (font (type::caption));
  6350. g.drawText (juce::String (rounded, 2), box.reduced (3, 0), juce::Justification::centred, false);
  6351. decimalX = box.getCentreX() + 6;
  6352. return;
  6353. }
  6354. if (isMouseOver() || dragging)
  6355. {
  6356. g.setColour (dragging ? colour::bg6 : colour::bg5);
  6357. g.fillRect (box);
  6358. }
  6359. const auto number = std::abs (rounded - std::round (rounded)) < 0.005 ? juce::String ((int) std::round (rounded)) : juce::String (rounded, 2);
  6360. const juce::Font big (font (15.0f, true)), unit (font (type::small));
  6361. const auto w1 = textcache::stringWidth (big, number), w2 = textcache::stringWidth (unit, "bpm");
  6362. auto x = (float) box.getCentreX() - (w1 + 4.0f + w2) / 2.0f;
  6363. const auto baseline = (float) box.getCentreY() + 5.0f;
  6364. // (round 190jj: greyed while a take records or counts in, as BandLab's)
  6365. g.setColour (isEnabled() ? colour::textPrimary : colour::textDisabled);
  6366. g.setFont (big);
  6367. g.drawSingleLineText (number, juce::roundToInt (x), juce::roundToInt (baseline));
  6368. x += w1 + 4.0f;
  6369. decimalX = juce::roundToInt (x);
  6370. g.setColour (isEnabled() ? colour::textSecondary : colour::textDisabled);
  6371. g.setFont (unit);
  6372. g.drawSingleLineText ("bpm", juce::roundToInt (x), juce::roundToInt (baseline));
  6373. return;
  6374. }
  6375. const auto area = getLocalBounds().toFloat();
  6376. g.setColour (colour::bg1);
  6377. g.fillRoundedRectangle (area, radius::md);
  6378. if (dragging)
  6379. {
  6380. g.setColour (colour::accent.withAlpha (0.6f));
  6381. g.drawRoundedRectangle (area.reduced (0.5f), radius::md, 1.0f);
  6382. }
  6383. // (round 190gl: the Link session's tempo while Link is on; to the thousandth shown, so 96.99995 reads 97.000 — the
  6384. // whole number and the decimals used to be cut apart and showed 96.000)
  6385. const auto bpm = linksync::displayTempo (engine.shownTempo());
  6386. const auto whole = juce::String ((int) std::floor (bpm + 1e-9));
  6387. const auto fraction = juce::String (bpm - std::floor (bpm + 1e-9), 3).fromFirstOccurrenceOf (".", false, false).paddedRight ('0', 3).substring (0, 3);
  6388. // (round 190jo FM-6: the whole BPM from cap 13 to cap 16, FL's large digits; ".000" stays small; narrower at the
  6389. // compact widths so the readout always fits)
  6390. juce::Font big (monoFont (22.0f));
  6391. const juce::Font small (monoFont (11.0f)), caption (font (type::caption - 1.0f));
  6392. {
  6393. const auto rest = textcache::stringWidth (small, "." + fraction) + 6.0f + textcache::stringWidth (caption, "BPM");
  6394. for (int i = 0; i < 8 && textcache::stringWidth (big, whole) + rest > area.getWidth() - 6.0f; ++i)
  6395. big = big.withHeight (big.getHeight() * 0.94f);
  6396. }
  6397. const auto wholeWidth = textcache::stringWidth (big, whole);
  6398. const auto fracWidth = textcache::stringWidth (small, "." + fraction);
  6399. const auto unitWidth = textcache::stringWidth (caption, "BPM");
  6400. auto x = area.getCentreX() - (wholeWidth + fracWidth + 6.0f + unitWidth) / 2.0f;
  6401. const auto baseline = area.getCentreY() + 5.0f;
  6402. g.setColour (colour::textPrimary);
  6403. g.setFont (big);
  6404. g.drawSingleLineText (whole, juce::roundToInt (x), juce::roundToInt (baseline));
  6405. x += wholeWidth;
  6406. decimalX = juce::roundToInt (x);
  6407. g.setColour (dragOnDecimals && dragging ? colour::textPrimary : colour::textSecondary);
  6408. g.setFont (small);
  6409. g.drawSingleLineText ("." + fraction, juce::roundToInt (x), juce::roundToInt (baseline));
  6410. x += fracWidth + 6.0f;
  6411. g.setColour (colour::textDisabled);
  6412. g.setFont (caption);
  6413. g.drawSingleLineText ("BPM", juce::roundToInt (x), juce::roundToInt (baseline));
  6414. }
  6415. void MainComponent::TempoDisplay::mouseDown (const juce::MouseEvent& e)
  6416. {
  6417. if (e.mods.isPopupMenu())
  6418. {
  6419. showMenu();
  6420. return;
  6421. }
  6422. if (ui::isResetClick (e))
  6423. {
  6424. setBpm (spec().defaultValue);
  6425. return;
  6426. }
  6427. startBpm = engine.shownTempo();
  6428. dragOnDecimals = isOnDecimals (e.x);
  6429. dragging = true;
  6430. repaint();
  6431. }
  6432. void MainComponent::TempoDisplay::mouseDrag (const juce::MouseEvent& e)
  6433. {
  6434. if (dragging)
  6435. {
  6436. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  6437. setBpm (controls::tempoDrag (startBpm, -e.getDistanceFromDragStartY(), dragOnDecimals, e.mods.isCtrlDown()));
  6438. }
  6439. }
  6440. void MainComponent::TempoDisplay::mouseUp (const juce::MouseEvent&)
  6441. {
  6442. dragging = false;
  6443. repaint();
  6444. }
  6445. void MainComponent::TempoDisplay::mouseDoubleClick (const juce::MouseEvent& e)
  6446. {
  6447. if (! e.mods.isPopupMenu())
  6448. ui::typeValue (*this, spec(), engine.shownTempo(), [this] (double v) { setBpm (v); });
  6449. }
  6450. void MainComponent::TempoDisplay::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  6451. {
  6452. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  6453. if (delta == 0.0f)
  6454. return;
  6455. const auto step = isOnDecimals (e.x) ? 0.01 : 1.0;
  6456. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  6457. setBpm (engine.shownTempo() + (delta > 0.0f ? 1.0 : -1.0) * step * (e.mods.isCtrlDown() ? 0.1 : 1.0));
  6458. }
  6459. ui::Hint MainComponent::TempoDisplay::hintAt (juce::Point<int> p)
  6460. {
  6461. return ui::valueHint (spec(), engine.shownTempo(),
  6462. isOnDecimals (p.x) ? tr ("[LMB] drag the decimals for fine changes [Wheel] 0.01 [2xLMB] type [RMB] tap tempo, half, double")
  6463. : tr ("[LMB] drag the whole number [Ctrl] fine [Wheel] 1 BPM [2xLMB] type [RMB] tap tempo, half, double"));
  6464. }
  6465. void MainComponent::TempoDisplay::showMenu()
  6466. {
  6467. buildMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  6468. }
  6469. juce::PopupMenu MainComponent::TempoDisplay::buildMenu()
  6470. {
  6471. const auto bpm = engine.getSong().bpm;
  6472. juce::PopupMenu menu;
  6473. menu.addSectionHeader (tr ("Tempo") + ": " + juce::String (bpm, 3) + " BPM");
  6474. menu.addItem (tr ("Type value..."), [this, bpm] { ui::typeValue (*this, spec(), bpm, [this] (double v) { setBpm (v); }); });
  6475. menu.addItem (tr ("Tempo tapper..."), [this] { showTap(); });
  6476. // FL's tempo menu (WheelMenu N80BPM...N160BPM; round 190bt): the fixed tempos 80 to 160 BPM
  6477. // (flat items after the tapper and before "Half", as FL's menu resource orders them)
  6478. for (int t = 80; t <= 160; t += 10)
  6479. menu.addItem (juce::String (t) + " BPM", [this, t] { setBpm ((double) t); });
  6480. // FL's "Half speed" (round 190mp, DF-16; capture 190mp A4, fl-tempo-menu.png): the last item of FL's column, after a
  6481. // line; ticked while on. The song plays at half its tempo and the display keeps showing the tempo (FL: "a temporary
  6482. // state"). LYNX's Half / Double (which change the tempo) follow under a line.
  6483. menu.addSeparator();
  6484. menu.addItem (tr ("Half speed"), true, engine.isHalfSpeed(), [this] { engine.setHalfSpeed (! engine.isHalfSpeed()); });
  6485. menu.addSeparator();
  6486. menu.addItem (tr ("Half ({0} BPM)", { juce::String (controls::halfTempo (bpm), 2) }), [this, bpm] { setBpm (controls::halfTempo (bpm)); });
  6487. menu.addItem (tr ("Double ({0} BPM)", { juce::String (controls::doubleTempo (bpm), 2) }), [this, bpm] { setBpm (controls::doubleTempo (bpm)); });
  6488. menu.addItem (tr ("Reset ({0})", { "130 BPM" }), [this] { setBpm (130.0); });
  6489. menu.addSeparator();
  6490. addAutomationItem (menu, engine, { AutomationTargetKind::tempo, 0 });
  6491. return menu;
  6492. }
  6493. void MainComponent::TempoDisplay::showTap()
  6494. {
  6495. openTempoTapper (engine); // FL's tempo menu opens its tempo tapper too
  6496. }
  6497. // --- hint bar ------------------------------------------------------------------------------------
  6498. juce::String MainComponent::idleHint() const
  6499. {
  6500. if (engine.isWaitingForInput())
  6501. return tr ("Recording: waiting for the first note ([Space] cancels)");
  6502. if (engine.isCountingIn())
  6503. return tr ("Recording: count-in...");
  6504. if (engine.isLinkWaiting()) // (round 190gl)
  6505. return tr ("Ableton Link: playback starts with the session's next cycle ([Space] cancels)");
  6506. // FL's text while "Multilink to controllers" is on (round 177b-4); the controls moved show their own hint
  6507. if (engine.isMultilinkOn())
  6508. return tr ("Please tweak the controls you want to link...");
  6509. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.running)
  6510. return tr ("Scanning for plugins in the background: {0}% {1}", { juce::String (juce::roundToInt (scan.progress * 100.0f)), scan.file });
  6511. // round 170e3: one line at 1920 (the typing piano's state shows on its own button)
  6512. return tr ("Point at anything for help [F1] shortcuts [F5]-[F9] windows [Space] play/stop");
  6513. }
  6514. juce::String MainComponent::keyMarkup (const char* actionId) const
  6515. {
  6516. const auto& chords = keyMap.chordsFor (actionId);
  6517. if (chords.empty())
  6518. return {};
  6519. // "Ctrl+Shift+S" -> "[Ctrl][Shift][S]"; a key name that is not markup stays as text
  6520. const auto text = juce::String (keys::displayString (chords.front()));
  6521. juce::String out;
  6522. for (const auto& part : juce::StringArray::fromTokens (text, "+", ""))
  6523. {
  6524. if (! hintmarkup::isToken (part.toStdString()))
  6525. return "(" + text + ")";
  6526. out << "[" << part << "]";
  6527. }
  6528. return out;
  6529. }
  6530. void MainComponent::setControlHints()
  6531. {
  6532. auto with = [this] (const juce::String& text, const char* actionId) {
  6533. const auto key = keyMarkup (actionId);
  6534. return key.isEmpty() ? text : text + " " + key;
  6535. };
  6536. ui::setHint (newButton, with (tr ("New project"), "file.new"));
  6537. ui::setHint (openButton, with (tr ("Open a project (.lynx, FL Studio .flp, Ableton Live .als, FL Studio Mobile .flm, DAWproject, GarageBand .band, BandLab .blx, MIDI)"), "file.open"));
  6538. ui::setHint (saveButton, with (tr ("Save the project"), "file.save") + " " + tr ("save as:") + " " + keyMarkup ("file.saveAs"));
  6539. ui::setHint (exportButton, with (tr ("Export audio: WAV, FLAC or OGG"), "file.export"));
  6540. ui::setHint (undoButton, with (tr ("Undo the last edit"), "edit.undo") + " " + tr ("[RMB] undo history"), true);
  6541. ui::setHint (redoButton, with (tr ("Redo"), "edit.redo") + " " + tr ("[RMB] undo history"), true);
  6542. ui::setHint (pluginPickerButton, with (tr ("Plugin picker: add an instrument or an effect by name"), "panel.quickAdd"));
  6543. ui::setHint (audioEditorButton, tr ("Open audio editor / New audio editor") + " " + tr ("[LMB] the Master's audio editor [RMB] a new one"), true);
  6544. ui::setHint (playButton, with (tr ("Play: [LMB] play; again: stop and go back to where it started"), "transport.playStop")
  6545. + " " + keyMarkup ("transport.pause") + " " + tr ("pause"));
  6546. ui::setHint (stopButton, tr ("Stop: [LMB] stop and go back to the start (or the remembered position; again: the start) "
  6547. "[2xLMB] back to the start and all notes off (panic) [RMB] remember seek time")
  6548. + " " + keyMarkup ("tools.stopSound") + " " + tr ("Stop sound (all notes off)"), // round 170h2
  6549. true);
  6550. ui::setHint (recordButton, with (tr ("Record: [LMB] arm, then play to record notes (and audio, when armed) [RMB] what to record"), "transport.record"),
  6551. true);
  6552. ui::setHint (recordMenuButton, tr ("What to record: notes, input audio, count-in, overdub or replace, quantise [LMB] menu"), true);
  6553. ui::setHint (patternModeButton, with (tr ("Pattern mode: plays the current pattern in a loop [RMB] show the Channel Rack"), "transport.toggleMode"));
  6554. ui::setHint (songModeButton, with (tr ("Song mode: plays the Playlist arrangement [RMB] show the Playlist"), "transport.toggleMode"));
  6555. ui::setHint (metronomeButton, with (tr ("Metronome: clicks on every beat while playing [RMB] volume and options"), "transport.metronome"), true);
  6556. ui::setHint (countInButton, with (tr ("Count-in: one bar of clicks before recording starts (the menu has more lengths)"), "record.countIn"));
  6557. ui::setHint (waitInputButton, with (tr ("Wait for input: recording starts with the first note you play"), "record.waitForInput"));
  6558. ui::setHint (blendButton, tr ("Blend recorded notes: on, a take adds its notes to the pattern (overdub); off, a recorded channel's old notes are replaced"));
  6559. ui::setHint (loopRecordButton, with (tr ("Loop record: on, recording loops (Song mode: the loop region, one take per pass; Pattern mode: the pattern); off, it "
  6560. "plays straight on, through the loop region or past the pattern's end, and keeps everything where it "
  6561. "was played (the pattern grows)"), "record.loop"));
  6562. ui::setHint (stepEditButton, with (tr ("Step edit: with the transport stopped, notes you play go into the current pattern at the position, "
  6563. "a snap step long; release the keys and the position moves on one step (chords: hold them together)"),
  6564. "record.stepEdit"));
  6565. ui::setHint (punchButton, with (tr ("Punch in/out: audio recording keeps only the loop region (playback runs through it; pre- and "
  6566. "post-roll in the recording options)"), "record.punch"));
  6567. ui::setHint (tapTempoButton, with (tr ("Tempo tapper: tap the beat to set the tempo"), "view.tempoTapper"));
  6568. ui::setHint (typingPianoButton, with (tr ("Typing keyboard to piano: Z..M and Q..P play the selected channels; letter shortcuts pause"),
  6569. "view.typingPiano"));
  6570. ui::setHint (snapToggleButton, with (tr ("Snap (magnet): [LMB] turns the snap off and back on; lit while it snaps. "
  6571. "The Playlist and Piano Roll snap boxes show the same magnet"),
  6572. "playlist.snapToggle")); // (round 190ng, issue #219: the key from the key map)
  6573. ui::setHint (gridBox, tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  6574. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"),
  6575. true);
  6576. ui::setHint (patternBox, tr ("Current pattern: what the Channel Rack and Piano Roll edit and Pattern mode plays [LMB] choose [Wheel] step "
  6577. "[F4] next empty [F2] rename") + " " + tr ("[LMB] drag up / down: step through the patterns"));
  6578. ui::setHint (newPatternButton, tr ("New pattern: an empty pattern after the last one"));
  6579. ui::setHint (patternMenuButton, tr ("Pattern menu: rename, color, length, clone, insert, split by channel, delete"), true);
  6580. const char* panelHelp[] = { TR_NOOP ("the arrangement: clips of patterns, audio and automation on tracks"),
  6581. TR_NOOP ("the instruments and their step sequencer"),
  6582. TR_NOOP ("the notes of the selected channel in the current pattern"),
  6583. TR_NOOP ("inserts, effects and routing"),
  6584. TR_NOOP ("samples, presets, plugins and projects to drag in") };
  6585. for (int i = 0; i < workspace::panelCount; ++i)
  6586. ui::setHint (panelButtons[(std::size_t) i],
  6587. with (panelName ((Panel) i) + ": " + tr (panelHelp[i]) + " " + tr ("[LMB] show, focus or hide [RMB] maximized"),
  6588. panelAction ((Panel) i)));
  6589. setQuickTips();
  6590. }
  6591. std::vector<std::pair<juce::Rectangle<int>, juce::String>> MainComponent::getQuickTipsForSnapshot()
  6592. {
  6593. std::vector<std::pair<juce::Rectangle<int>, juce::String>> tips;
  6594. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  6595. for (auto* child : c.getChildren())
  6596. {
  6597. if (! child->isVisible())
  6598. continue;
  6599. if (const auto tip = ui::quickTipOf (*child); tip.isNotEmpty() && ! child->getBounds().isEmpty())
  6600. tips.emplace_back (getLocalArea (child->getParentComponent(), child->getBounds()), tip);
  6601. visit (*child);
  6602. }
  6603. };
  6604. visit (*this);
  6605. return tips;
  6606. }
  6607. // the small name bubble of every toolbar control (the hint bar keeps the full description)
  6608. void MainComponent::setQuickTips()
  6609. {
  6610. auto tip = [this] (juce::Component& c, const juce::String& name, const char* actionId = nullptr) {
  6611. ui::setQuickTip (c, name, actionId != nullptr ? shortcutText (actionId).trim() : juce::String());
  6612. };
  6613. tip (newButton, tr ("New project"), "file.new");
  6614. tip (openButton, tr ("Open project"), "file.open");
  6615. tip (saveButton, tr ("Save project"), "file.save");
  6616. tip (exportButton, tr ("Export audio"), "file.export");
  6617. tip (undoButton, tr ("Undo"), "edit.undo");
  6618. tip (redoButton, tr ("Redo"), "edit.redo");
  6619. tip (pluginPickerButton, tr ("Plugin picker"), "panel.quickAdd");
  6620. tip (audioEditorButton, tr ("Audio editor"));
  6621. tip (playButton, tr ("Play"), "transport.playStop");
  6622. tip (stopButton, tr ("Stop"));
  6623. tip (recordButton, tr ("Record"), "transport.record");
  6624. tip (recordMenuButton, tr ("Recording options"));
  6625. tip (patternModeButton, tr ("Pattern mode"), "transport.toggleMode");
  6626. tip (songModeButton, tr ("Song mode"), "transport.toggleMode");
  6627. tip (metronomeButton, tr ("Metronome"), "transport.metronome");
  6628. tip (countInButton, tr ("Count-in"), "record.countIn");
  6629. tip (waitInputButton, tr ("Wait for input"), "record.waitForInput");
  6630. tip (blendButton, tr ("Blend recorded notes"), "record.blend");
  6631. tip (loopRecordButton, tr ("Loop record"), "record.loop");
  6632. tip (stepEditButton, tr ("Step edit"), "record.stepEdit");
  6633. tip (multilinkButton, tr ("Multilink to controllers"), "options.multilink"); // (FL's hint: "Ctrl+J Multilink to controllers")
  6634. tip (punchButton, tr ("Punch in/out"), "record.punch");
  6635. tip (tapTempoButton, tr ("Tempo tapper"), "view.tempoTapper");
  6636. tip (typingPianoButton, tr ("Typing keyboard to piano"), "view.typingPiano");
  6637. tip (tempoDisplay, tr ("Tempo (BPM)"));
  6638. tip (timeDisplay, tr ("Song time"));
  6639. tip (songPosition, tr ("Song position"));
  6640. tip (masterVolume, tr ("Master volume"));
  6641. tip (masterPitch, tr ("Master pitch"));
  6642. tip (gridBox, tr ("Snap"));
  6643. tip (snapToggleButton, tr ("Snap on / off"));
  6644. tip (patternBox, tr ("Pattern"));
  6645. tip (newPatternButton, tr ("New pattern"));
  6646. tip (patternMenuButton, tr ("Pattern options"));
  6647. tip (perfMeter, tr ("CPU, memory and polyphony"));
  6648. tip (chordPanel, tr ("Detected chord"));
  6649. tip (output, tr ("Output monitor"));
  6650. tip (swingSlider, tr ("Swing"));
  6651. tip (rackFilterBox, tr ("Channel filter group"));
  6652. tip (rackGraphButton, tr ("Graph editor"));
  6653. tip (rackPianoRollButton, tr ("Piano-roll view"), "rack.pianoRollView");
  6654. tip (rackLoopButton, tr ("Channel looping"));
  6655. tip (rackLoopStarterButton, tr ("Loop Starter"));
  6656. for (int i = 0; i < workspace::panelCount; ++i)
  6657. tip (panelButtons[(std::size_t) i], tr (panelName ((Panel) i)), panelAction ((Panel) i));
  6658. }
  6659. // FL's Step edit (round 170e3): the notes played since the last tick go into the current pattern at the position, a
  6660. // snap step of the Piano Roll long; when every key is up the position moves on a step (core/StepEdit.h). While the
  6661. // transport plays they are left to the recording, as in FL.
  6662. void MainComponent::applyStepEdit()
  6663. {
  6664. auto played = engine.takeStepEditNotes();
  6665. if (played.empty() || engine.getTransport().playing.load())
  6666. return;
  6667. const auto now = engine.getTransport().positionTicks.load();
  6668. // the position moved by anything else (a click on a ruler, Stop): start from there
  6669. if (now != stepSeekTick && now != stepPrevTick)
  6670. {
  6671. const auto& song = engine.getSong();
  6672. const auto at = transportedit::patternPlayhead (song, song.currentPattern, now);
  6673. stepWriter.reset (at >= 0.0 ? (std::int64_t) std::llround (at) : 0);
  6674. stepSeekTick = stepPrevTick = now;
  6675. }
  6676. // the toolbar (main) snap is FL's step-edit step (round 170e5)
  6677. const auto& mainSnap = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  6678. const auto mainTicks = mainSnap.kind == grid::Kind::ticks ? (std::int64_t) mainSnap.ticks
  6679. : mainSnap.kind == grid::Kind::bar ? engine.getSong().barTicks()
  6680. : 0;
  6681. const auto step = stepedit::stepLength (mainTicks, pianoRoll.gridForSnapshot());
  6682. for (const auto& p : played)
  6683. {
  6684. auto moved = false;
  6685. engine.editSong ([&] (Song& s) {
  6686. if (! s.patterns.empty())
  6687. moved = stepWriter.play (p, s.patterns[(std::size_t) juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern)], step);
  6688. }, p.on);
  6689. if (! moved)
  6690. continue;
  6691. const auto& song = engine.getSong();
  6692. const auto target = transportedit::patternSeekTarget (song, song.currentPattern, (double) stepWriter.getPosition(), now);
  6693. if (target >= 0.0)
  6694. {
  6695. stepPrevTick = engine.getTransport().positionTicks.load();
  6696. stepSeekTick = target;
  6697. engine.seek (target);
  6698. }
  6699. }
  6700. }
  6701. bool MainComponent::toolbarFrame (double nowMs)
  6702. {
  6703. const auto moved = output.update (nowMs);
  6704. timeDisplay.update();
  6705. songPosition.update();
  6706. return moved || engine.getTransport().playing.load (std::memory_order_relaxed);
  6707. }
  6708. void MainComponent::refreshChordOptions()
  6709. {
  6710. auto options = chordReadout.getOptions();
  6711. options.sharps = ! notenames::flats();
  6712. for (int pc = 0; pc < 12; ++pc)
  6713. {
  6714. // the chosen note names, with FL's accidentals ("C♯", "B♭", "Sol♯")
  6715. auto name = juce::String (notenames::pitchName (pc));
  6716. if (name.endsWithChar ('#'))
  6717. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266F);
  6718. else if (name.length() > 1 && name.endsWithChar ('b'))
  6719. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266D);
  6720. chordNotes[(std::size_t) pc] = name.toStdString();
  6721. }
  6722. options.notes = &chordNotes;
  6723. // Roman (a LYNX choice, FL's item changes nothing): against the Piano Roll's scale, when one is set
  6724. const auto& highlight = engine.getSong().scaleHighlight;
  6725. options.tonic = pianoRoll.scaleTonic() >= 0 ? pianoRoll.scaleTonic() : highlight.scale >= 0 ? highlight.root : -1;
  6726. chordReadout.setOptions (options);
  6727. }
  6728. void MainComponent::showChordText()
  6729. {
  6730. auto text = juce::String::fromUTF8 (chordReadout.text().c_str());
  6731. if (chordReadout.lastWasNovelty())
  6732. text = tr (text);
  6733. chordPanel.setText (text);
  6734. if (chordShowNearHint)
  6735. {
  6736. // as FL: it follows the panel, leaves with "---", and with a display delay stays that long at most (15 s at most)
  6737. const auto chord = chordReadout.text() != chordread::noChord && text.isNotEmpty();
  6738. chordNearHint.setText (text);
  6739. const auto width = juce::roundToInt (juce::GlyphArrangement::getStringWidth (theme::font (theme::type::body, true).withHeight (17.0f), text)) + 8;
  6740. chordNearHint.setBounds (hintBar.getX() + 8, hintBar.getBottom() + 2, width, 24);
  6741. chordNearHint.setVisible (chord);
  6742. if (chord)
  6743. {
  6744. chordNearHint.toFront (false);
  6745. chordNearHintUntil = juce::Time::getMillisecondCounter() + juce::jmin<std::uint32_t> (15000, chordReadout.getDelayMs());
  6746. }
  6747. }
  6748. }
  6749. void MainComponent::updateChordPanel()
  6750. {
  6751. if (! chordPanel.isVisible() && ! chordShowNearHint)
  6752. return;
  6753. const auto now = juce::Time::getMillisecondCounter();
  6754. auto changed = false;
  6755. for (int channel = 0; channel < chordread::channels; ++channel)
  6756. {
  6757. const auto bits = engine.heldInputKeyBits (channel);
  6758. auto& before = chordHeld[(std::size_t) channel];
  6759. if (bits == before)
  6760. continue;
  6761. if (! changed)
  6762. refreshChordOptions();
  6763. changed = true;
  6764. // what ended first: a chord changed between two ticks reads as the new chord, not as both
  6765. for (const auto on : { false, true })
  6766. for (int word = 0; word < 2; ++word)
  6767. {
  6768. auto diff = (on ? bits[(std::size_t) word] & ~before[(std::size_t) word] : before[(std::size_t) word] & ~bits[(std::size_t) word]);
  6769. for (int b = 0; diff != 0; ++b, diff >>= 1)
  6770. if ((diff & 1u) != 0)
  6771. chordReadout.note (channel, word * 64 + b, on, now);
  6772. }
  6773. before = bits;
  6774. }
  6775. if (chordReadout.tick (now))
  6776. changed = true;
  6777. if (changed)
  6778. showChordText();
  6779. if (chordNearHint.isVisible() && chordReadout.getDelayMs() > 0 && (int) (now - chordNearHintUntil) > 0)
  6780. chordNearHint.setVisible (false);
  6781. }
  6782. void MainComponent::showChordPanelMenu()
  6783. {
  6784. juce::PopupMenu menu;
  6785. menu.addSectionHeader (tr ("Chord style"));
  6786. const auto roman = chordReadout.getOptions().roman;
  6787. auto setRoman = [this] (bool on) {
  6788. auto o = chordReadout.getOptions();
  6789. o.roman = on;
  6790. chordReadout.setOptions (o);
  6791. saveUiSettings();
  6792. };
  6793. menu.addItem (tr ("Standard"), true, ! roman, [setRoman] { setRoman (false); });
  6794. menu.addItem (tr ("Roman"), true, roman, [setRoman] { setRoman (true); });
  6795. menu.addSectionHeader (tr ("Display delay for played chords"));
  6796. const auto delay = chordReadout.getDelayMs();
  6797. auto delayItem = [&] (const juce::String& name, std::uint32_t seconds) {
  6798. menu.addItem (name, true, delay == seconds * 1000u, [this, seconds] {
  6799. chordReadout.setDelayMs (seconds * 1000u);
  6800. saveUiSettings();
  6801. });
  6802. };
  6803. delayItem (tr ("None"), 0);
  6804. delayItem (tr ("1 second"), 1);
  6805. delayItem (tr ("3 seconds"), 3);
  6806. delayItem (tr ("5 seconds"), 5);
  6807. delayItem (tr ("Show forever"), chordread::foreverSeconds);
  6808. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&chordPanel));
  6809. }
  6810. namespace
  6811. {
  6812. // "A minor", "C# Dorian": the root and the short scale name (round 184a S11)
  6813. juce::String keyLabel (const projectkey::Key& key)
  6814. {
  6815. return juce::String (projectkey::rootName (key.root)) + " " + tr (juce::String (projectkey::shortScaleName (key.flScale)));
  6816. }
  6817. } // namespace
  6818. void MainComponent::refreshKeyPanel()
  6819. {
  6820. const auto key = projectkey::get (engine.getSong());
  6821. keyPanel.setText (key ? keyLabel (*key) : juce::String());
  6822. }
  6823. void MainComponent::setProjectKey (std::optional<projectkey::Key> key)
  6824. {
  6825. if (projectkey::get (engine.getSong()) == key)
  6826. return;
  6827. engine.editSong ([key] (Song& s) { projectkey::set (s, key); }); // one undo step; no note moves
  6828. refreshKeyPanel();
  6829. pianoRoll.repaint(); // (its scale highlight is this key)
  6830. }
  6831. // The Key menu (round 184a S11, design §3.1): the best guesses from the song's notes, the root, the scale (the common ones,
  6832. // then "More scales"), and None. Every choice writes the one stored key, FL's project scale (.flp 0xF3).
  6833. void MainComponent::showKeyMenu()
  6834. {
  6835. makeKeyMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&keyPanel));
  6836. }
  6837. juce::PopupMenu MainComponent::makeKeyMenu()
  6838. {
  6839. const auto current = projectkey::get (engine.getSong());
  6840. juce::PopupMenu menu;
  6841. menu.addSectionHeader (tr ("Guess from notes"));
  6842. const auto guesses = keyguess::guess (engine.getSong(), 3);
  6843. if (guesses.empty())
  6844. menu.addItem (tr ("No notes to guess from yet"), false, false, [] {});
  6845. for (const auto& g : guesses)
  6846. menu.addItem (keyLabel (g.key) + " (" + tr ("{0} of {1} notes in scale", { juce::String (g.notesInScale), juce::String (g.notes) }) + ")",
  6847. true, current == g.key, [this, key = g.key] { setProjectKey (key); });
  6848. const auto root = current ? current->root : 0;
  6849. const auto scale = current ? current->flScale : projectkey::commonFirst().front(); // (no key yet: Major)
  6850. menu.addSectionHeader (tr ("Root"));
  6851. juce::PopupMenu roots;
  6852. for (int r = 0; r < 12; ++r)
  6853. roots.addItem (juce::String (projectkey::rootName (r)), true, current && current->root == r,
  6854. [this, r, scale] { setProjectKey (projectkey::Key { r, scale }); });
  6855. menu.addSubMenu (current ? juce::String (projectkey::rootName (root)) : tr ("Choose the root"), roots);
  6856. menu.addSectionHeader (tr ("Scale"));
  6857. const auto order = projectkey::commonFirst();
  6858. juce::PopupMenu more;
  6859. for (std::size_t i = 0; i < order.size(); ++i)
  6860. {
  6861. const auto flScale = order[i];
  6862. const auto ticked = current && current->flScale == flScale;
  6863. auto choose = [this, root, flScale] { setProjectKey (projectkey::Key { root, flScale }); };
  6864. if ((int) i < keyguess::commonScales)
  6865. {
  6866. const auto name = tr (juce::String (projectkey::shortScaleName (flScale))); // ("minor" in "A minor"; "Minor" in the list)
  6867. menu.addItem (name.substring (0, 1).toUpperCase() + name.substring (1), true, ticked, choose);
  6868. }
  6869. else // FL's own scale names (its Reference scales folder), as its Piano roll lists them
  6870. more.addItem (juce::String (notetools::flReferenceScales()[(std::size_t) flScale].name), true, ticked, choose);
  6871. }
  6872. menu.addSubMenu (tr ("More scales"), more);
  6873. menu.addSeparator();
  6874. menu.addItem (tr ("None"), true, ! current, [this] { setProjectKey (std::nullopt); });
  6875. return menu;
  6876. }
  6877. void MainComponent::addAudioLoggerMenu (juce::PopupMenu& menu)
  6878. {
  6879. // FL 2026's Tools › Audio logger, item for item (REA_rodada181b.md)
  6880. auto& log = engine.getRollingLog();
  6881. const auto on = log.isEnabled();
  6882. auto title = tr ("Audio logger");
  6883. if (on)
  6884. title << " (" << tr ("memory used: {0}MB", { juce::String (juce::roundToInt ((double) log.bytesInUse() / 1048576.0)) }) << ")";
  6885. menu.addSectionHeader (title);
  6886. menu.addItem (tr ("Enabled"), true, on, [this, on] {
  6887. engine.getRollingLog().setEnabled (! on);
  6888. saveUiSettings();
  6889. });
  6890. juce::PopupMenu settings;
  6891. settings.addSectionHeader (tr ("Maximum length"));
  6892. const auto seconds = log.lengthSeconds();
  6893. auto lengthItem = [&] (const juce::String& name, int minutes) {
  6894. settings.addItem (name, true, seconds == minutes * 60, [this, minutes] {
  6895. engine.getRollingLog().setLengthSeconds (minutes * 60);
  6896. saveUiSettings();
  6897. });
  6898. };
  6899. lengthItem (tr ("1 minute"), 1);
  6900. lengthItem (tr ("2 minutes"), 2);
  6901. lengthItem (tr ("5 minutes"), 5);
  6902. lengthItem (tr ("10 minutes"), 10);
  6903. settings.addSectionHeader (tr ("Recording position"));
  6904. const auto pre = log.getPosition() == RollingAudioLog::Position::preEffects;
  6905. auto positionItem = [&] (const juce::String& name, RollingAudioLog::Position p, bool ticked) {
  6906. settings.addItem (name, true, ticked, [this, p] {
  6907. engine.getRollingLog().setPosition (p);
  6908. saveUiSettings();
  6909. });
  6910. };
  6911. positionItem (tr ("Pre effects"), RollingAudioLog::Position::preEffects, pre);
  6912. positionItem (tr ("Post effects, pre fader"), RollingAudioLog::Position::postEffects, ! pre);
  6913. menu.addSubMenu (tr ("Settings"), settings);
  6914. menu.addItem (tr ("Dump to audio editor"), on, false, [this] { dumpAudioLog(); });
  6915. }
  6916. void MainComponent::dumpAudioLog()
  6917. {
  6918. auto dump = std::make_shared<RollingAudioLog::Dump>();
  6919. if (! engine.getRollingLog().dump (*dump))
  6920. {
  6921. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Audio logger is empty"),
  6922. tr ("The audio logger doesn't contain any audio at the moment"));
  6923. return;
  6924. }
  6925. const auto folder = AudioLogger::defaultFolder();
  6926. folder.createDirectory();
  6927. const auto target = folder.getNonexistentChildFile ("Audiolog-" + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S"), ".wav", false);
  6928. juce::Component::SafePointer<MainComponent> self (this);
  6929. // (a long log takes a moment to write: not on the UI thread)
  6930. juce::Thread::launch ([self, dump, target] {
  6931. auto saved = false;
  6932. {
  6933. juce::WavAudioFormat wav;
  6934. std::unique_ptr<juce::OutputStream> stream (target.createOutputStream().release());
  6935. if (stream != nullptr)
  6936. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (stream.get(), dump->rate, 2, 32, {}, 0) }; writer != nullptr)
  6937. {
  6938. stream.release(); // owned by the writer now
  6939. const float* channels[] = { dump->left.data(), dump->right.data() };
  6940. saved = writer->writeFromFloatArrays (channels, 2, (int) dump->left.size());
  6941. }
  6942. }
  6943. juce::MessageManager::callAsync ([self, target, saved] {
  6944. if (self == nullptr)
  6945. return;
  6946. if (saved)
  6947. openAudioEditor (self->engine, target);
  6948. else
  6949. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Audio logger"),
  6950. tr ("Could not create a file in {0}", { target.getParentDirectory().getFullPathName() }));
  6951. });
  6952. });
  6953. }
  6954. void MainComponent::readPluginDatabaseAgain()
  6955. {
  6956. // the Plugin database folder as it is on disk now (issue #104): the Browser is built again when it changed; open
  6957. // menus and an open Plugin picker stay as they are (FL, fl190be Q2 / Q4), the next ones read the new state
  6958. auto& host = engine.getPluginHost();
  6959. const auto folders = host.databaseFolders();
  6960. const auto names = host.pluginNames();
  6961. quickpick::markPluginDatabaseChanged();
  6962. quickpick::refreshPluginDatabase (engine, true);
  6963. const auto& now = host.databaseFolders();
  6964. if (now.of != folders.of || now.effects != folders.effects || now.generators != folders.generators || now.hidden != folders.hidden
  6965. || now.top != folders.top || host.pluginNames() != names)
  6966. browser.pluginDatabaseChanged();
  6967. }
  6968. // FL's Settings › Audio › "Auto close" (round 190bx, core/FlSettings.h): the audio device is free for other programs
  6969. // while LYNX is not in front and has no use for it; it opens again when LYNX comes back or needs it.
  6970. void MainComponent::autoCloseDevice()
  6971. {
  6972. if (! persistent)
  6973. return;
  6974. auto& devices = engine.getDeviceManager();
  6975. flsettings::DeviceUse use;
  6976. use.foreground = juce::Process::isForegroundProcess();
  6977. use.busy = engine.getTransport().playing.load() || engine.isRecording() || engine.isLiveRecording() || engine.isCountingIn()
  6978. || engine.isWaitingForInput() || engine.isAudioRecordingArmed() || engine.isBouncing() || engine.isPinging();
  6979. const auto open = devices.getCurrentAudioDevice() != nullptr;
  6980. switch (flsettings::autoCloseAction (flsettings::options().autoCloseDevice.load(), use, open, deviceClosedByAutoClose))
  6981. {
  6982. case flsettings::DeviceAction::close:
  6983. devices.closeAudioDevice();
  6984. deviceClosedByAutoClose = true;
  6985. break;
  6986. case flsettings::DeviceAction::reopen:
  6987. devices.restartLastAudioDevice();
  6988. deviceClosedByAutoClose = false;
  6989. break;
  6990. case flsettings::DeviceAction::none:
  6991. if (open)
  6992. deviceClosedByAutoClose = false; // (opened again by something else: the Settings page, a device change)
  6993. break;
  6994. }
  6995. }
  6996. void MainComponent::timerCallback()
  6997. {
  6998. const auto remoteHistoryError = engine.getRemoteHistoryError();
  6999. const auto showRemote = (remoteui::enabled() || remoteui::active() || remoteHistoryError.isNotEmpty()) && ! demo::active(); // (round 190np: --demo hides it)
  7000. if (next3Card != nullptr && ++onboardingTicks % 15 == 0) // (round 190np: what the Next-3 items read from the view)
  7001. onboardingTick();
  7002. remoteControlBar.setText (remoteHistoryError.isNotEmpty() ? remoteHistoryError : tr (remoteui::status()), juce::dontSendNotification);
  7003. if (remoteControlBar.isVisible() != showRemote)
  7004. {
  7005. remoteControlBar.setVisible (showRemote);
  7006. resized();
  7007. }
  7008. const uitrace::Scope trace ("MainComponent timer", false);
  7009. engine.getMeters().expirePower (juce::Time::getMillisecondCounter()); // (round 190lr: the RMS sums stop with their reader)
  7010. {
  7011. const uitrace::Scope part ("timer: toolbar displays", false);
  7012. masterVolume.update();
  7013. masterPitch.update();
  7014. updateRecordQuantise();
  7015. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  7016. }
  7017. if (engine.isStepEdit())
  7018. applyStepEdit();
  7019. revealPanelUnderDrag(); // round 190mr (DF-34)
  7020. if (engine.isModified() != lastModified)
  7021. {
  7022. const uitrace::Scope part ("timer: title", false);
  7023. lastModified = engine.isModified();
  7024. updateTitle();
  7025. }
  7026. // the Browser's "Project folder" follows the project's file (.lynx, or the .flp it was imported from)
  7027. const uitrace::Scope partFolders ("timer: project folder / recording target", false);
  7028. browser.setProjectFile (currentFile != juce::File() ? currentFile : importedFlpFile);
  7029. // and so does where audio is recorded ("<project folder>/Audio/Recorded", FL-like take names)
  7030. engine.setRecordingTarget (recordingFolderFor (currentFile != juce::File() ? currentFile : importedFlpFile),
  7031. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String());
  7032. // a backup copy every few minutes (Settings › General) when there are changes
  7033. // (not in the middle of a recording: FL also postpones the timed backup until the transport is free; round 177d:
  7034. // with "Wait with backups..." on, also while playing and for a few seconds after MIDI input, so writing the plugin
  7035. // states never stutters the sound, up to the longest wait set there)
  7036. if (const auto midi = engine.getMidiPlayed(); midi != backupMidiSeen)
  7037. {
  7038. backupMidiSeen = midi;
  7039. backupMidiMs = juce::Time::getMillisecondCounterHiRes();
  7040. }
  7041. const auto backupDueTicks = 30 * 60 * autosaveMinutes;
  7042. if (autosaveMinutes > 0 && ++autosaveTicks >= backupDueTicks
  7043. && prefs::backupMayRun (engine.isRecording(), engine.getTransport().playing.load(),
  7044. juce::Time::getMillisecondCounterHiRes() - backupMidiMs, backupWaitsForQuiet,
  7045. autosaveTicks * 1000.0 / 30.0, backupLongestWaitMinutes * 60000.0))
  7046. {
  7047. autosaveTicks = 0;
  7048. if (engine.isModified())
  7049. autosave();
  7050. }
  7051. updateSaveReminder();
  7052. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.finished != scansSeen)
  7053. {
  7054. scansSeen = scan.finished;
  7055. ui::postHint ({ scan.found == 1 ? tr ("Plugin scan finished: 1 new plugin.")
  7056. : tr ("Plugin scan finished: {0} new plugins.", { juce::String (scan.found) }), {}, false, false },
  7057. 6000);
  7058. }
  7059. // round 190gg (B4, Linux / macOS): a hosted plugin's own thread faulted; that thread was parked, and every instance
  7060. // of the plugin is switched off now (counted as crashes: the prompt below)
  7061. switchOffPluginsOfThreadFaults();
  7062. // a hosted plugin crashed inside a call: it was switched off (bypassed / silent) and LYNX kept running
  7063. if (const auto crashes = pluginCrashCount(); crashes != pluginCrashesSeen)
  7064. {
  7065. pluginCrashesSeen = crashes;
  7066. juce::StringArray names, lines;
  7067. for (const auto& c : pluginCrashes())
  7068. {
  7069. const auto name = juce::String::fromUTF8 (c.plugin.c_str());
  7070. names.addIfNotAlreadyThere (name);
  7071. lines.add (juce::Time::getCurrentTime().toISO8601 (true) + " " + name + " " + crashguard::describe (c.code) + " 0x"
  7072. + juce::String::toHexString ((juce::int64) c.code));
  7073. }
  7074. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (lines[lines.size() - 1] + "\n");
  7075. // round 190ao: "Reload" starts it again without reopening the project (only on request: a plugin that crashes
  7076. // again shows this again)
  7077. const auto crashedName = names[names.size() - 1];
  7078. // round 190dt: it crashed on its saved settings (it was left out as the project opened): the same settings would
  7079. // crash it again, so no Reload; the project keeps them for the save
  7080. const auto all = pluginCrashes();
  7081. const auto onLoad = ! all.empty() && all.back().onLoad;
  7082. // round 190gg (B1): Reload, or from now on in a process of its own, where its next crash cannot reach LYNX
  7083. const auto prompt = PluginWindows::crashPrompt (crashedName, onLoad);
  7084. auto options = juce::MessageBoxOptions().withIconType (juce::MessageBoxIconType::WarningIcon).withTitle (prompt.title).withMessage (prompt.message);
  7085. for (const auto& button : prompt.buttons)
  7086. options = options.withButton (button);
  7087. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), crashedName, prompt] (int result) {
  7088. // (JUCE: the first button is 1, the last one 0)
  7089. if (safe == nullptr || result == 0)
  7090. return;
  7091. if (result == 1 && prompt.reload)
  7092. safe->reloadCrashedPlugins (crashedName);
  7093. else if (prompt.separate && result == (prompt.reload ? 2 : 1))
  7094. PluginWindows::alwaysRunSeparately (safe->engine, crashedName);
  7095. });
  7096. }
  7097. // round 176a: a plugin in a separate process (Make bridged, or a 32-bit plugin in the 32-bit bridge) crashed or hung:
  7098. // only that process went; the plugin is muted. Round 174a's prompt, logged like the other plugin crashes.
  7099. if (const auto deaths = pluginSandboxDeathCount(); deaths != sandboxDeathsSeen)
  7100. {
  7101. const auto fresh = juce::jmax (1, deaths - sandboxDeathsSeen);
  7102. sandboxDeathsSeen = deaths;
  7103. const auto all = pluginSandboxDeaths();
  7104. if (! all.empty())
  7105. {
  7106. const auto& d = all.back();
  7107. // round 190jg: a group's process (per vendor / all plugins together) took the other plugins in it along
  7108. juce::StringArray withIt;
  7109. for (int i = juce::jmax (0, (int) all.size() - fresh); i + 1 < (int) all.size(); ++i)
  7110. if (! d.alone && all[(std::size_t) i].group == d.group && all[(std::size_t) i].plugin != d.plugin)
  7111. withIt.addIfNotAlreadyThere (all[(std::size_t) i].plugin);
  7112. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (
  7113. juce::Time::getCurrentTime().toISO8601 (true) + " " + d.plugin + " " + (d.crashed ? "crashed" : "stopped responding")
  7114. + (d.bits32 ? " (32-bit bridge)" : d.group.isNotEmpty() ? " (process group " + d.group + ")" : " (separate process)")
  7115. + (withIt.isEmpty() ? juce::String() : ", with " + withIt.joinIntoString (", ")) + "\n");
  7116. announceSeparateProcessCrash (d.plugin, d.crashed, d.bits32, withIt);
  7117. }
  7118. }
  7119. // issue #32 (round 174a): a plugin's own editor window faulted; LYNX closed that editor and kept running
  7120. if (const auto crashes = PluginWindows::editorCrashCount(); crashes != editorCrashesSeen)
  7121. {
  7122. editorCrashesSeen = crashes;
  7123. const auto all = PluginWindows::editorCrashes();
  7124. if (! all.empty())
  7125. announceEditorCrash (all.back().plugin);
  7126. }
  7127. autoCloseDevice();
  7128. // back from another app (the file manager, perhaps: issue #104): the Plugin database folder is read again
  7129. if (const auto foreground = juce::Process::isForegroundProcess(); foreground != wasForeground)
  7130. {
  7131. wasForeground = foreground;
  7132. if (foreground && persistent)
  7133. readPluginDatabaseAgain();
  7134. }
  7135. auto& transport = engine.getTransport();
  7136. if (! heldKeys.empty())
  7137. {
  7138. if (! juce::Process::isForegroundProcess()) // switched to another app with keys down: no key-up will come
  7139. heldKeys.releaseAll();
  7140. else // keys released while another window (a detached panel, a dialog) had the focus
  7141. keyStateChanged (false);
  7142. }
  7143. // hint bar: a gesture's own posted hint, else the control under the mouse (while it is dragged, the
  7144. // control that was pressed, at the point it was pressed, so its value updates live); MIDI learn and
  7145. // recording states first
  7146. if (! hintsFrozen)
  7147. {
  7148. const uitrace::Scope part ("timer: hint", false);
  7149. ui::Hint hint;
  7150. bool live = false;
  7151. juce::Component* hovered = nullptr;
  7152. if (engine.isLearningMidi())
  7153. hint.text = tr ("Move a knob/fader on the MIDI controller to link it to the parameter...");
  7154. else if (engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting())
  7155. hint.text = idleHint();
  7156. else if (auto posted = ui::postedHint())
  7157. {
  7158. hint = *posted;
  7159. live = true;
  7160. }
  7161. else if (isShowing())
  7162. {
  7163. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  7164. if (auto* under = source.getComponentUnderMouse(); under == &hintBar)
  7165. hint = hintBar.getHint(); // (round 190kn: the hint stays while the pointer is on the bar, for its copy menu)
  7166. else if (under != nullptr)
  7167. {
  7168. live = source.isDragging();
  7169. const auto at = live ? source.getLastMouseDownPosition() : source.getScreenPosition();
  7170. hint = ui::hintFor (under, under->getLocalPoint (nullptr, at).roundToInt());
  7171. hovered = under;
  7172. }
  7173. }
  7174. if (hint.isEmpty())
  7175. {
  7176. hint.text = idleHint();
  7177. live = false;
  7178. }
  7179. hintBar.setHint (hint, live && hint.value.isNotEmpty());
  7180. if (auto* panel = static_cast<ui::ExtendedHintPanel*> (extendedHint.get())) // round 190mr (DF-49)
  7181. panel->setHint (hintBar.getHint(), live && hint.value.isNotEmpty());
  7182. if (detailView != nullptr && detailView->isShowing()) // (round 190jn: Live's Info View; repaints only on a change)
  7183. detailView->setInfoHint (hint);
  7184. if (hoverValues)
  7185. updateHoverValue (hovered, hint, live);
  7186. if (++tweakTicks >= 3) // 10 times a second
  7187. {
  7188. tweakTicks = 0;
  7189. refreshTweakReadout();
  7190. }
  7191. }
  7192. // Ableton Link (round 190gl): the toggle's peers, the tempo the session plays, and Start Stop Sync from a peer
  7193. // (Play / Stop pressed as the user would)
  7194. linkToggle.update();
  7195. if (toolbarLook != toolbarlayout::Look::fl)
  7196. updateLookFields(); // (round 190iv: the Simple / Clip-launch toolbar's own fields; each repaints only on a change)
  7197. updateUndoRedoEnabled();
  7198. if (const auto linkTempo = engine.getLink().isEnabled() ? engine.getLink().sessionTempo() : 0.0; linkTempo != shownLinkTempo)
  7199. {
  7200. shownLinkTempo = linkTempo;
  7201. tempoDisplay.repaint();
  7202. }
  7203. if (engine.getLink().takeRemoteStart() && ! transport.playing.load() && ! engine.isLinkWaiting() && ! engine.isCountingIn())
  7204. playStop();
  7205. if (engine.getLink().takeRemoteStop() && (transport.playing.load() || engine.isLinkWaiting()))
  7206. playStop();
  7207. // (lit while the start waits for Link; FL shows its Pause glyph through the count-in too, live check 190iw Q7)
  7208. const auto playing = transport.playing.load() || engine.isLinkWaiting() || (engine.isCountingIn() && layoutStyle == layoutstyle::Style::pattern);
  7209. playButton.setToggleState (playing, juce::dontSendNotification);
  7210. updateTransportStates (playing);
  7211. updateLiveNoteHint();
  7212. if (simpleWorkflow != nullptr && layoutStyle == layoutstyle::Style::simple) // round 190ih: the dock's input level
  7213. simpleWorkflow->tick();
  7214. updateChordPanel();
  7215. // CPU / memory / polyphony, a few times a second
  7216. if (++meterTicks >= toolbar::PerformanceMeter::refreshTicks() && perfMeter.isVisible() && ! hintsFrozen)
  7217. {
  7218. const uitrace::Scope part ("timer: performance meter", false);
  7219. meterTicks = 0;
  7220. const auto held = (int) heldKeys.size();
  7221. const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
  7222. if (toolbar::PerformanceMeter::secondView == toolbar::PerformanceMeter::framesPerSecond) // round 190ld: View FPS
  7223. perfMeter.setFramesPerSecond (ui::FrameTicker::uiFrameRate());
  7224. perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
  7225. const auto rt = engine.getRtStats().snapshot();
  7226. juce::StringArray heaviest;
  7227. for (const auto& u : engine.getHeaviestUnits())
  7228. if (heaviest.size() < 3 && u.load >= 0.01)
  7229. heaviest.add (u.name + " " + juce::String (juce::roundToInt (u.load * 100.0)) + "%");
  7230. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  7231. perfMeter.setRealtime (rt.overBudget, rt.lateCalls, engine.getRtStats().takeWindowMaxLoad(), heaviest,
  7232. device != nullptr ? device->getXRunCount() : -1);
  7233. perfMeter.setDropouts (describeDropouts (engine)); // (round 190gg: how many, when, why)
  7234. // dropouts on Windows shared mode: suggest the interface's ASIO driver (round 160), worked out once per device type
  7235. if (device != nullptr && (rt.overBudget > 0 || rt.lateCalls > 0) && device->getTypeName() != driverTipType)
  7236. {
  7237. driverTipType = device->getTypeName();
  7238. std::vector<std::string> asio;
  7239. for (auto* type : engine.getDeviceManager().getAvailableDeviceTypes())
  7240. if (type->getTypeName() == "ASIO")
  7241. for (const auto& name : type->getDeviceNames())
  7242. asio.push_back (name.toStdString());
  7243. perfMeter.setDriverTip (juce::String::fromUTF8 (prefs::suggestedAsioDriver (driverTipType.toStdString(), asio).c_str()));
  7244. }
  7245. // Linux: the first dropouts without real-time priority explain how to get it, once per installation (round 161)
  7246. if (device != nullptr && ! realtimeHintChecked && (rt.overBudget > 0 || device->getXRunCount() > 0)
  7247. && lynx::rt::status() == lynx::rt::Status::denied)
  7248. {
  7249. realtimeHintChecked = true;
  7250. if (lynx::rt::shouldShowHint (PluginHost::settingsFolder().getChildFile ("realtime-hint-shown")))
  7251. juce::AlertWindow::showMessageBoxAsync (
  7252. juce::MessageBoxIconType::InfoIcon, tr ("Real-time priority"),
  7253. tr ("The sound broke up, and Linux runs LYNX SHARE's audio thread at normal priority. Real-time priority makes dropouts much rarer:\n\n"
  7254. "- install rtkit (package \"rtkit\"; most desktops already have it), or\n"
  7255. "- add yourself to the \"audio\" group with an rtprio limit in /etc/security/limits.d (as for JACK),\n\n"
  7256. "then log out and in again. LYNX SHARE never needs root. Options > Audio settings shows the current state."));
  7257. }
  7258. }
  7259. if (++midiInputTicks % 30 == 1) // the open MIDI inputs, once a second
  7260. midiLightInputs = engine.getActiveMidiInputs();
  7261. midiLight.update (engine.getMidiActivity(), midiLightInputs, engine.getMidiProjectLinked(), engine.getMidiGlobalLinked());
  7262. // FL's MIDI Sync light (round 190ld): with master sync sent, a blink on each beat, blue on each bar's first
  7263. if (engine.getMidiSync().sending() && transport.playing.load())
  7264. {
  7265. const auto& song = engine.getSong();
  7266. const auto beatTicks = juce::jmax<std::int64_t> (1, song.beatTicks());
  7267. const auto beat = (std::int64_t) std::floor (transport.positionTicks.load() / (double) beatTicks);
  7268. if (beat != syncLightBeat)
  7269. {
  7270. if (syncLightBeat != std::numeric_limits<std::int64_t>::min())
  7271. midiLight.beat (beat % juce::jmax (1, (int) (song.barTicks() / beatTicks)) == 0);
  7272. syncLightBeat = beat;
  7273. }
  7274. }
  7275. else
  7276. syncLightBeat = std::numeric_limits<std::int64_t>::min();
  7277. // If a closed dialog left the main window without a focused component, take it back so the PC keyboard
  7278. // keeps playing. Only while the main window itself is the active one: another LYNX window (Audio editor,
  7279. // Quick-add palette, a plugin's editor, a detached panel) keeps its focus (issue #4: grabbing it here, 30
  7280. // times a second, pulled the main window to the front and closed the plugins' drop-down menus).
  7281. if (shouldReclaimKeyboardFocus())
  7282. grabKeyboardFocus();
  7283. }
  7284. bool MainComponent::shouldReclaimKeyboardFocus()
  7285. {
  7286. auto* peer = getPeer();
  7287. return ! hasKeyboardFocus (true) && isShowing() && peer != nullptr && peer->isFocused() && juce::Process::isForegroundProcess()
  7288. && juce::Component::getCurrentlyModalComponent() == nullptr && ! workspace.isDetachedWindowActive();
  7289. }
  7290. void MainComponent::updateTitle()
  7291. {
  7292. repaint (titleArea); // the project name in the toolbar
  7293. if (! engine.isModified()) // what is on disk now: the reference for "unused recordings" after a Discard
  7294. savedSamples = safety::referencedSamples (engine.getSong());
  7295. if (auto* window = getTopLevelComponent())
  7296. {
  7297. // a live session's state (round 169j): LIVE, or what it is waiting for
  7298. juce::String liveState;
  7299. if (live != nullptr && live->isActive())
  7300. {
  7301. using S = LiveSessionManager::State;
  7302. const auto st = live->getState();
  7303. liveState = " [" + (st == S::live ? tr ("LIVE") : st == S::reconnecting ? tr ("Reconnecting...") : st == S::waitingHost ? tr ("Waiting for the host...") : tr ("Connecting...")) + "]";
  7304. }
  7305. // round 190ap: opened without third-party plugins, while some are still off
  7306. const auto pluginsOff = engine.pluginsOff() ? " " + tr ("(third-party plugins off)") : juce::String();
  7307. window->setName ((engine.isModified() ? "* " : "")
  7308. + (projectName.isNotEmpty() ? "LYNX SHARE - " + projectName : juce::String ("LYNX SHARE")) + importedSuffix + pluginsOff + liveState);
  7309. }
  7310. }
  7311. std::unique_ptr<juce::AlertWindow> MainComponent::makeConfirmDiscardWindow()
  7312. {
  7313. // round 190jp (design190ia FW-17, FL's confirm): "Save changes to <file>?" with the name in the highlight colour, the
  7314. // default button in the accent, an underlined letter on each button (S / D / C), FL's Y / N for Save / Discard
  7315. const auto name = currentFile.existsAsFile() ? currentFile.getFileName() : projectName.isNotEmpty() ? projectName : tr ("Untitled");
  7316. auto window = std::make_unique<ui::dialog::Dialog> (tr ("Confirm"), 400, juce::MessageBoxIconType::QuestionIcon);
  7317. window->setSentence (ui::dialog::sentence (tr ("Save changes to {0}?"), name, theme::font (theme::type::title)));
  7318. window->addDialogButton (tr ("Save"), 1, true, false, "y");
  7319. window->addDialogButton (tr ("Discard"), 2, false, false, "n");
  7320. window->addDialogButton (tr ("Cancel"), 0, false, true);
  7321. return window;
  7322. }
  7323. void MainComponent::confirmDiscard (std::function<void()> then)
  7324. {
  7325. if (! engine.isModified())
  7326. {
  7327. offerToDeleteUnusedRecordings (true, std::move (then));
  7328. return;
  7329. }
  7330. auto* window = makeConfirmDiscardWindow().release();
  7331. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
  7332. if (result == 1)
  7333. save (false, [this, then] { offerToDeleteUnusedRecordings (true, then); }); // (not after a cancelled "save as")
  7334. else if (result == 2)
  7335. offerToDeleteUnusedRecordings (false, then);
  7336. }),
  7337. true);
  7338. }
  7339. juce::File MainComponent::recordingFolderFor (const juce::File& projectFile) const
  7340. {
  7341. // FL records into the project data folder's "Audio\Recorded" (REA round 134); LYNX's data folder is the folder of
  7342. // the project file. Unsaved projects record into the global recordings folder.
  7343. return projectFile == juce::File() ? AudioEngine::defaultRecordingFolder()
  7344. : projectFile.getParentDirectory().getChildFile (safety::recordedSubfolder);
  7345. }
  7346. namespace
  7347. {
  7348. // FL's Keep / Delete question about recorded files nothing uses (FLEngine FUN_00ed1380, REA round 134)
  7349. void askKeepOrDelete (const juce::String& message, const std::vector<juce::File>& files, std::function<void (bool)> done)
  7350. {
  7351. juce::String list;
  7352. for (std::size_t i = 0; i < files.size() && i < 8; ++i)
  7353. list << "\n " << files[i].getFileName();
  7354. if (files.size() > 8)
  7355. list << "\n " << tr ("...and {0} more", { juce::String ((int) files.size() - 8) });
  7356. auto* w = new juce::AlertWindow (tr ("Unused recordings"), message + list, juce::MessageBoxIconType::QuestionIcon);
  7357. w->addButton (tr ("Keep"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7358. w->addButton (tr ("Delete"), 1);
  7359. w->enterModalState (true, juce::ModalCallbackFunction::create ([done] (int result) { done (result == 1); }), true);
  7360. }
  7361. // to the recycle bin when the system has one (FL's "Delete recorded files to recycle bin")
  7362. int removeFiles (const std::vector<juce::File>& files)
  7363. {
  7364. int removed = 0;
  7365. for (const auto& f : files)
  7366. removed += f.existsAsFile() && (f.moveToTrash() || f.deleteFile());
  7367. return removed;
  7368. }
  7369. } // namespace
  7370. void MainComponent::offerToDeleteUnusedRecordings (bool keepsCurrentState, std::function<void()> then)
  7371. {
  7372. // the takes of this session the project on disk will not use: deleted takes, undone recordings, a project closed
  7373. // without saving (FL: "You created ... sample file(s) that are no longer used if the project isn't saved")
  7374. std::vector<std::string> recorded;
  7375. for (const auto& f : engine.getSessionRecordings())
  7376. if (f.existsAsFile())
  7377. recorded.push_back (f.getFullPathName().toStdString());
  7378. const auto referenced = keepsCurrentState ? safety::referencedSamples (engine.getSong()) : savedSamples;
  7379. std::vector<juce::File> unused;
  7380. for (const auto& path : safety::unusedRecordings (recorded, referenced))
  7381. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  7382. if (unused.empty() || ! askUnusedRecordings || ! persistent)
  7383. {
  7384. then();
  7385. return;
  7386. }
  7387. askKeepOrDelete (unused.size() == 1 ? tr ("You recorded 1 audio file that this project will not use.")
  7388. : tr ("You recorded {0} audio files that this project will not use.", { juce::String ((int) unused.size()) }),
  7389. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused, then] (bool remove) {
  7390. if (safe == nullptr)
  7391. return;
  7392. if (remove)
  7393. removeFiles (unused);
  7394. safe->engine.forgetRecordings (unused); // asked once per file
  7395. then();
  7396. });
  7397. }
  7398. void MainComponent::deleteUnusedRecordingsAndSave()
  7399. {
  7400. // FL's Tools › Macros "Delete unused files and save project", for the files this project recorded: every take in
  7401. // its recording folder (and this session's takes elsewhere) that no channel or clip uses
  7402. if (currentFile == juce::File())
  7403. {
  7404. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Delete unused recordings"),
  7405. tr ("Save the project first: its recordings are kept next to it, in {0}.", { juce::String (safety::recordedSubfolder) }));
  7406. return;
  7407. }
  7408. std::vector<std::string> recorded;
  7409. const auto stem = currentFile.getFileNameWithoutExtension() + "_";
  7410. for (const auto& f : recordingFolderFor (currentFile).findChildFiles (juce::File::findFiles, false, "*.wav"))
  7411. if (f.getFileName().startsWithIgnoreCase (stem)) // other projects in the same folder record there too
  7412. recorded.push_back (f.getFullPathName().toStdString());
  7413. for (const auto& f : engine.getSessionRecordings())
  7414. if (f.existsAsFile())
  7415. recorded.push_back (f.getFullPathName().toStdString());
  7416. std::vector<juce::File> unused;
  7417. for (const auto& path : safety::unusedRecordings (recorded, safety::referencedSamples (engine.getSong())))
  7418. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  7419. if (unused.empty())
  7420. {
  7421. save (false);
  7422. ui::postHint ({ tr ("No unused recordings. Project saved."), {}, false, false }, 4000);
  7423. return;
  7424. }
  7425. askKeepOrDelete (tr ("This project has {0} unused recording(s). Deleting them cannot be undone (they go to the recycle bin).",
  7426. { juce::String ((int) unused.size()) }),
  7427. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused] (bool remove) {
  7428. if (safe == nullptr)
  7429. return;
  7430. if (remove)
  7431. {
  7432. const auto n = removeFiles (unused);
  7433. safe->engine.forgetRecordings (unused);
  7434. ui::postHint ({ tr ("Deleted {0} unused recording(s).", { juce::String (n) }), {}, false, false }, 4000);
  7435. }
  7436. safe->save (false);
  7437. });
  7438. }
  7439. namespace
  7440. {
  7441. juce::String projectStem (const juce::String& projectName)
  7442. {
  7443. return projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled");
  7444. }
  7445. // the backup folder's projects with their modification times (for rotation and "revert to last backup")
  7446. std::vector<safety::BackupFile> backupFiles (const juce::File& folder)
  7447. {
  7448. std::vector<safety::BackupFile> files;
  7449. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, juce::String ("*") + ProjectFile::extension))
  7450. files.push_back ({ f.getFileNameWithoutExtension().toStdString(), f.getLastModificationTime().toMilliseconds() });
  7451. return files;
  7452. }
  7453. // "Song (autosaved on 2026-10-20 at 14h19)" in `folder`, "_2"... when that minute is taken (FL's naming, REA round 118)
  7454. juce::File newBackupFile (const juce::File& folder, const juce::String& stem, safety::BackupKind kind)
  7455. {
  7456. const auto now = juce::Time::getCurrentTime();
  7457. const auto name = safety::backupName (stem.toStdString(), kind, now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(), now.getMinutes());
  7458. const auto unique = safety::uniqueName (name, [&folder] (const std::string& n) {
  7459. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  7460. });
  7461. return folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ProjectFile::extension);
  7462. }
  7463. } // namespace
  7464. void MainComponent::autosave()
  7465. {
  7466. commitSongNotes(); // (round 190ch: notes still being typed are part of what is saved)
  7467. // backup copy of the open project, so work isn't lost if something crashes ("Song (autosaved on 2026-10-20 at
  7468. // 14h19).lynx" in the backup folder, like FL's Backup folder); only the newest few of each project are kept
  7469. // The plugins' settings are read here (they answer on the message thread); writing the file (the big part:
  7470. // every plugin's state, encoded) runs on a thread of its own, so the timed backup no longer freezes the screen
  7471. // (round 151: 180 ms every two minutes on a project with 71 plugins). One at a time.
  7472. if (autosaveRunning->load())
  7473. return;
  7474. const auto folder = autosaveFolder();
  7475. folder.createDirectory();
  7476. const auto stem = projectStem (projectName);
  7477. {
  7478. const uitrace::Scope trace ("autosave: plugin states", false);
  7479. engine.capturePluginStates();
  7480. }
  7481. auto copy = std::make_shared<Song> (engine.getSong());
  7482. auto layout = currentWindowLayout();
  7483. const auto file = newBackupFile (folder, stem, safety::BackupKind::autosaved);
  7484. autosaveRunning->store (true);
  7485. juce::Thread::launch ([copy, layout = std::move (layout), file, running = autosaveRunning, safe = juce::Component::SafePointer<MainComponent> (this), stem] {
  7486. juce::String error;
  7487. const auto ok = ProjectFile::save (*copy, file, error, layout);
  7488. running->store (false);
  7489. juce::MessageManager::callAsync ([safe, ok, error, stem] {
  7490. if (safe == nullptr)
  7491. return;
  7492. if (! ok)
  7493. ui::postHint ({ tr ("Autosave failed: {0}", { error }), {}, false, false }, 6000);
  7494. else
  7495. {
  7496. safe->rotateBackups (stem);
  7497. safe->lastBackupMs = juce::Time::currentTimeMillis(); // (the Simple workflow's "Backed up ... ago")
  7498. safe->lastBackupProject = safe->engine.getSong().projectId;
  7499. }
  7500. });
  7501. });
  7502. }
  7503. // The Simple workflow's line beside "+ Add track" (round 190t): what a beginner needs to know about their work — LYNX
  7504. // backs it up by itself. Empty when there is nothing to say (a new project with nothing in it yet).
  7505. juce::String MainComponent::simpleSaveStatus() const
  7506. {
  7507. return simpleSaveStatusText (engine.isModified(), currentFile.existsAsFile(),
  7508. lastBackupProject == engine.getSong().projectId ? lastBackupMs : 0, juce::Time::currentTimeMillis());
  7509. }
  7510. juce::String MainComponent::simpleSaveStatusText (bool modified, bool hasFile, juce::int64 backupMs, juce::int64 nowMs)
  7511. {
  7512. if (! modified)
  7513. return hasFile ? tr ("All changes saved") : juce::String();
  7514. if (backupMs <= 0)
  7515. return tr ("Not saved yet");
  7516. const auto minutes = (int) ((nowMs - backupMs) / 60000);
  7517. return minutes < 1 ? tr ("Backed up just now") : tr ("Backed up {0} min ago", { juce::String (minutes) });
  7518. }
  7519. void MainComponent::rotateBackups (const juce::String& stem)
  7520. {
  7521. const auto folder = autosaveFolder();
  7522. // (round 190ap: a backup the user labelled in the Versions panel is one to find again: it is left alone and does
  7523. // not count toward the number kept; without labels the rotation is exactly as before)
  7524. const auto files = safety::versions::withoutLabelled (backupFiles (folder), backupLabels (folder, stem));
  7525. for (const auto& old : safety::backupsToRemove (files, stem.toStdString(), autosaveKeep))
  7526. {
  7527. const auto f = folder.getChildFile (juce::String::fromUTF8 (old.c_str()) + ProjectFile::extension);
  7528. f.setReadOnly (false); // (FL clears the read-only flag before deleting an old backup too)
  7529. f.deleteFile();
  7530. }
  7531. }
  7532. void MainComponent::keepOverwrittenCopy (const juce::File& file)
  7533. {
  7534. // FL moves the file a save replaces into its Backup folder as "Song (overwritten on ... at ...)"; LYNX copies it
  7535. // (the save itself still goes through a temporary file and a rename)
  7536. const auto folder = autosaveFolder();
  7537. if (! file.existsAsFile() || file.isAChildOf (folder))
  7538. return;
  7539. folder.createDirectory();
  7540. const auto stem = projectStem (file.getFileNameWithoutExtension());
  7541. if (file.copyFileTo (newBackupFile (folder, stem, safety::BackupKind::overwritten)))
  7542. rotateBackups (stem);
  7543. }
  7544. void MainComponent::saveNewVersion()
  7545. {
  7546. commitSongNotes(); // (round 190ch: notes still being typed are part of what is saved)
  7547. // FL's "Save new version": Song.flp -> Song_2.flp -> Song_3.flp, next to the current file
  7548. if (currentFile == juce::File())
  7549. {
  7550. save (true);
  7551. return;
  7552. }
  7553. const auto folder = currentFile.getParentDirectory();
  7554. const auto name = safety::nextVersionName (currentFile.getFileNameWithoutExtension().toStdString(), [&folder] (const std::string& n) {
  7555. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  7556. });
  7557. const auto file = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  7558. juce::String error;
  7559. engine.capturePluginStates();
  7560. if (! ProjectFile::save (engine.getSong(), file, error, currentWindowLayout()))
  7561. {
  7562. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  7563. return;
  7564. }
  7565. engine.markSaved();
  7566. rememberRecent (file);
  7567. currentFile = file;
  7568. projectName = file.getFileNameWithoutExtension();
  7569. importedSuffix = {};
  7570. updateTitle();
  7571. ui::postHint ({ tr ("Saved as a new version: {0}", { file.getFileName() }), {}, false, false }, 5000);
  7572. }
  7573. void MainComponent::showVersions()
  7574. {
  7575. if (auto* open = findToolWindow ("versions"))
  7576. {
  7577. open->toFront (true);
  7578. return;
  7579. }
  7580. VersionsActions actions;
  7581. const juce::Component::SafePointer<MainComponent> safe (this);
  7582. actions.context = [safe] {
  7583. VersionsContext c;
  7584. if (safe == nullptr)
  7585. return c;
  7586. c.projectFile = safe->currentFile;
  7587. c.projectStem = projectStem (safe->projectName);
  7588. c.backupFolder = autosaveFolder();
  7589. c.extension = ProjectFile::extension;
  7590. return c;
  7591. };
  7592. actions.openAsCopy = [safe] (const juce::File& file, const juce::String& name) {
  7593. if (safe != nullptr)
  7594. safe->confirmDiscard ([safe, file, name] {
  7595. if (safe != nullptr)
  7596. safe->openProjectAsCopy (file, name);
  7597. });
  7598. };
  7599. actions.saveNewVersion = [safe] {
  7600. if (safe != nullptr)
  7601. safe->saveNewVersion();
  7602. };
  7603. if (auto* window = openToolWindow (makeVersionsPanel (std::move (actions)), tr ("Versions"), "versions"))
  7604. window->setResizable (true, false);
  7605. }
  7606. void MainComponent::openProjectAsCopy (const juce::File& file, const juce::String& name)
  7607. {
  7608. // A version or a backup opened to look at or to carry on from: it becomes an unsaved project under `name`, so
  7609. // neither that file nor the project that was open is written over (Save asks where to put it).
  7610. juce::String error;
  7611. auto song = ProjectFile::load (file, error);
  7612. if (! song)
  7613. {
  7614. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  7615. return;
  7616. }
  7617. engine.getPluginHost().applySubstitutes (*song);
  7618. engine.stop();
  7619. engine.rewind();
  7620. engine.setSong (std::move (*song));
  7621. currentFile = juce::File();
  7622. importedFlpFile = juce::File();
  7623. projectName = name;
  7624. importedSuffix = {};
  7625. updateTitle();
  7626. playlist.showSongAfterOpen();
  7627. ui::postHint ({ tr ("Opened as a copy: {0}", { file.getFileName() }), tr ("Save asks where to keep it; the original file is untouched") }, 7000);
  7628. }
  7629. void MainComponent::revertToLastBackup()
  7630. {
  7631. const auto stem = projectStem (projectName);
  7632. const auto name = safety::newestBackup (backupFiles (autosaveFolder()), stem.toStdString());
  7633. if (name.empty())
  7634. {
  7635. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Revert to last backup"),
  7636. tr ("There is no backup of this project yet."));
  7637. return;
  7638. }
  7639. const auto backup = autosaveFolder().getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  7640. const auto when = backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M");
  7641. auto* w = new juce::AlertWindow (tr ("Revert to last backup"),
  7642. tr ("Replace the open project with its backup from {0}?\n{1}\n\nThe project file itself only changes when you save.",
  7643. { when, backup.getFileName() }),
  7644. juce::MessageBoxIconType::QuestionIcon);
  7645. w->addButton (tr ("Revert"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7646. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7647. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup] (int result) {
  7648. if (safe == nullptr || result != 1)
  7649. return;
  7650. juce::String error;
  7651. auto song = ProjectFile::load (backup, error);
  7652. if (! song)
  7653. {
  7654. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  7655. return;
  7656. }
  7657. safe->engine.getPluginHost().applySubstitutes (*song);
  7658. safe->engine.stop();
  7659. safe->engine.rewind();
  7660. safe->engine.setSong (std::move (*song));
  7661. safe->engine.markModified(); // Save writes it back to the project's own file
  7662. safe->updateTitle();
  7663. safe->playlist.showSongAfterOpen();
  7664. }),
  7665. true);
  7666. }
  7667. sessionui::Context MainComponent::sessionContext()
  7668. {
  7669. return { engine, currentFile, projectName, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::File& project) {
  7670. if (safe != nullptr)
  7671. safe->openLynxProject (project);
  7672. } };
  7673. }
  7674. liveui::Context MainComponent::liveContext()
  7675. {
  7676. return { engine, *live, currentFile, [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  7677. if (safe != nullptr)
  7678. safe->confirmDiscard (std::move (then));
  7679. } };
  7680. }
  7681. void MainComponent::startLiveFromCommandLine()
  7682. {
  7683. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  7684. auto value = [&] (const char* flag) {
  7685. const auto at = cli.indexOf (flag);
  7686. return at >= 0 && at + 1 < cli.size() ? cli[at + 1].unquoted() : juce::String();
  7687. };
  7688. auto o = LiveSessionManager::Options();
  7689. o.name = value ("--live-name").isNotEmpty() ? value ("--live-name") : liveui::myName();
  7690. o.projectFile = currentFile;
  7691. if (const auto relay = value ("--live-relay"); relay.isNotEmpty())
  7692. o.relay = relay;
  7693. // round 169j: --live-chat "text" (sent once in), --live-follow (follow the host's transport), --live-resume (the
  7694. // host resumes its interrupted session without asking)
  7695. if (const auto text = value ("--live-chat"); text.isNotEmpty())
  7696. juce::Timer::callAfterDelay (9000, [safe = juce::Component::SafePointer<MainComponent> (this), text] {
  7697. if (safe != nullptr)
  7698. {
  7699. safe->live->sendChat (text);
  7700. liveui::showChat (*safe->live);
  7701. }
  7702. });
  7703. if (cli.contains ("--live-follow"))
  7704. juce::Timer::callAfterDelay (8500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  7705. if (safe != nullptr)
  7706. safe->live->setFollowTransport (true);
  7707. });
  7708. if (cli.contains ("--live-resume"))
  7709. {
  7710. o.projectFile = juce::File();
  7711. o.autoAccept = true;
  7712. if (! live->resumeHost (LiveSessionManager::defaultJournal(), o))
  7713. platform::testModeLog ("live session: nothing to resume");
  7714. return;
  7715. }
  7716. if (cli.contains ("--live-rejoin"))
  7717. {
  7718. // (round 190ah, scripted: a guest goes back into its session without the question)
  7719. if (! live->resumeGuest (LiveSessionManager::defaultGuestJournal(), o))
  7720. platform::testModeLog ("live session: nothing to go back to");
  7721. return;
  7722. }
  7723. if (! cli.contains ("--live-host") && ! cli.contains ("--live-join"))
  7724. {
  7725. if (! platform::testMode())
  7726. liveui::offerResume (liveContext());
  7727. return;
  7728. }
  7729. if (const auto codeFile = value ("--live-host"); codeFile.isNotEmpty())
  7730. {
  7731. o.autoAccept = true; // (scripted: nobody to click "Let them in")
  7732. live->start (o);
  7733. auto poll = std::make_shared<std::function<void (int)>>();
  7734. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), codeFile, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  7735. if (safe == nullptr)
  7736. return;
  7737. if (safe->live->getState() == LiveSessionManager::State::live)
  7738. return (void) juce::File (codeFile).replaceWithText (safe->live->getInviteCode());
  7739. if (safe->live->isActive() && left > 0)
  7740. juce::Timer::callAfterDelay (200, [poll = weak.lock(), left] {
  7741. if (poll != nullptr)
  7742. (*poll) (left - 1);
  7743. });
  7744. else
  7745. juce::File (codeFile).replaceWithText ("ERROR " + safe->live->getStatus());
  7746. };
  7747. (*poll) (150);
  7748. // round 190ai: --live-share file.vst3 — once live, the host shares that plugin and shows its list
  7749. if (const auto pluginFile = value ("--live-share"); pluginFile.isNotEmpty())
  7750. juce::Timer::callAfterDelay (6000, [safe = juce::Component::SafePointer<MainComponent> (this), pluginFile] {
  7751. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  7752. return;
  7753. auto& plugins = safe->engine.getPluginHost();
  7754. plugins.addPluginFile (juce::File (pluginFile));
  7755. juce::String why = "not found";
  7756. bool ok = false;
  7757. for (const auto& type : plugins.getKnownPlugins().getTypes())
  7758. if (! ok && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginFile).getFileName())
  7759. ok = safe->live->sharePlugin (type.createIdentifierString().toStdString(), true, &why);
  7760. platform::testModeLog ("live session: --live-share " + pluginFile + (ok ? " shared" : " NOT shared: " + why));
  7761. liveui::showSharePlugins (*safe->live, safe->engine);
  7762. });
  7763. }
  7764. else if (auto code = value ("--live-join"); code.isNotEmpty())
  7765. {
  7766. if (code.startsWith ("@"))
  7767. code = juce::File (code.substring (1)).loadFileAsString().trim();
  7768. live->join (code, o);
  7769. // round 190ai: --live-use — when the host shares a plugin, a channel of one's own with it, a riff, and its
  7770. // parameter editor (the GUI check of remote plugins)
  7771. if (cli.contains ("--live-use"))
  7772. {
  7773. auto poll = std::make_shared<std::function<void (int)>>();
  7774. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  7775. if (safe == nullptr)
  7776. return;
  7777. if (! safe->live->mayUseSharedPlugins())
  7778. {
  7779. if (left > 0)
  7780. juce::Timer::callAfterDelay (500, [poll = weak.lock(), left] {
  7781. if (poll != nullptr)
  7782. (*poll) (left - 1);
  7783. });
  7784. return;
  7785. }
  7786. std::uint64_t uid = 0;
  7787. const auto channelName = (name + " remote").toStdString();
  7788. safe->engine.editSong ([&] (Song& s) {
  7789. ChannelDef c;
  7790. c.name = channelName;
  7791. c.instrument = InstrumentKind::plugin;
  7792. c.plugin = safe->live->sharedPluginRef (safe->live->sharedPlugins().front());
  7793. const auto* me = s.session.find (s.session.me);
  7794. c.mixerTrack = me != nullptr ? me->insertFirst : 0;
  7795. s.channels.push_back (c);
  7796. Pattern p;
  7797. p.name = channelName + " riff";
  7798. for (int n = 0; n < 4; ++n)
  7799. p.notes.push_back ({ (std::int64_t) n * ppq, ppq / 2, (int) s.channels.size() - 1, 57 + 2 * n, 0.9f });
  7800. s.patterns.push_back (p);
  7801. });
  7802. for (const auto& c : safe->engine.getSong().channels)
  7803. if (c.name == channelName)
  7804. uid = c.uid;
  7805. platform::testModeLog ("live session: --live-use channel " + juce::String (channelName) + " uid " + juce::String ((juce::int64) uid));
  7806. liveui::showHostedEditor ({ { live::Kind::channel, uid, 0 }, -1 });
  7807. };
  7808. (*poll) (120);
  7809. }
  7810. // --live-edit: once in, add a channel of one's own (the GUI check sees it arrive on the host)
  7811. if (cli.contains ("--live-edit"))
  7812. juce::Timer::callAfterDelay (8000, [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name] {
  7813. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  7814. return;
  7815. safe->engine.editSong ([&] (Song& s) {
  7816. ChannelDef c;
  7817. c.name = (name + " synth").toStdString();
  7818. c.instrument = InstrumentKind::synth;
  7819. s.channels.push_back (c);
  7820. });
  7821. });
  7822. }
  7823. }
  7824. void MainComponent::exportPackage()
  7825. {
  7826. // FL's zipped loop package: the project and every sample it uses in one .zip
  7827. const auto stem = projectStem (projectName);
  7828. const auto start = (currentFile != juce::File() ? currentFile.getParentDirectory()
  7829. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory))
  7830. .getChildFile (stem + ".zip");
  7831. fileChooser = lynx::ui::makeFileChooser (tr ("Export project with samples"), start, "*.zip");
  7832. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  7833. [safe = juce::Component::SafePointer<MainComponent> (this), stem] (const juce::FileChooser& chooser) {
  7834. auto zip = chooser.getResult();
  7835. if (safe == nullptr || zip == juce::File())
  7836. return;
  7837. zip = zip.withFileExtension (".zip");
  7838. safe->engine.capturePluginStates();
  7839. ProjectPackage::Result result;
  7840. juce::String error;
  7841. if (! ProjectPackage::exportZip (safe->engine.getSong(), stem, zip, result, error))
  7842. {
  7843. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  7844. return;
  7845. }
  7846. auto text = tr ("{0} saved with {1} samples.", { zip.getFileName(), juce::String (result.files) });
  7847. if (! result.missing.isEmpty())
  7848. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  7849. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Export project with samples"), text);
  7850. });
  7851. }
  7852. void MainComponent::collectSamples()
  7853. {
  7854. // FL's "Export project data files": copy the samples the project uses into one folder (and use the copies)
  7855. fileChooser = lynx::ui::makeFileChooser (tr ("Copy the project's samples to..."),
  7856. currentFile != juce::File() ? currentFile.getParentDirectory()
  7857. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  7858. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  7859. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  7860. const auto folder = chooser.getResult();
  7861. if (safe == nullptr || folder == juce::File())
  7862. return;
  7863. std::map<std::string, std::string> relink;
  7864. ProjectPackage::Result result;
  7865. juce::String error;
  7866. if (! ProjectPackage::collectSamples (safe->engine.getSong(), folder, relink, result, error))
  7867. {
  7868. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not copy"), error);
  7869. return;
  7870. }
  7871. safe->engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  7872. auto text = tr ("{0} samples copied to {1}. The project now uses the copies.", { juce::String (result.files), folder.getFullPathName() });
  7873. if (! result.missing.isEmpty())
  7874. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  7875. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Collect project samples"), text);
  7876. });
  7877. }
  7878. void MainComponent::saveToNewProjectFolder()
  7879. {
  7880. // FL's "Save to new project folder...": <chosen name>/<name>.lynx, so the project gets its own data folder (its
  7881. // recordings go to <name>/Audio/Recorded). This session's takes still in the global recordings folder move along
  7882. // (copied there, the project uses the copies; the originals are then offered for deletion as unused).
  7883. const auto start = currentFile != juce::File() ? currentFile.getParentDirectory()
  7884. : lynx::platform::documentsFolder().getChildFile ("LYNX/Projects");
  7885. start.createDirectory();
  7886. fileChooser = lynx::ui::makeFileChooser (tr ("Save to new project folder"),
  7887. start.getChildFile (projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled")),
  7888. juce::String ("*") + ProjectFile::extension);
  7889. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  7890. const auto chosen = chooser.getResult();
  7891. if (safe == nullptr || chosen == juce::File())
  7892. return;
  7893. const auto name = chosen.getFileNameWithoutExtension();
  7894. auto folder = chosen.getParentDirectory().getChildFile (name);
  7895. if (folder.exists() && ! folder.findChildFiles (juce::File::findFilesAndDirectories, false).isEmpty())
  7896. folder = folder.getNonexistentSibling (false);
  7897. if (! folder.createDirectory())
  7898. {
  7899. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  7900. tr ("Could not create the folder {0}", { folder.getFullPathName() }));
  7901. return;
  7902. }
  7903. auto& self = *safe;
  7904. const auto recorded = folder.getChildFile (safety::recordedSubfolder);
  7905. std::map<std::string, std::string> relink;
  7906. const auto used = safety::referencedSamples (self.engine.getSong());
  7907. for (const auto& take : self.engine.getSessionRecordings())
  7908. if (take.existsAsFile() && take.isAChildOf (AudioEngine::defaultRecordingFolder())
  7909. && std::any_of (used.begin(), used.end(), [&take] (const std::string& p) { return safety::samePath (p, take.getFullPathName().toStdString()); }))
  7910. {
  7911. recorded.createDirectory();
  7912. const auto copy = recorded.getNonexistentChildFile (take.getFileNameWithoutExtension(), take.getFileExtension(), false);
  7913. if (take.copyFileTo (copy))
  7914. relink[take.getFullPathName().toStdString()] = copy.getFullPathName().toStdString();
  7915. }
  7916. if (! relink.empty())
  7917. self.engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  7918. const auto file = folder.getChildFile (name + ProjectFile::extension);
  7919. juce::String error;
  7920. self.engine.capturePluginStates();
  7921. if (! ProjectFile::save (self.engine.getSong(), file, error, self.currentWindowLayout()))
  7922. {
  7923. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  7924. return;
  7925. }
  7926. self.engine.markSaved();
  7927. self.rememberRecent (file);
  7928. self.currentFile = file;
  7929. self.projectName = name;
  7930. self.importedSuffix = {};
  7931. self.updateTitle();
  7932. ui::postHint ({ tr ("Saved in its own folder: {0}", { folder.getFullPathName() }), {}, false, false }, 5000);
  7933. });
  7934. }
  7935. void MainComponent::startSession()
  7936. {
  7937. // Like FL's backup on crash: a marker exists while LYNX runs; finding one at start means the last session
  7938. // ended without closing (crash, power loss), so the newest backup written during it is offered.
  7939. sessionLock = std::make_unique<juce::InterProcessLock> ("LYNX-ui-session");
  7940. if (! sessionLock->enter (0))
  7941. {
  7942. sessionLock.reset(); // another LYNX window is running: it owns the marker
  7943. return;
  7944. }
  7945. sessionMarker = lynx::platform::settingsFile ("session-running.txt");
  7946. if (sessionMarker.existsAsFile())
  7947. {
  7948. const auto previousStart = juce::Time (sessionMarker.loadFileAsString().trim().getLargeIntValue());
  7949. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this), previousStart] {
  7950. if (safe != nullptr)
  7951. safe->checkPreviousSession (previousStart);
  7952. });
  7953. }
  7954. sessionMarker.getParentDirectory().createDirectory();
  7955. sessionMarker.replaceWithText (juce::String (juce::Time::getCurrentTime().toMilliseconds()));
  7956. // takes that were recording when LYNX stopped (crash, power loss, closed while recording): after the backup offer
  7957. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  7958. if (safe != nullptr)
  7959. safe->checkInterruptedTakes();
  7960. });
  7961. }
  7962. void MainComponent::checkInterruptedTakes()
  7963. {
  7964. if (juce::Component::getCurrentlyModalComponent() != nullptr) // a dialog is open (the backup offer): ask later
  7965. {
  7966. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  7967. if (safe != nullptr)
  7968. safe->checkInterruptedTakes();
  7969. });
  7970. return;
  7971. }
  7972. std::vector<juce::File> folders { engine.getRecordingFolder() };
  7973. const auto takes = engine.recoverInterruptedTakes (folders);
  7974. if (takes.empty())
  7975. return;
  7976. juce::StringArray names;
  7977. for (const auto& j : takes)
  7978. names.add (juce::File (juce::String::fromUTF8 (j.wav.c_str())).getFileName());
  7979. const auto folder = juce::File (juce::String::fromUTF8 (takes.front().wav.c_str())).getParentDirectory();
  7980. auto* w = new juce::AlertWindow (tr ("Recordings recovered"),
  7981. tr ("LYNX SHARE was recording when it stopped. These takes were saved and repaired:\n{0}\n\nPut them on the Playlist "
  7982. "where they were recorded?", { names.joinIntoString ("\n") }),
  7983. juce::MessageBoxIconType::InfoIcon);
  7984. w->addButton (tr ("Put them on the Playlist"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7985. w->addButton (tr ("Show the folder"), 2);
  7986. w->addButton (tr ("Keep the files only"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7987. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), takes, folder] (int result) {
  7988. if (safe == nullptr)
  7989. return;
  7990. if (result == 1)
  7991. {
  7992. const auto placed = safe->engine.placeRecoveredTakes (takes);
  7993. ui::postHint ({ tr ("{0} recovered take(s) placed on the Playlist", { juce::String (placed) }), {}, false, false }, 5000);
  7994. }
  7995. else
  7996. {
  7997. if (result == 2)
  7998. folder.startAsProcess();
  7999. safe->engine.forgetInterruptedTakes (takes);
  8000. }
  8001. }),
  8002. true);
  8003. }
  8004. void MainComponent::checkPreviousSession (juce::Time sessionStart)
  8005. {
  8006. if (juce::Component::getCurrentlyModalComponent() != nullptr) // the setup wizard or another dialog: ask later
  8007. {
  8008. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this), sessionStart] {
  8009. if (safe != nullptr)
  8010. safe->checkPreviousSession (sessionStart);
  8011. });
  8012. return;
  8013. }
  8014. const auto folder = autosaveFolder();
  8015. const auto name = safety::crashRecoveryCandidate (backupFiles (folder), sessionStart.toMilliseconds());
  8016. if (name.empty())
  8017. return; // nothing was saved in that session
  8018. const auto backup = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  8019. auto* w = new juce::AlertWindow (tr ("LYNX SHARE did not close properly"),
  8020. tr ("The last session ended unexpectedly. Open the newest backup it saved?\n{0} ({1})",
  8021. { backup.getFileName(), backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M") }),
  8022. juce::MessageBoxIconType::WarningIcon);
  8023. w->addButton (tr ("Open backup"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8024. w->addButton (tr ("Open backup folder"), 2);
  8025. w->addButton (tr ("Ignore"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8026. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup, folder] (int result) {
  8027. if (safe == nullptr)
  8028. return;
  8029. if (result == 1)
  8030. safe->confirmDiscard ([safe, backup] {
  8031. if (safe != nullptr)
  8032. safe->openLynxProject (backup);
  8033. });
  8034. else if (result == 2)
  8035. folder.startAsProcess();
  8036. }),
  8037. true);
  8038. }
  8039. void MainComponent::newProject (bool askAlways)
  8040. {
  8041. confirmDiscard ([this, askAlways] {
  8042. if (! askAlways && ! newProjectDialogEnabled())
  8043. {
  8044. // FL's File › New: a new project from the default template (issue #123)
  8045. bool missing = false;
  8046. auto song = makeDefaultTemplateProject (&missing);
  8047. startNewProject (std::move (song), {});
  8048. if (missing)
  8049. ui::postHint ({ tr ("The default template was not found; LYNX SHARE's default project opened instead") }, 6000);
  8050. return;
  8051. }
  8052. showNewProjectDialog ([safe = juce::Component::SafePointer<MainComponent> (this)] (Song song, juce::File file) {
  8053. if (safe != nullptr)
  8054. safe->startNewProject (std::move (song), file);
  8055. });
  8056. });
  8057. }
  8058. void MainComponent::openStartupProject()
  8059. {
  8060. // (only over the untouched start-up song: a file, a resumed session or an edit made meanwhile stays)
  8061. if (currentFile != juce::File() || projectName.isNotEmpty() || engine.isModified())
  8062. return;
  8063. switch (startupProject())
  8064. {
  8065. case StartupProject::lastProject:
  8066. // FL's "Last used project": the project itself (saving goes to it), when it is still there
  8067. if (const auto last = recent.getFile (0); last.existsAsFile())
  8068. {
  8069. openFile (last);
  8070. return;
  8071. }
  8072. break; // (none, or gone: the default template, as FL's default)
  8073. case StartupProject::emptyProject:
  8074. if (const auto empty = builtInTemplateIndex ("Empty"); empty >= 0)
  8075. startNewProject (makeNewProject (empty), {});
  8076. return;
  8077. case StartupProject::defaultTemplate:
  8078. break;
  8079. }
  8080. if (defaultTemplate().isLynxDefault())
  8081. return; // (the start-up song is LYNX's default already)
  8082. bool missing = false;
  8083. auto song = makeDefaultTemplateProject (&missing);
  8084. if (missing)
  8085. {
  8086. ui::postHint ({ tr ("The default template was not found; LYNX SHARE's default project opened instead") }, 6000);
  8087. return;
  8088. }
  8089. startNewProject (std::move (song), {});
  8090. }
  8091. void MainComponent::startNewProject (Song song, const juce::File& file)
  8092. {
  8093. forgetSeekMark();
  8094. engine.stop();
  8095. engine.rewind();
  8096. engine.setSong (std::move (song));
  8097. engine.markCreatedNow(); // Project info › created (a template's own date is kept, as FL does)
  8098. currentFile = juce::File();
  8099. projectName = {};
  8100. importedSuffix = {};
  8101. if (file != juce::File())
  8102. {
  8103. juce::String error;
  8104. file.getParentDirectory().createDirectory();
  8105. if (ProjectFile::save (engine.getSong(), file, error))
  8106. {
  8107. engine.markSaved();
  8108. rememberRecent (file);
  8109. currentFile = file;
  8110. projectName = file.getFileNameWithoutExtension();
  8111. }
  8112. else
  8113. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  8114. }
  8115. updateTitle();
  8116. }
  8117. // The user's choice after a plugin's editor crashed (issue #32): save under a new name now, and/or run that plugin in a
  8118. // separate process from now on (like Processing › "Always run … in a separate process": persisted, applied at once)
  8119. void MainComponent::announceEditorCrash (const juce::String& plugin)
  8120. {
  8121. const auto offerSeparate = ! pluginSandboxEnabled() && ! pluginAlwaysSeparate (plugin) && plugin != "?";
  8122. auto options = juce::MessageBoxOptions()
  8123. .withIconType (juce::MessageBoxIconType::WarningIcon)
  8124. .withTitle (tr ("Plugin crashed"))
  8125. .withMessage (tr ("{0} crashed. Save your project now (as a new file is safest).", { plugin }) + "\n\n"
  8126. + tr ("Its window was closed so that LYNX SHARE could keep running. The plugin may not work "
  8127. "properly until the project is opened again."))
  8128. .withButton (tr ("Save as..."));
  8129. if (offerSeparate)
  8130. options = options.withButton (tr ("Always run {0} in a separate process", { plugin }));
  8131. options = options.withButton (tr ("Close"));
  8132. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), plugin, offerSeparate] (int result) {
  8133. if (safe == nullptr)
  8134. return;
  8135. if (result == 1)
  8136. safe->save (true);
  8137. else if (result == 2 && offerSeparate)
  8138. PluginWindows::alwaysRunSeparately (safe->engine, plugin); // (round 190gg: the same as the crash prompt's)
  8139. });
  8140. }
  8141. // Round 190ao: "Reload" of a crash prompt: the plugins of that name that are down (the prompt only knows the name the
  8142. // plugin reports; when the project knows it under another name, every plugin that is down)
  8143. void MainComponent::reloadCrashedPlugins (const juce::String& plugin)
  8144. {
  8145. auto which = engine.downHostedPlugins (plugin.toStdString());
  8146. if (which.empty())
  8147. which = engine.downHostedPlugins();
  8148. if (! which.empty())
  8149. PluginWindows::reload (engine, which);
  8150. }
  8151. // Round 176a: round 174a's "Plugin crashed" prompt for a plugin whose separate process died. LYNX itself is unharmed
  8152. // (the plugin ran in its own process), so it offers the save and says how to get the plugin back.
  8153. void MainComponent::announceSeparateProcessCrash (const juce::String& plugin, bool crashed, bool bits32, const juce::StringArray& withIt)
  8154. {
  8155. const auto name = plugin.isNotEmpty() ? plugin : tr ("A plugin");
  8156. const auto where = bits32 ? tr ("{0} crashed in the 32-bit bridge.", { name }) : tr ("{0} crashed in its separate process.", { name });
  8157. // round 190jg: the other plugins of its process group (per vendor / all together) stopped with it; Reload brings all back
  8158. const auto group = withIt.isEmpty() ? juce::String()
  8159. : "\n" + tr ("The other plugins in the same process stopped with it: {0}.", { withIt.joinIntoString (", ") });
  8160. auto options = juce::MessageBoxOptions()
  8161. .withIconType (juce::MessageBoxIconType::WarningIcon)
  8162. .withTitle (tr ("Plugin crashed"))
  8163. .withMessage ((crashed ? where : tr ("{0} stopped responding (separate process).", { name })) + group + "\n\n"
  8164. + tr ("Only its process was affected: LYNX SHARE and your project kept running, and the plugin "
  8165. "was muted. Save your project.")
  8166. + " " + tr ("Reload starts it again with the settings from the last save or backup."))
  8167. .withButton (tr ("Reload")) // (round 190ao: without reopening the project; only on request)
  8168. .withButton (tr ("Save as..."))
  8169. .withButton (tr ("Close"));
  8170. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), plugin, everyDown = ! withIt.isEmpty()] (int result) {
  8171. if (safe == nullptr)
  8172. return;
  8173. if (result == 1 && everyDown) // (round 190jg: the whole group came down; all of it comes back)
  8174. {
  8175. if (const auto which = safe->engine.downHostedPlugins(); ! which.empty())
  8176. PluginWindows::reload (safe->engine, which);
  8177. }
  8178. else if (result == 1)
  8179. safe->reloadCrashedPlugins (plugin);
  8180. else if (result == 2)
  8181. safe->save (true);
  8182. });
  8183. }
  8184. void MainComponent::saveAsTemplate()
  8185. {
  8186. auto* w = new juce::AlertWindow (tr ("Save as template"), tr ("The template appears in File › New project... (saved in {0})", { userTemplatesFolder().getFullPathName() }),
  8187. juce::MessageBoxIconType::NoIcon);
  8188. w->addTextEditor ("name", projectName.isNotEmpty() ? projectName : tr ("My template"));
  8189. w->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8190. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8191. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, safe = juce::Component::SafePointer<MainComponent> (this)] (int result) {
  8192. if (result != 1 || safe == nullptr)
  8193. return;
  8194. safe->engine.capturePluginStates();
  8195. juce::String error;
  8196. if (! saveUserTemplate (safe->engine.getSong(), w->getTextEditorContents ("name"), error))
  8197. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  8198. }), true);
  8199. }
  8200. juce::AlertWindow* MainComponent::buildSaveCopyWindow (const juce::String& json, std::shared_ptr<juce::TextEditor> list)
  8201. {
  8202. // round 190hq (B20): the release, and what the copy loses there (worked out again for each release)
  8203. const auto releases = olderlynx::releases();
  8204. auto* w = new juce::AlertWindow (tr ("Save a copy for an older LYNX"),
  8205. tr ("The copy opens in the release you pick. The open project stays as it is."), juce::MessageBoxIconType::NoIcon);
  8206. juce::StringArray names;
  8207. for (const auto& r : releases)
  8208. names.add ("LYNX SHARE " + r);
  8209. w->addComboBox ("release", names, tr ("For"));
  8210. list->setMultiLine (true);
  8211. list->setReadOnly (true);
  8212. list->setScrollbarsShown (true);
  8213. list->setCaretVisible (false);
  8214. list->setSize (560, 240);
  8215. w->addCustomComponent (list.get());
  8216. auto* combo = w->getComboBoxComponent ("release");
  8217. auto update = [json, releases, combo, list] {
  8218. const auto copy = olderlynx::forRelease (json, releases[juce::jmax (0, combo->getSelectedItemIndex())]);
  8219. juce::String sound, other;
  8220. for (const auto& l : copy.lost)
  8221. (l.sound ? sound : other) << "- " << tr (l.text, { l.detail }) << "\n";
  8222. juce::String text;
  8223. if (sound.isNotEmpty())
  8224. text << tr ("May sound different there:") << "\n" << sound << "\n";
  8225. if (other.isNotEmpty())
  8226. text << tr ("Left out (the sound stays):") << "\n" << other;
  8227. if (text.isEmpty())
  8228. text = tr ("Nothing is lost: the copy holds the whole project.");
  8229. list->setText (text.trimEnd(), false);
  8230. };
  8231. combo->onChange = update;
  8232. combo->setSelectedItemIndex (0, juce::dontSendNotification);
  8233. update();
  8234. w->addButton (tr ("Save copy..."), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8235. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8236. return w;
  8237. }
  8238. void MainComponent::saveCopyForOlder()
  8239. {
  8240. // round 190hq (B20, engine/ProjectDowngrade.h): the release and its losses, then where to save the copy. The open
  8241. // project and its file are not touched.
  8242. engine.capturePluginStates();
  8243. const auto json = ProjectFile::toJson (engine.getSong());
  8244. const auto releases = olderlynx::releases();
  8245. auto list = std::make_shared<juce::TextEditor>();
  8246. auto* w = buildSaveCopyWindow (json, list);
  8247. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, list, json, releases, safe = juce::Component::SafePointer<MainComponent> (this)] (int result) {
  8248. const auto release = releases[juce::jmax (0, w->getComboBoxComponent ("release")->getSelectedItemIndex())];
  8249. if (result != 1 || safe == nullptr)
  8250. return;
  8251. const auto start = (safe->currentFile != juce::File() ? safe->currentFile.getParentDirectory()
  8252. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory))
  8253. .getChildFile (olderlynx::copyName (projectStem (safe->projectName), release) + ProjectFile::extension);
  8254. safe->fileChooser = lynx::ui::makeFileChooser (tr ("Save a copy for LYNX SHARE {0}", { release }), start, juce::String ("*") + ProjectFile::extension);
  8255. lynx::ui::launchChooser (safe->fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  8256. [json, release] (const juce::FileChooser& chooser) {
  8257. auto file = chooser.getResult();
  8258. if (file == juce::File())
  8259. return;
  8260. file = ProjectFile::withProjectExtension (file);
  8261. const auto copy = olderlynx::forRelease (json, release);
  8262. juce::TemporaryFile temp (file);
  8263. if (! copy.ok || ! temp.getFile().replaceWithText (copy.json, false, false, nullptr) || ! temp.overwriteTargetFileWithTemporary()
  8264. || file.loadFileAsString() != copy.json)
  8265. {
  8266. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  8267. copy.ok ? file.getFullPathName() : copy.error);
  8268. return;
  8269. }
  8270. ui::postHint ({ tr ("Saved a copy for LYNX SHARE {0}", { release }), file.getFileName() }, 6000);
  8271. });
  8272. }), true);
  8273. }
  8274. void MainComponent::chooseFileToOpen()
  8275. {
  8276. confirmDiscard ([this] { chooseFileToOpenNow(); });
  8277. }
  8278. void MainComponent::chooseFileToOpenNow()
  8279. {
  8280. fileChooser = lynx::ui::makeFileChooser (tr ("Open project"), currentFile.getParentDirectory(),
  8281. juce::String ("*") + ProjectFile::extension
  8282. + ";*.dawproj;*.dawproject;*.flp;*.als;*.flm;*.band;projectData;ProjectData;*.blx;*.zip;*.lynxpack;*.mid;*.midi");
  8283. // (a GarageBand .band is a folder: macOS's dialog shows it as one file; elsewhere its "projectData" is picked)
  8284. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  8285. [this] (const juce::FileChooser& chooser) {
  8286. const auto result = chooser.getResult();
  8287. if (result.existsAsFile() || ProjectPackage::garageBandPackage (result) != juce::File())
  8288. openFile (result);
  8289. });
  8290. }
  8291. void MainComponent::openFileRequest (const juce::File& file)
  8292. {
  8293. const juce::Component::SafePointer<MainComponent> safe (this);
  8294. if (projectLoadRunning())
  8295. {
  8296. juce::Timer::callAfterDelay (500, [safe, file] {
  8297. if (safe != nullptr)
  8298. safe->openFileRequest (file);
  8299. });
  8300. return;
  8301. }
  8302. confirmDiscard ([safe, file] {
  8303. if (safe != nullptr)
  8304. safe->openFile (file);
  8305. });
  8306. }
  8307. void MainComponent::openFile (const juce::File& file)
  8308. {
  8309. // round 190np: the Next-3 items "Open one of your .flp projects / .als sets"
  8310. onboardCtx.openedFlp = onboardCtx.openedFlp || file.hasFileExtension ("flp");
  8311. onboardCtx.openedAls = onboardCtx.openedAls || file.hasFileExtension ("als");
  8312. forgetSeekMark(); // (another project: FL's mark and a pause don't carry over)
  8313. juce::String error;
  8314. crashguard::note (("opening project " + file.getFileName()).toStdString()); // session breadcrumb (round 111)
  8315. // (round 190ic: a GarageBand song that arrived as one zipped file keeps its ".band" name: unpacked as a package)
  8316. // (round 190jr: a .blx that is a zip of the project, rather than its JSON, is unpacked the same way)
  8317. if (file.hasFileExtension ("zip") || (file.hasFileExtension ("band") && file.existsAsFile())
  8318. || (file.hasFileExtension ("blx") && [&file] { juce::FileInputStream in (file); return in.openedOk() && in.readByte() == 'P' && in.readByte() == 'K'; }()))
  8319. {
  8320. // a project package (File › Export project with samples, or FL's zipped loop package): extracted into a
  8321. // folder of its own, then the project inside is opened (its samples are found next to it)
  8322. const auto project = ProjectPackage::extractZip (file, ProjectPackage::defaultExtractRoot(), error);
  8323. if (project == juce::File())
  8324. {
  8325. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  8326. return;
  8327. }
  8328. openFile (project);
  8329. return;
  8330. }
  8331. if (file.hasFileExtension (sessionpack::extension))
  8332. {
  8333. // Online Sessions (round 168a): a project a friend sent (opened after a summary) or a part sent back (merged)
  8334. sessionui::openPackage (sessionContext(), file);
  8335. return;
  8336. }
  8337. if (file.hasFileExtension ("mid;midi"))
  8338. {
  8339. auto song = MidiFileIo::loadSong (file, error);
  8340. if (! song)
  8341. {
  8342. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  8343. return;
  8344. }
  8345. engine.stop();
  8346. engine.rewind();
  8347. engine.setSong (std::move (*song));
  8348. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  8349. projectName = file.getFileNameWithoutExtension();
  8350. rememberRecent (file);
  8351. importedSuffix = " " + tr ("(imported from MIDI)");
  8352. updateTitle();
  8353. return;
  8354. }
  8355. // a GarageBand project (round 190ic): the .band folder, also when a file inside it was picked
  8356. if (const auto band = ProjectPackage::garageBandPackage (file); band != juce::File() && band != file)
  8357. {
  8358. openFile (band);
  8359. return;
  8360. }
  8361. // (a Live set takes the .flp import's path, round 175a; an FL Studio Mobile project too, round 182c; a GarageBand
  8362. // project too, round 190ic)
  8363. if (file.hasFileExtension ("flp;als;flm;songtmpl;dawproject;blx") || ProjectPackage::garageBandPackage (file) == file)
  8364. {
  8365. if (! persistent) // (command-line modes open synchronously, without scanning)
  8366. {
  8367. importFlp (file);
  8368. return;
  8369. }
  8370. // behind a progress panel (round 112): the project's unknown plugins get a targeted scan of just their files,
  8371. // the samples are decoded off the message thread, the hosted plugins are created one by one with their names
  8372. // shown; the panel's bar never sits still at 0 %
  8373. if (projectLoadRunning())
  8374. return;
  8375. openFlpWithProgress (*this, engine, file, [safe = juce::Component::SafePointer<MainComponent> (this), file] (bool ok, const juce::String& error) {
  8376. if (safe == nullptr)
  8377. return;
  8378. if (! ok)
  8379. {
  8380. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  8381. return;
  8382. }
  8383. safe->flpImported (file);
  8384. });
  8385. return;
  8386. }
  8387. openLynxProject (file);
  8388. }
  8389. void MainComponent::importFlp (const juce::File& file)
  8390. {
  8391. juce::String error;
  8392. loadtrace::begin (file.getFullPathName().toStdString());
  8393. const auto ok = engine.importFlpFile (file, error);
  8394. loadtrace::end();
  8395. if (! ok)
  8396. {
  8397. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  8398. return;
  8399. }
  8400. flpImported (file);
  8401. }
  8402. void MainComponent::flpImported (const juce::File& file)
  8403. {
  8404. {
  8405. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  8406. importedFlpFile = file;
  8407. projectName = file.getFileNameWithoutExtension();
  8408. rememberRecent (file);
  8409. importedSuffix = " " + (file.hasFileExtension ("als") ? tr ("(imported from .als)")
  8410. : file.hasFileExtension ("dawproject") ? tr ("(imported from DAWproject)")
  8411. : file.hasFileExtension ("flm;songtmpl") ? tr ("(imported from FL Studio Mobile)")
  8412. : file.hasFileExtension ("band") ? tr ("(imported from GarageBand)")
  8413. : file.hasFileExtension ("blx") ? tr ("(imported from BandLab)")
  8414. : tr ("(imported from FL Studio)"));
  8415. updateTitle();
  8416. playlist.showSongAfterOpen();
  8417. showMissingFiles (true);
  8418. // FL opens Project info when the project's "Show on opening" box is on (event 0x0A, REA round 167g)
  8419. if (engine.getSong().info.showOnOpen && platform::testMode())
  8420. platform::testModeLog ("project info shown on open");
  8421. else if (engine.getSong().info.showOnOpen)
  8422. openSettings ((int) SettingsPage::info);
  8423. }
  8424. }
  8425. void MainComponent::chooseFileToOpenWithoutPlugins()
  8426. {
  8427. confirmDiscard ([this] {
  8428. fileChooser = lynx::ui::makeFileChooser (tr ("Open without third-party plugins"), currentFile.getParentDirectory(), juce::String ("*") + ProjectFile::extension);
  8429. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  8430. [this] (const juce::FileChooser& chooser) {
  8431. if (chooser.getResult().existsAsFile())
  8432. {
  8433. crashguard::note (("opening project without plugins " + chooser.getResult().getFileName()).toStdString());
  8434. openLynxProject (chooser.getResult(), true);
  8435. }
  8436. });
  8437. });
  8438. }
  8439. void MainComponent::showPluginsOff()
  8440. {
  8441. if (auto* open = findToolWindow ("pluginsOff"))
  8442. {
  8443. open->toFront (true);
  8444. return;
  8445. }
  8446. if (auto* window = openToolWindow (makePluginsOffPanel (engine), tr ("Third-party plugins"), "pluginsOff"))
  8447. window->setResizable (true, false);
  8448. }
  8449. void MainComponent::openLynxProject (const juce::File& file, bool withoutPlugins)
  8450. {
  8451. juce::String error, savedBy;
  8452. ProjectFile::WindowLayout layout; // round 190mr (DF-141)
  8453. auto song = ProjectFile::load (file, error, &savedBy, &layout);
  8454. if (! song)
  8455. {
  8456. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  8457. return;
  8458. }
  8459. withoutPlugins = withoutPlugins || std::exchange (nextOpenWithoutPlugins, false);
  8460. engine.stop();
  8461. engine.rewind();
  8462. if (withoutPlugins)
  8463. {
  8464. // round 190ap: no hosted plugin is created and no slot is changed (no substitutes either): each keeps the
  8465. // settings the file has, which is also what a save made now writes
  8466. engine.setSongWithPluginsOff (std::move (*song));
  8467. }
  8468. else
  8469. {
  8470. // missing plugins get their LYNX substitute; substitutes whose original is installed now go back to it
  8471. engine.getPluginHost().applySubstitutes (*song);
  8472. engine.setSong (std::move (*song));
  8473. }
  8474. currentFile = file;
  8475. importedFlpFile = juce::File();
  8476. projectName = file.getFileNameWithoutExtension();
  8477. // round 190lo (LYNX extra, off by default): clips with polyphonic note edits get their analysis ready in the background
  8478. if (const auto queued = PolyEditorWindows::prepareEditedClips (engine); queued > 0)
  8479. platform::testModeLog ("polyphonic edits prepared in the background: " + juce::String (queued) + " clips");
  8480. importedSuffix = {};
  8481. rememberRecent (file);
  8482. updateTitle();
  8483. playlist.showSongAfterOpen();
  8484. applyProjectWindowLayout (layout); // round 190mr (DF-141)
  8485. // pain point 37 (round 177d): a project from a newer LYNX SHARE opens, but saving it here would drop what that
  8486. // version added, so say so once (FL warns about a project from a more recent version too)
  8487. if (safety::savedByNewerVersion (savedBy.toStdString(), JUCE_APPLICATION_VERSION_STRING))
  8488. {
  8489. platform::testModeLog ("project saved by newer version " + savedBy);
  8490. if (! platform::testMode())
  8491. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Saved by a newer version"),
  8492. tr ("This project was saved by LYNX SHARE {0}, and this is {1}. What the newer version added may be "
  8493. "lost if you save it here: use File › Save as... to keep the original.",
  8494. { savedBy, JUCE_APPLICATION_VERSION_STRING }));
  8495. }
  8496. if (engine.pluginsOff())
  8497. {
  8498. platform::testModeLog ("project opened without third-party plugins");
  8499. ui::postHint ({ tr ("Opened without third-party plugins: their settings are kept"), {}, false, false }, 8000);
  8500. if (persistent && ! engine.hostedPluginUses().empty())
  8501. showPluginsOff();
  8502. }
  8503. if (persistent)
  8504. {
  8505. showMissingFiles (true);
  8506. if (engine.getSong().info.showOnOpen && platform::testMode())
  8507. platform::testModeLog ("project info shown on open");
  8508. else if (engine.getSong().info.showOnOpen)
  8509. openSettings (1);
  8510. }
  8511. }
  8512. void MainComponent::openSettings (int page)
  8513. {
  8514. lastSettingsPage = page; // (issue #181: Ctrl+, opens this page next time)
  8515. const juce::Component::SafePointer<MainComponent> safe (this);
  8516. SettingsHooks hooks;
  8517. hooks.browserFoldersChanged = [safe] {
  8518. if (safe != nullptr)
  8519. safe->browser.reloadUserFolders();
  8520. };
  8521. hooks.getGeneral = [safe] {
  8522. GeneralOptions o;
  8523. if (safe == nullptr)
  8524. return o;
  8525. o.language = i18n::saved();
  8526. o.uiFont = theme::savedUiFont();
  8527. o.textSize = theme::savedTextSize();
  8528. o.boldText = theme::savedBoldText();
  8529. o.condensedLabels = theme::savedCondensedLabels();
  8530. o.uiScale = safe->toolbarLayout.uiScale;
  8531. o.compactMenus = theme::menus::compact();
  8532. o.waveSpectral = ui::WaveformCache::spectral;
  8533. o.waveStereo = ui::WaveformCache::stereo;
  8534. o.noteNames = notenames::currentStyle.load();
  8535. o.noteFlats = notenames::currentFlats.load();
  8536. o.noteNamesEveryKey = notenames::everyKey.load();
  8537. o.rackPlayheadColumn = ChannelRackComponent::playheadColumn.load();
  8538. o.rackStepsChannelColour = ChannelRackComponent::stepsChannelColour.load();
  8539. o.reducedEffects = skin::reducedEffects();
  8540. o.animationRate = ui::FrameTicker::rateLimit();
  8541. o.artMotion = skin::artMotion();
  8542. o.uiAnimations = ui::motion::enabled();
  8543. o.gpuRendering = gpuRenderingEnabled();
  8544. o.editorsInMainWindow = editorsInMainWindowSetting(); // (round 190jy)
  8545. o.pluginStyle = skin::forcedStyle();
  8546. o.splash = safe->startup.splash;
  8547. o.startupSound = safe->startup.sound;
  8548. o.scanAtStart = backgroundScanAtStart();
  8549. o.supportNote = support::noteEnabled();
  8550. o.defaultTemplate = juce::String::fromUTF8 (defaultTemplate().toText().c_str());
  8551. o.startupProject = (int) startupProject();
  8552. o.typingPiano = safe->typingPiano;
  8553. o.keepEditorsOpen = ChannelRackComponent::keepEditorsOpen;
  8554. o.selectFirstChannelWithNotes = ChannelRackComponent::selectFirstChannelWithNotes;
  8555. o.monophonicPainting = PianoRollComponent::monophonicPainting;
  8556. o.alternateMeterScale = meterscale::alternate();
  8557. o.detachNewPlugins = safe->engine.detachesNewPlugins();
  8558. o.autoSelectLinked = ChannelRackComponent::autoSelectLinked;
  8559. o.alternateUndo = safe->alternateUndo;
  8560. o.rememberSeek = EditorGlobals::get().rememberSeek;
  8561. o.stretchedClipsLoop = stretchedClipsLoop();
  8562. o.autoClipsAtPlayback = autoclipplace::atPlayback();
  8563. o.disableTypingPriority = pluginkeys::newPluginsHostFirst().load();
  8564. o.layoutStyle = (int) safe->layoutStyle;
  8565. o.alsSessionOnPlaylist = AudioEngine::alsSessionOnPlaylist.load();
  8566. o.editPatternsIn = PlaylistComponent::editPatternsIn;
  8567. o.undoLevels = safe->engine.getUndoLevels();
  8568. o.autosaveMinutes = safe->autosaveMinutes;
  8569. o.autosaveKeep = safe->autosaveKeep;
  8570. o.askUnusedRecordings = safe->askUnusedRecordings;
  8571. o.backupWaitsForQuiet = safe->backupWaitsForQuiet;
  8572. o.backupLongestWaitMinutes = safe->backupLongestWaitMinutes;
  8573. o.hoverValues = safe->hoverValues;
  8574. o.crossfadesInNewProjects = newProjectDefaults().autoCrossfades;
  8575. o.linkTracksInNewProjects = newProjectDefaults().linkTracks;
  8576. o.pluginSandbox = (int) pluginSandboxMode();
  8577. o.menuEntry = appImageMenuEntryInstalled();
  8578. o.pluginSubstitutes = pluginSubstitutesEnabled();
  8579. o.sampleAccurateAutomation = sampleAccurateAutomation();
  8580. o.limitEditors = editorlimit::enabled();
  8581. o.crashReports = (int) crashreporter::consent();
  8582. o.checkUpdates = updater::automatic();
  8583. o.remoteControl = remoteui::enabled();
  8584. return o;
  8585. };
  8586. hooks.setGeneral = [safe] (const GeneralOptions& o) {
  8587. if (safe == nullptr)
  8588. return;
  8589. auto& self = *safe;
  8590. if (o.uiScale != self.toolbarLayout.uiScale)
  8591. {
  8592. auto layout = self.toolbarLayout;
  8593. layout.uiScale = toolbarlayout::clampScale (o.uiScale);
  8594. self.setToolbarLayout (layout, true);
  8595. }
  8596. theme::menus::setCompact (o.compactMenus);
  8597. ui::FrameTicker::rateLimit() = o.animationRate; // (the tickers read it every frame)
  8598. ui::motion::enabled() = o.uiAnimations;
  8599. if (o.reducedEffects != skin::reducedEffects() || o.pluginStyle != skin::forcedStyle() || o.artMotion != skin::artMotion())
  8600. {
  8601. skin::setArtMotion (o.artMotion);
  8602. skin::setReducedEffects (o.reducedEffects);
  8603. skin::setForcedStyle (o.pluginStyle);
  8604. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // open editors redraw at once
  8605. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  8606. }
  8607. if (o.noteNames != notenames::currentStyle.load() || o.noteFlats != notenames::currentFlats.load()
  8608. || o.noteNamesEveryKey != notenames::everyKey.load())
  8609. {
  8610. notenames::currentStyle.store (juce::jlimit (0, 2, o.noteNames));
  8611. notenames::currentFlats.store (o.noteFlats);
  8612. notenames::everyKey.store (o.noteNamesEveryKey);
  8613. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // the keyboards redraw with the new names
  8614. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  8615. }
  8616. if (o.rackPlayheadColumn != ChannelRackComponent::playheadColumn.load()
  8617. || o.rackStepsChannelColour != ChannelRackComponent::stepsChannelColour.load())
  8618. {
  8619. ChannelRackComponent::playheadColumn.store (o.rackPlayheadColumn);
  8620. ChannelRackComponent::stepsChannelColour.store (o.rackStepsChannelColour);
  8621. self.rack.repaint();
  8622. }
  8623. if (o.gpuRendering != gpuRenderingEnabled())
  8624. setGpuRenderingEnabled (o.gpuRendering);
  8625. if (o.editorsInMainWindow != editorsInMainWindowSetting()) // round 190jy: the open docked editors move at once
  8626. {
  8627. setEditorsInMainWindow (o.editorsInMainWindow);
  8628. self.saveUiSettings();
  8629. }
  8630. if (o.waveSpectral != ui::WaveformCache::spectral || o.waveStereo != ui::WaveformCache::stereo)
  8631. {
  8632. ui::WaveformCache::spectral = o.waveSpectral;
  8633. ui::WaveformCache::stereo = o.waveStereo;
  8634. ui::WaveformCache::getInstance()->settingsChanged();
  8635. }
  8636. if (o.typingPiano != self.typingPiano)
  8637. self.setTypingPiano (o.typingPiano);
  8638. if (o.scanAtStart != backgroundScanAtStart())
  8639. setBackgroundScanAtStart (o.scanAtStart);
  8640. if (o.defaultTemplate.toStdString() != defaultTemplate().toText())
  8641. setDefaultTemplate (TemplateChoice::parse (o.defaultTemplate.toStdString()));
  8642. if (o.startupProject != (int) startupProject())
  8643. setStartupProject ((StartupProject) juce::jlimit (0, 2, o.startupProject));
  8644. if (o.pluginSandbox != (int) pluginSandboxMode())
  8645. setPluginSandboxMode ((SandboxMode) juce::jlimit (0, 4, o.pluginSandbox));
  8646. if (runningAsAppImage() && o.menuEntry != appImageMenuEntryInstalled())
  8647. setAppImageMenuEntry (o.menuEntry);
  8648. editorlimit::enabled() = o.limitEditors;
  8649. setSampleAccurateAutomation (o.sampleAccurateAutomation);
  8650. if (o.pluginSubstitutes != pluginSubstitutesEnabled())
  8651. setPluginSubstitutesEnabled (o.pluginSubstitutes);
  8652. if (o.crashReports != (int) crashreporter::consent())
  8653. crashreporter::setConsent ((crashreport::Consent) juce::jlimit (0, 2, o.crashReports));
  8654. updater::setAutomatic (o.checkUpdates);
  8655. remoteui::setEnabled (o.remoteControl);
  8656. ChannelRackComponent::keepEditorsOpen = o.keepEditorsOpen;
  8657. ChannelRackComponent::selectFirstChannelWithNotes = o.selectFirstChannelWithNotes;
  8658. PianoRollComponent::monophonicPainting = o.monophonicPainting;
  8659. if (std::exchange (meterscale::alternate(), o.alternateMeterScale) != o.alternateMeterScale) // (round 190lx: the meters' scale changed)
  8660. self.repaint();
  8661. self.engine.setDetachNewPlugins (o.detachNewPlugins);
  8662. setEditorsDetached (o.detachNewPlugins); // (round 190ev)
  8663. ChannelRackComponent::autoSelectLinked = o.autoSelectLinked;
  8664. self.alternateUndo = o.alternateUndo;
  8665. EditorGlobals::get().rememberSeek = o.rememberSeek;
  8666. autoclipplace::setAtPlayback (o.autoClipsAtPlayback);
  8667. pluginkeys::newPluginsHostFirst() = o.disableTypingPriority;
  8668. self.setLayoutStyle ((layoutstyle::Style) juce::jlimit (0, layoutstyle::count - 1, o.layoutStyle));
  8669. AudioEngine::alsSessionOnPlaylist = o.alsSessionOnPlaylist;
  8670. if (o.stretchedClipsLoop != stretchedClipsLoop())
  8671. {
  8672. setStretchedClipsLoop (o.stretchedClipsLoop);
  8673. self.repaint(); // the Playlist draws what plays
  8674. }
  8675. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, o.editPatternsIn);
  8676. self.startup.splash = o.splash;
  8677. if (o.supportNote != support::noteEnabled())
  8678. support::setNoteEnabled (o.supportNote);
  8679. self.startup.sound = o.startupSound;
  8680. self.engine.setUndoLevels (o.undoLevels);
  8681. self.autosaveMinutes = prefs::clampAutosaveMinutes (o.autosaveMinutes);
  8682. self.autosaveKeep = prefs::clampAutosaveKeep (o.autosaveKeep);
  8683. self.askUnusedRecordings = o.askUnusedRecordings;
  8684. self.backupWaitsForQuiet = o.backupWaitsForQuiet;
  8685. self.backupLongestWaitMinutes = prefs::clampBackupLongestWait (o.backupLongestWaitMinutes);
  8686. if (self.hoverValues && ! o.hoverValues && self.hoverTipShown)
  8687. ui::hideValueTip();
  8688. self.hoverValues = o.hoverValues;
  8689. self.hoverTipShown = false;
  8690. newProjectDefaults().autoCrossfades = o.crossfadesInNewProjects;
  8691. newProjectDefaults().linkTracks = o.linkTracksInNewProjects;
  8692. self.autosaveTicks = 0;
  8693. self.saveUiSettings();
  8694. if (o.uiFont != theme::savedUiFont())
  8695. theme::saveUiFont (o.uiFont);
  8696. if (o.textSize != theme::savedTextSize())
  8697. theme::saveTextSize (o.textSize);
  8698. if (o.boldText != theme::savedBoldText())
  8699. theme::saveBoldText (o.boldText);
  8700. if (o.condensedLabels != theme::savedCondensedLabels())
  8701. theme::saveCondensedLabels (o.condensedLabels);
  8702. if (o.language != i18n::saved())
  8703. self.showLanguageChoice (o.language);
  8704. };
  8705. hooks.manageShortcuts = [safe] {
  8706. if (safe != nullptr)
  8707. safe->showShortcutManager();
  8708. };
  8709. hooks.managePlugins = [safe] {
  8710. if (safe != nullptr)
  8711. safe->showPluginManager();
  8712. };
  8713. hooks.runAction = [safe] (const std::string& id) { return safe != nullptr && safe->runAction (id); };
  8714. hooks.linkToggleShown = [safe] { return safe != nullptr && safe->toolbarLayout.isShown (toolbarlayout::Group::link); };
  8715. hooks.showLinkToggle = [safe] (bool on) {
  8716. if (safe != nullptr)
  8717. safe->showLinkToggle (on);
  8718. };
  8719. hooks.midiChanged = [safe] {
  8720. if (safe != nullptr)
  8721. safe->updateGamepad();
  8722. };
  8723. showSettings (engine, (SettingsPage) juce::jlimit (0, (int) SettingsPage::link, page), std::move (hooks)); // (Theme was clamped to MIDI)
  8724. }
  8725. void MainComponent::showPluginManager()
  8726. {
  8727. lynx::showPluginManager (engine, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  8728. if (safe != nullptr)
  8729. safe->openSettings ((int) SettingsPage::files);
  8730. });
  8731. }
  8732. void MainComponent::showShortcutManager()
  8733. {
  8734. lynx::showShortcutManager ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  8735. if (safe == nullptr)
  8736. return;
  8737. safe->loadKeyMap();
  8738. safe->setControlHints();
  8739. safe->menuItemsChanged();
  8740. });
  8741. }
  8742. void MainComponent::showMissingFiles (bool afterOpening)
  8743. {
  8744. if (afterOpening && platform::testMode()) // (LYNX_TEST_MODE: nothing waits for a click)
  8745. {
  8746. platform::testModeLog ("Missing files dialog after opening " + projectName);
  8747. return;
  8748. }
  8749. MissingFilesInfo info;
  8750. info.projectName = projectName;
  8751. const auto fromFlp = importedFlpFile.existsAsFile() && currentFile == juce::File();
  8752. const auto exists = [] (const std::string& path) { return juce::File::isAbsolutePath (juce::String::fromUTF8 (path.c_str())) && juce::File (juce::String::fromUTF8 (path.c_str())).existsAsFile(); };
  8753. if (fromFlp)
  8754. {
  8755. // the import dropped the samples it couldn't find: its report keeps them (minus the ones located since)
  8756. const auto& report = engine.getImportReport();
  8757. for (const auto& m : report.missingFiles)
  8758. info.files.push_back (m);
  8759. info.plugins = engine.getMissingPluginDetails();
  8760. info.autoRelocated = report.relocatedFiles;
  8761. info.searchFolders.add (importedFlpFile.getParentDirectory().getFullPathName());
  8762. }
  8763. else
  8764. {
  8765. const auto& song = engine.getSong();
  8766. info.files = findMissingSamples (song, exists);
  8767. auto& host = engine.getPluginHost();
  8768. auto addPlugin = [&info] (const PluginRef& ref, const std::string& user, const char* replacement) {
  8769. const auto name = ref.name.empty() ? ref.id : ref.name;
  8770. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  8771. if (it == info.plugins.end())
  8772. it = info.plugins.insert (info.plugins.end(), MissingPlugin { name, {}, replacement });
  8773. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  8774. it->usedBy.push_back (user);
  8775. };
  8776. for (const auto& c : song.channels)
  8777. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty() && host.find (juce::String::fromUTF8 (c.plugin.id.c_str())) == nullptr)
  8778. addPlugin (c.plugin, c.name, "Silence: the channel keeps the plugin's settings until it is installed");
  8779. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  8780. for (const auto& fx : song.mixer[t].effects)
  8781. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty() && host.find (juce::String::fromUTF8 (fx.plugin.id.c_str())) == nullptr)
  8782. addPlugin (fx.plugin, song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name,
  8783. "Bypassed: the slot keeps the plugin's settings until it is installed");
  8784. // played by a LYNX substitute until the original is installed
  8785. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  8786. for (const auto& fx : song.mixer[t].effects)
  8787. if (fx.isSubstitute())
  8788. {
  8789. const auto name = substituteOriginalName (fx);
  8790. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  8791. if (it == info.plugins.end())
  8792. it = info.plugins.insert (info.plugins.end(),
  8793. MissingPlugin { name, {}, TR_NOOP ("LYNX SHARE substitute: {0} (the original plugin is used again once it is installed). FL Studio plays a missing plugin's slot unprocessed: a substitute slot's menu › Bypass all LYNX SHARE substitutes of this project does the same"),
  8794. effectInfo (fx.kind).name });
  8795. const auto user = song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name;
  8796. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  8797. it->usedBy.push_back (user);
  8798. }
  8799. // installed, but failed to load: they play silence / are bypassed
  8800. for (const auto& line : host.getLoadFailures())
  8801. if (std::none_of (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == line.toStdString(); }))
  8802. info.plugins.push_back ({ line.toStdString(), {}, "Silence: the plugin is installed but did not load" });
  8803. if (currentFile.existsAsFile())
  8804. info.searchFolders.add (currentFile.getParentDirectory().getFullPathName());
  8805. }
  8806. if (afterOpening && info.files.empty() && info.plugins.empty())
  8807. {
  8808. if (fromFlp)
  8809. showImportReport();
  8810. return;
  8811. }
  8812. auto safe = juce::Component::SafePointer<MainComponent> (this);
  8813. const auto flp = fromFlp ? importedFlpFile : juce::File();
  8814. showMissingFilesDialog (
  8815. std::move (info),
  8816. [safe, flp] (const std::map<std::string, std::string>& relocations) {
  8817. if (safe == nullptr)
  8818. return;
  8819. if (flp != juce::File())
  8820. {
  8821. // FL import: imported again with the located samples (the channels become samplers, slices are read...)
  8822. juce::String error;
  8823. if (! safe->engine.importFlpFile (flp, error, relocations, true))
  8824. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  8825. }
  8826. else
  8827. safe->engine.editSong ([&relocations] (Song& s) { applyRelocations (s, relocations); });
  8828. safe->updateTitle();
  8829. },
  8830. [safe, afterOpening, fromFlp] {
  8831. if (safe != nullptr && afterOpening && fromFlp)
  8832. safe->showImportReport();
  8833. });
  8834. }
  8835. juce::PopupMenu MainComponent::makeSwitchAudioClipsMenu (bool selectedOnly)
  8836. {
  8837. // FL's groups where LYNX has a match (Realtime: Resample), LYNX's stretch engine, and its Ableton-style warp modes
  8838. juce::PopupMenu m;
  8839. auto item = [this, &m, selectedOnly] (const char* name, bool keepPitch, StretchMethod method) {
  8840. m.addItem (tr (name), [this, selectedOnly, keepPitch, method, name] { switchAudioClips (selectedOnly, keepPitch, method, tr (name)); });
  8841. };
  8842. m.addSectionHeader (tr ("Realtime"));
  8843. item (TR_NOOP ("Resample"), false, StretchMethod::general);
  8844. m.addSectionHeader (tr ("Stretch engine"));
  8845. item (TR_NOOP ("General"), true, StretchMethod::general);
  8846. item (TR_NOOP ("Drums / transients"), true, StretchMethod::transients);
  8847. item (TR_NOOP ("Vocal / mono"), true, StretchMethod::mono);
  8848. m.addSectionHeader (tr ("Warp (Ableton-style)"));
  8849. item (TR_NOOP ("Beats"), true, StretchMethod::beats);
  8850. item (TR_NOOP ("Tones"), true, StretchMethod::tones);
  8851. item (TR_NOOP ("Texture"), true, StretchMethod::texture);
  8852. item (TR_NOOP ("Complex"), true, StretchMethod::complex);
  8853. return m;
  8854. }
  8855. void MainComponent::switchAudioClips (bool selectedOnly, bool keepPitch, StretchMethod method, const juce::String& modeName)
  8856. {
  8857. // FL's FUN_01213a20 (REA round 181b): the error when there is none, else a question, then the change (undoable)
  8858. std::vector<int> channels;
  8859. if (selectedOnly)
  8860. channels = engine.getSelectedChannels();
  8861. else
  8862. for (int i = 0; i < (int) engine.getSong().channels.size(); ++i)
  8863. channels.push_back (i);
  8864. if (audioClipsAmong (engine.getSong(), channels) == 0)
  8865. {
  8866. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  8867. selectedOnly ? tr ("No audio clip channels were selected.") : tr ("No audio clip channels were found."));
  8868. return;
  8869. }
  8870. const auto text = selectedOnly ? tr ("Selected audio clip channels will be set to {0} mode. Some channels may need manual time adjustment.", { modeName })
  8871. : tr ("All audio clip channels will be set to {0} mode. Some channels may need manual time adjustment.", { modeName });
  8872. auto options = juce::MessageBoxOptions()
  8873. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  8874. .withTitle (tr ("Confirm"))
  8875. .withMessage (text)
  8876. .withButton (tr ("OK"))
  8877. .withButton (tr ("Cancel"));
  8878. juce::AlertWindow::showAsync (options, [this, channels, keepPitch, method] (int result) {
  8879. if (result == 1)
  8880. engine.editSong ([&channels, keepPitch, method] (Song& s) { setStretchOfAudioClips (s, channels, keepPitch, method); });
  8881. });
  8882. }
  8883. void MainComponent::saveClipboardToBrowser (bool midi)
  8884. {
  8885. // FL's FUN_0124d070 (REA round 181b): the clipboard as "Audio clipboard.wav" / "MIDI clipboard.mid" in the
  8886. // Browser's Clipboard files
  8887. juce::File file;
  8888. if (midi)
  8889. {
  8890. if (const auto smf = midiclipboard::get())
  8891. file = audioclipboard::save ("MIDI clipboard", ".mid", smf->getData(), smf->getSize());
  8892. else
  8893. return;
  8894. }
  8895. else
  8896. {
  8897. const auto data = audioclipboard::wav();
  8898. if (data.empty())
  8899. return;
  8900. file = audioclipboard::save ("Audio clipboard", ".wav", data.data(), data.size());
  8901. }
  8902. if (file == juce::File())
  8903. {
  8904. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  8905. tr ("Unable to create folder: {0}", { audioclipboard::folder().getFullPathName() }));
  8906. return;
  8907. }
  8908. browser.refreshRoots();
  8909. ui::postHint ({ tr ("Saved to Clipboard files: {0}", { file.getFileName() }), {}, false, false }, 5000);
  8910. }
  8911. void MainComponent::confirmPrepareForMidiExport()
  8912. {
  8913. // FL's text, without its "(no undo)": this edit can be undone in LYNX
  8914. auto options = juce::MessageBoxOptions()
  8915. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  8916. .withTitle (tr ("Confirm"))
  8917. .withMessage (tr ("All of the channels are about to be turned into MIDI Out channels in order to allow output to a MIDI file."))
  8918. .withButton (tr ("OK"))
  8919. .withButton (tr ("Cancel"));
  8920. juce::AlertWindow::showAsync (options, [this] (int result) {
  8921. if (result == 1)
  8922. engine.editSongStructural ([] (Song& s) { prepareForMidiExport (s); });
  8923. });
  8924. }
  8925. void MainComponent::changeDeclickOfSelectedClips (int mode)
  8926. {
  8927. const auto selected = engine.getSelectedChannels();
  8928. if (audioClipsAmong (engine.getSong(), selected) == 0)
  8929. {
  8930. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("No selection"), tr ("There are no audio clip channels selected."));
  8931. return;
  8932. }
  8933. auto options = juce::MessageBoxOptions()
  8934. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  8935. .withTitle (tr ("Change declicking mode?"))
  8936. .withMessage (tr ("Change the declicking mode of all selected audio clip channels?"))
  8937. .withButton (tr ("OK"))
  8938. .withButton (tr ("Cancel"));
  8939. juce::AlertWindow::showAsync (options, [this, selected, mode] (int result) {
  8940. if (result == 1)
  8941. engine.editSong ([&selected, mode] (Song& s) { setDeclickOfAudioClips (s, selected, mode); });
  8942. });
  8943. }
  8944. void MainComponent::switchSmartDisableForAll()
  8945. {
  8946. // FL's Tools › Macros › "Switch smart disable for all plugins" (FLEngine FUN_0124d430, REA round 139): every
  8947. // effect slot of every insert is set to smart disable
  8948. engine.editSong ([] (Song& s) {
  8949. for (auto& track : s.mixer)
  8950. for (auto& slot : track.effects)
  8951. slot.smartDisable = true;
  8952. });
  8953. }
  8954. void MainComponent::exportAudio (int format)
  8955. {
  8956. // FL's render window selects the Master in the Mixer as it opens (round 190my, live check 190my A2: "Mixer - Master",
  8957. // still after Cancel; REA FormShow FUN_00c51750 → FUN_00c4d0b0) — so the Current track renders on the Master
  8958. mixer.selectTrack (0);
  8959. showExportDialog (engine, currentFile.getParentDirectory(), projectName, format);
  8960. }
  8961. void MainComponent::exportForOtherApps()
  8962. {
  8963. engine.capturePluginStates();
  8964. showOtherAppsExportDialog (engine,
  8965. currentFile != juce::File() ? currentFile.getParentDirectory()
  8966. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  8967. projectStem (projectName));
  8968. }
  8969. void MainComponent::importMidiFile()
  8970. {
  8971. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  8972. fileChooser = lynx::ui::makeFileChooser (tr ("Import MIDI file"), folder, "*.mid;*.midi");
  8973. juce::Component::SafePointer<MainComponent> safe (this);
  8974. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe] (const juce::FileChooser& fc) {
  8975. const auto file = fc.getResult();
  8976. if (safe == nullptr || file == juce::File())
  8977. return;
  8978. juce::String error;
  8979. const auto midi = MidiFileIo::parseFile (file, error);
  8980. if (! midi)
  8981. {
  8982. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  8983. return;
  8984. }
  8985. static MidiFileIo::ImportOptions remembered; // FL keeps the window's choices
  8986. showMidiImportDialog (file.getFileName(), *midi, remembered, false, [safe, file] (const MidiFileIo::ImportOptions& o) {
  8987. remembered = o;
  8988. if (safe != nullptr)
  8989. safe->importMidiFile (file, o);
  8990. });
  8991. });
  8992. }
  8993. void MainComponent::importMidiFile (const juce::File& file, const MidiFileIo::ImportOptions& o)
  8994. {
  8995. juce::String error;
  8996. if (o.newProject)
  8997. {
  8998. confirmDiscard ([this, file, o] {
  8999. Song song;
  9000. juce::String err;
  9001. if (! MidiFileIo::importInto (song, file, o, err))
  9002. {
  9003. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), err);
  9004. return;
  9005. }
  9006. engine.stop();
  9007. engine.rewind();
  9008. engine.setSong (std::move (song));
  9009. currentFile = juce::File();
  9010. projectName = file.getFileNameWithoutExtension();
  9011. importedSuffix = " " + tr ("(imported from MIDI)");
  9012. updateTitle();
  9013. });
  9014. return;
  9015. }
  9016. auto song = engine.getSong();
  9017. if (! MidiFileIo::importInto (song, file, o, error))
  9018. {
  9019. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  9020. return;
  9021. }
  9022. engine.editSong ([&song] (Song& s) { s = std::move (song); });
  9023. showPanel (Panel::channelRack);
  9024. }
  9025. void MainComponent::exportMidiFile()
  9026. {
  9027. // FL's File › Export › "MIDI file...": the arrangement's notes (or the current pattern's) as a Standard MIDI File
  9028. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  9029. const auto name = projectName.isNotEmpty() ? projectName : juce::String ("LYNX SHARE");
  9030. fileChooser = lynx::ui::makeFileChooser (tr ("Export MIDI file"), folder.getChildFile (name + ".mid"), "*.mid");
  9031. juce::Component::SafePointer<MainComponent> safe (this);
  9032. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  9033. [safe] (const juce::FileChooser& fc) {
  9034. auto file = fc.getResult();
  9035. if (safe == nullptr || file == juce::File())
  9036. return;
  9037. if (! file.hasFileExtension (".mid;.midi"))
  9038. file = file.withFileExtension (".mid");
  9039. juce::String error;
  9040. if (! MidiFileIo::saveSong (safe->engine.getSong(), file, error))
  9041. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not export"), error);
  9042. else
  9043. file.revealToUser();
  9044. });
  9045. }
  9046. void MainComponent::save (bool askForFile, std::function<void()> afterSaved)
  9047. {
  9048. commitSongNotes(); // (round 190ch: notes still being typed are part of what is saved)
  9049. auto write = [this, afterSaved] (const juce::File& file) {
  9050. juce::String error;
  9051. engine.capturePluginStates(); // plugin state lives in the plugins; copy it before saving
  9052. keepOverwrittenCopy (file); // the version this save replaces goes to the backup folder (like FL)
  9053. if (ProjectFile::save (engine.getSong(), file, error, currentWindowLayout()))
  9054. {
  9055. engine.markSaved();
  9056. warnIfProjectTooBig (file); // round 190mr (DF-147)
  9057. rememberRecent (file);
  9058. currentFile = file;
  9059. projectName = file.getFileNameWithoutExtension();
  9060. importedSuffix = {};
  9061. updateTitle();
  9062. if (afterSaved)
  9063. afterSaved();
  9064. }
  9065. else
  9066. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  9067. };
  9068. // a project opened from the backup folder is saved somewhere else (old backups there are deleted)
  9069. if (! askForFile && currentFile != juce::File() && ! currentFile.isAChildOf (autosaveFolder()))
  9070. {
  9071. write (ProjectFile::withProjectExtension (currentFile));
  9072. return;
  9073. }
  9074. const auto startFolder = currentFile.isAChildOf (autosaveFolder()) ? juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
  9075. : currentFile.getParentDirectory();
  9076. fileChooser = lynx::ui::makeFileChooser (tr ("Save project"), startFolder, juce::String ("*") + ProjectFile::extension);
  9077. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  9078. [this, write] (const juce::FileChooser& chooser) {
  9079. const auto chosen = chooser.getResult();
  9080. if (chosen == juce::File())
  9081. return;
  9082. const auto file = ProjectFile::withProjectExtension (chosen);
  9083. // the dialog's overwrite warning was about the name typed, without the extension
  9084. if (file != chosen && file != currentFile && file.existsAsFile())
  9085. {
  9086. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  9087. tr ("{0} already exists. Choose another name or folder.", { file.getFullPathName() }));
  9088. return;
  9089. }
  9090. if (! file.isAChildOf (autosaveFolder()))
  9091. {
  9092. write (file);
  9093. return;
  9094. }
  9095. // FL warns the same way: the backup folder is cleaned up as new backups arrive
  9096. auto* w = new juce::AlertWindow (tr ("Save in the backup folder?"),
  9097. tr ("This folder keeps LYNX SHARE's automatic backups and old ones are deleted as new "
  9098. "ones arrive, so a project saved here can be lost. If you opened a backup, save it "
  9099. "somewhere else."),
  9100. juce::MessageBoxIconType::WarningIcon);
  9101. w->addButton (tr ("Save anyway"), 1);
  9102. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  9103. w->enterModalState (true, juce::ModalCallbackFunction::create ([write, file] (int r) {
  9104. if (r == 1)
  9105. write (file);
  9106. }),
  9107. true);
  9108. });
  9109. }
  9110. void MainComponent::placeHintBar (juce::Rectangle<int> row)
  9111. {
  9112. // the read-out takes the right part of the hint row once something was tweaked (2/5 of it, 170..280 px), and
  9113. // only when the hint keeps at least 220 px
  9114. const auto readoutWidth = juce::jlimit (170, 280, row.getWidth() * 2 / 5);
  9115. if (tweakReadout.hasContent() && row.getWidth() - readoutWidth - 6 >= 220)
  9116. {
  9117. tweakReadout.setBounds (row.removeFromRight (readoutWidth));
  9118. tweakReadout.setVisible (true);
  9119. row.removeFromRight (6);
  9120. }
  9121. else
  9122. {
  9123. tweakReadout.setVisible (false);
  9124. tweakReadout.setBounds ({});
  9125. }
  9126. hintBar.setVisible (true);
  9127. hintBar.setBounds (row);
  9128. }
  9129. // Settings › General › "Show a control's value next to the mouse..." (round 177d, pain point 10; off by default = FL,
  9130. // whose value shows in the hint bar only): the value the hint bar shows for the control under the mouse, in the
  9131. // drag read-out's pill just above the cursor. A drag shows its own read-out, so nothing here while one runs.
  9132. void MainComponent::updateHoverValue (juce::Component* hovered, const ui::Hint& hint, bool live)
  9133. {
  9134. if (live)
  9135. {
  9136. hoverTipShown = false; // (the drag's read-out owns the pill now)
  9137. return;
  9138. }
  9139. const auto at = juce::Desktop::getInstance().getMainMouseSource().getScreenPosition().roundToInt();
  9140. const auto show = hovered != nullptr && hint.value.isNotEmpty() && ! juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  9141. && (hovered->getTopLevelComponent() == getTopLevelComponent()
  9142. || (bool) hovered->getTopLevelComponent()->getProperties().getWithDefault ("lynxNativeChild", false));
  9143. if (! show)
  9144. {
  9145. if (hoverTipShown)
  9146. ui::hideValueTip();
  9147. hoverTipShown = false;
  9148. return;
  9149. }
  9150. if (hoverTipShown && hint.value == hoverTipText && at == hoverTipAt)
  9151. return;
  9152. hoverTipShown = true;
  9153. hoverTipText = hint.value;
  9154. hoverTipAt = at;
  9155. ui::showValueTip (*hovered, juce::Rectangle<int> (1, 18).withCentre (hovered->getLocalPoint (nullptr, at)), hint.value);
  9156. }
  9157. void MainComponent::refreshTweakReadout()
  9158. {
  9159. const auto had = tweakReadout.hasContent();
  9160. if (const auto t = engine.getLastTweaked (0))
  9161. tweakReadout.setContent (describeAutomationTarget (engine, *t), describeTargetValue (engine, *t));
  9162. else
  9163. tweakReadout.setContent ({}, {});
  9164. if (had != tweakReadout.hasContent())
  9165. resized(); // the read-out appears (or goes, with its target)
  9166. }
  9167. juce::PopupMenu MainComponent::makeLastTweakedMenu (int which)
  9168. {
  9169. juce::PopupMenu menu;
  9170. const auto target = engine.getLastTweaked (which);
  9171. if (! target)
  9172. {
  9173. menu.addItem (tr ("No parameter"), false, false, [] {});
  9174. return menu;
  9175. }
  9176. // as FL: the parameter's name, then the items of its own menu (events, automation clip, remote control, value)
  9177. const auto valueNow = describeTargetValue (engine, *target); // (round 162d: with its value, as the read-out shows it)
  9178. ui::addItemHeader (menu, tr ("Parameter"), describeAutomationTarget (engine, *target) + (valueNow.isNotEmpty() ? ": " + valueNow : juce::String()),
  9179. juce::Colours::transparentBlack);
  9180. addLastTweakedItems (menu, *target);
  9181. return menu;
  9182. }
  9183. juce::PopupMenu MainComponent::getMultilinkMenuForSnapshot()
  9184. {
  9185. // (round 190df: FL's menu, then LYNX's own items; round 190ey: with multilink off, the last tweaked control's own
  9186. // menu as FL's left column, captioned with its name)
  9187. return multilinkButtonMenu (engine, [this] (juce::PopupMenu& column) {
  9188. if (const auto target = engine.getLastTweaked (0))
  9189. {
  9190. column.addSectionHeader (describeAutomationTarget (engine, *target));
  9191. addLastTweakedItems (column, *target);
  9192. }
  9193. });
  9194. }
  9195. void MainComponent::addLastTweakedItems (juce::PopupMenu& menu, const AutomationTarget& target)
  9196. {
  9197. addAutomationItem (menu, engine, target, true);
  9198. menu.addSectionHeader (tr ("Value"));
  9199. const auto value = engine.currentTargetValue (target);
  9200. menu.addItem (tr ("Copy value"), value >= 0.0f, false, [value] { lastTweakedClipboard() = value; });
  9201. menu.addItem (tr ("Paste value"), lastTweakedClipboard() >= 0.0f, false, [this, t = target] { setTweakedValue (t, lastTweakedClipboard()); });
  9202. menu.addItem (tr ("Type in value..."), value >= 0.0f, false, [this, t = target, value] {
  9203. auto spec = ui::percentSpec (describeAutomationTarget (engine, t), value);
  9204. ui::typeValue (*this, spec, value, [this, t] (double v) { setTweakedValue (t, (float) v); });
  9205. });
  9206. }
  9207. float& MainComponent::lastTweakedClipboard()
  9208. {
  9209. static float copied = -1.0f;
  9210. return copied;
  9211. }
  9212. void MainComponent::setTweakedValue (const AutomationTarget& target, float value)
  9213. {
  9214. value = juce::jlimit (0.0f, 1.0f, value);
  9215. auto plugin = false;
  9216. engine.editSong ([&] (Song& s) {
  9217. if (target.kind == AutomationTargetKind::tempo)
  9218. clipops::followTempo (s, tempoFromValue (value)); // (issue #87: audio clips follow)
  9219. else
  9220. plugin = ! s.setTargetValue (target, value);
  9221. });
  9222. if (plugin)
  9223. {
  9224. if (target.kind == AutomationTargetKind::channelParam)
  9225. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (target.index).get()))
  9226. p->setParameterFromUi (target.param, value);
  9227. if (target.kind == AutomationTargetKind::effectParam)
  9228. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (target.index, target.slot).get()))
  9229. p->setParameterFromUi (target.param, value);
  9230. }
  9231. engine.noteTweaked (target);
  9232. }
  9233. juce::StringArray MainComponent::getMenuBarNames()
  9234. {
  9235. // FL's menu bar order (REA round 139): FILE EDIT ADD PATTERNS VIEW OPTIONS TOOLS HELP
  9236. return { tr ("File"), tr ("Edit"), tr ("Add"), tr ("Patterns"), tr ("View"), tr ("Options"), tr ("Tools"), tr ("Help") };
  9237. }
  9238. juce::PopupMenu MainComponent::getMenuForIndex (int barIndex, const juce::String&)
  9239. {
  9240. juce::PopupMenu menu;
  9241. // the bar's position → the menu built below (0 File, 1 Edit, 2 View, 3 Patterns, 4 Options, 5 Help, 10 Add, 11 Tools)
  9242. static constexpr int menus[] = { 0, 1, 10, 3, 2, 4, 11, 5 };
  9243. const auto index = juce::isPositiveAndBelow (barIndex, (int) std::size (menus)) ? menus[barIndex] : 5;
  9244. // round qafix190kq (QA-8): in the Clip-launch / Simple layouts the View menu is not split into the two columns of a
  9245. // menu taller than 70 % of the screen (JUCE fix 40, FL's split): "Layout style" landed in the first column, and its
  9246. // submenu opened beside the menu's outer edge (issue #18, core/MenuPlacement.h), beyond the second column. Live's and
  9247. // BandLab's View menus are one column; it stays one column while it fits on the screen (JUCE fix 42 reads this
  9248. // property of the menu's target: the menu bar opens the menu built here right away). The Pattern layout keeps FL's split.
  9249. menuBar.getProperties().set ("lynxOneColumnMenu", index == 2 && layoutStyle != layoutstyle::Style::pattern);
  9250. if (index == 10)
  9251. {
  9252. // FL's ADD menu: a channel (LYNX's instruments and the installed plugins), a pattern, the plugin tools
  9253. menu.addSectionHeader (tr ("Channel"));
  9254. rack.addInstrumentItems (menu, -1);
  9255. // the Channel Rack's and the mixer slots' view switch (Categories / Simple / Tree), so that the three menus are
  9256. // one (issue #104)
  9257. quickpick::addFolderViewItems (menu, engine);
  9258. menu.addSectionHeader (tr ("Other"));
  9259. // FL's "Automation for last tweaked parameter" (Add_AutoLastMenu → FUN_01231100, REA round 143)
  9260. const auto last = engine.getLastTweaked (0);
  9261. menu.addItem ((last ? tr ("Automation for last tweaked parameter ({0})", { describeAutomationTarget (engine, *last) })
  9262. : tr ("Automation for last tweaked parameter"))
  9263. + shortcutText ("automation.lastTweaked"),
  9264. last.has_value(), false, [this] { runAction ("automation.lastTweaked"); });
  9265. menu.addItem (tr ("Pattern"), [this] { newPatternButton.onClick(); });
  9266. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  9267. return menu;
  9268. }
  9269. if (index == 11)
  9270. {
  9271. // FL's TOOLS menu, with the tools LYNX has (REA round 139)
  9272. menu.addItem (tr ("Browser find") + shortcutText ("browser.search"), [this] {
  9273. showPanel (Panel::browser);
  9274. browser.focusSearch();
  9275. });
  9276. {
  9277. // FL's One-click audio recording submenu (OneClickRecMenu, round 190dx; [FORM] and live 190cq): a caption, then
  9278. // Into Edison (FL's default item) and Into playlist
  9279. juce::PopupMenu oneClick;
  9280. oneClick.addSectionHeader (tr ("I want to record audio..."));
  9281. oneClick.addItem (tr ("Into Edison audio editor/recorder"), [this] { oneClickRecord ((int) oneclick::Into::edison); });
  9282. oneClick.addItem (tr ("Into playlist as an audio clip"), [this] { oneClickRecord ((int) oneclick::Into::playlist); });
  9283. menu.addSubMenu (tr ("One-click audio recording"), oneClick);
  9284. }
  9285. // FL's Tools menu has these two here; they work on the selected channel's Piano Roll (round 181b)
  9286. menu.addItem (tr ("Riff machine..."), [this] {
  9287. openPianoRoll();
  9288. pianoRoll.runAction ("pianoRoll.riffMachine");
  9289. });
  9290. menu.addItem (tr ("Chord progression tool..."), [this] {
  9291. openPianoRoll();
  9292. pianoRoll.runAction ("pianoRoll.chordProgression");
  9293. });
  9294. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  9295. menu.addItem (tr ("Modulators..."), [this] { openModulators (engine); }); // round 177b: LYNX's own (FL has none)
  9296. // FL's Clipboard and Score logger sections, in FL's place (round 181b)
  9297. menu.addSectionHeader (tr ("Clipboard"));
  9298. menu.addItem (tr ("Save audio clipboard to browser"), audioclipboard::hasAudio(), false, [this] { saveClipboardToBrowser (false); });
  9299. menu.addItem (tr ("Save MIDI clipboard to browser"), midiclipboard::hasMidi(), false, [this] { saveClipboardToBrowser (true); });
  9300. {
  9301. // FL's score logger (REA round 165f): the notes played lately, recording or not, into the current pattern
  9302. menu.addSectionHeader (tr ("Score logger"));
  9303. juce::PopupMenu dumpMenu;
  9304. for (const auto minutes : { 2, 5, 10, 20, 30 })
  9305. dumpMenu.addItem (tr ("Last {0} minutes", { juce::String (minutes) }), [this, minutes] { dumpScoreLog (minutes); });
  9306. menu.addSubMenu (tr ("Dump score log to selected pattern"), dumpMenu);
  9307. menu.addItem (tr ("Clear log"), ! engine.scoreLogEmpty(), false, [this] {
  9308. auto options = juce::MessageBoxOptions()
  9309. .withIconType (juce::MessageBoxIconType::WarningIcon)
  9310. .withTitle (tr ("Score logger"))
  9311. .withMessage (tr ("This will clear all logged notes!"))
  9312. .withButton (tr ("Clear log"))
  9313. .withButton (tr ("Cancel"));
  9314. juce::AlertWindow::showAsync (options, [this] (int result) {
  9315. if (result == 1)
  9316. engine.clearScoreLog();
  9317. });
  9318. });
  9319. }
  9320. addAudioLoggerMenu (menu); // FL's Tools menu has it just above "Last tweaked parameters"
  9321. // FL's "Last tweaked parameters" section (LastTweaked1Menu / LastTweaked2Menu → FUN_0123d1d0, REA round 143):
  9322. // the parameter's own menu for the last two moved controls
  9323. menu.addSectionHeader (tr ("Last tweaked parameters"));
  9324. menu.addSubMenu (tr ("Last tweaked"), makeLastTweakedMenu (0), engine.getLastTweaked (0).has_value());
  9325. menu.addSubMenu (tr ("Next to last tweaked"), makeLastTweakedMenu (1), engine.getLastTweaked (1).has_value());
  9326. menu.addSectionHeader (tr ("Macros"));
  9327. menu.addItem (tr ("Stop sound") + shortcutText ("tools.stopSound"), [this] { engine.stopSound(); });
  9328. // FL's next item, MacroCancelRecordingAction (round 187a; REA 169k §2.3): greyed while not recording
  9329. menu.addItem (tr ("Cancel recording"), engine.isRecording(), false, [this] { engine.cancelRecording(); });
  9330. menu.addSeparator();
  9331. // FL's Macros order (round 181b; [DFM] mainmenu, round 168f)
  9332. menu.addItem (tr ("Prepare for performance mode..."), [this] { prepareForPerformance(); });
  9333. menu.addItem (tr ("Prepare for MIDI export"), [this] { confirmPrepareForMidiExport(); });
  9334. menu.addItem (tr ("Select unused channels"), [this] {
  9335. showPanel (Panel::channelRack);
  9336. rack.selectUnused();
  9337. });
  9338. menu.addItem (tr ("Purge unused audio clips"), [this] { playlist.runAction ("playlist.purgeUnusedAudio"); });
  9339. menu.addItem (tr ("Switch smart disable for all plugins"), [this] { switchSmartDisableForAll(); });
  9340. // FL's two Switch items, with LYNX's own modes inside (user's decision, round 181b)
  9341. menu.addSubMenu (tr ("Switch all audio clip channels to"), makeSwitchAudioClipsMenu (false));
  9342. menu.addSubMenu (tr ("Switch selected audio clip channels to"), makeSwitchAudioClipsMenu (true));
  9343. menu.addItem (tr ("Lock all playlist tracks to content"), [this] { playlist.runAction ("playlist.lockAllToContent"); });
  9344. menu.addItem (tr ("Unlock all playlist tracks from content"), [this] { playlist.runAction ("playlist.unlockAllFromContent"); });
  9345. menu.addItem (tr ("Reset empty playlist tracks"), [this] { playlist.runAction ("playlist.resetEmptyTracks"); });
  9346. // FL's next item (round 190cd; FL's main menu, rea190bc mainmenu_toolbar-0262): every audio editor loaded in a
  9347. // mixer slot is taken out, its slot left empty. FL asks first and keeps the item enabled with no instance (live
  9348. // check 190cq, shots edison190cd-07a / 07b); LYNX keeps it one undo step.
  9349. menu.addItem (tr ("Remove all Edison instances"), [this] { askRemoveAllEdisonInstances (engine); });
  9350. // greyed until the project has a file, as in FL 2026 (seen in an unsaved project, round 181b)
  9351. menu.addItem (tr ("Delete unused files and save project"), currentFile != juce::File(), false, [this] { deleteUnusedRecordingsAndSave(); });
  9352. // FL's next item (round 190i, issue #116; FL 2026's Tools menu, shots fl2-01 / fl2-02): every plugin editor
  9353. // docked in the desktop (FL's word: Attached) or in a window of its own
  9354. if (nativechild::dockingEnabled())
  9355. {
  9356. juce::PopupMenu editors;
  9357. editors.addItem (tr ("Attached"), [this] { PluginWindows::setAllDetached (engine, false); });
  9358. editors.addItem (tr ("Detached"), [this] { PluginWindows::setAllDetached (engine, true); });
  9359. menu.addSubMenu (tr ("Switch all plugin editors to"), editors);
  9360. }
  9361. {
  9362. juce::PopupMenu declick;
  9363. int mode = 0;
  9364. for (const auto* name : { TR_NOOP ("Out only (no bleeding)"), TR_NOOP ("Transient (no bleeding)"), TR_NOOP ("Transient (bleeding)"),
  9365. TR_NOOP ("Generic (bleeding)"), TR_NOOP ("Smooth (bleeding)"), TR_NOOP ("Crossfade (bleeding)") })
  9366. {
  9367. declick.addItem (tr (name), [this, mode] { changeDeclickOfSelectedClips (mode); });
  9368. ++mode;
  9369. }
  9370. menu.addSubMenu (tr ("Change declicking for selected channels to"), declick);
  9371. }
  9372. menu.addItem (tr ("Collect project samples into a folder..."), [this] { collectSamples(); });
  9373. return menu;
  9374. }
  9375. if (index == 0)
  9376. {
  9377. // FL names the default template in the item ("New (Basic with limiter)", REA_rodada186a); LYNX's own default: "New"
  9378. const auto startTemplate = defaultTemplate();
  9379. menu.addItem ((startTemplate.isLynxDefault() ? tr ("New") : tr ("New") + " (" + templateChoiceName (startTemplate) + ")") + shortcutText ("file.new"),
  9380. [this] { newProject(); });
  9381. menu.addItem (tr ("New project..."), [this] { newProject (true); });
  9382. // FL's File › New from template (REA_rodada186a): the templates, the user's after LYNX's own, then "Change default
  9383. // template..." (FL's last item; it opens Settings › General where the default is chosen)
  9384. juce::PopupMenu templates;
  9385. bool userSection = false;
  9386. for (const auto& choice : availableTemplates())
  9387. {
  9388. if (choice.isLynxDefault())
  9389. continue;
  9390. if (choice.kind == TemplateChoice::Kind::user && ! userSection)
  9391. {
  9392. templates.addSeparator();
  9393. userSection = true;
  9394. }
  9395. templates.addItem (templateChoiceName (choice), [this, choice] {
  9396. confirmDiscard ([this, choice] {
  9397. auto song = makeFromTemplate (choice);
  9398. if (! song)
  9399. {
  9400. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("New from template"),
  9401. tr ("{0} could not be opened.", { templateChoiceName (choice) }));
  9402. return;
  9403. }
  9404. startNewProject (std::move (*song), {});
  9405. });
  9406. });
  9407. }
  9408. templates.addSeparator();
  9409. templates.addItem (tr ("Change default template..."), [this] { openSettings (3); });
  9410. menu.addSubMenu (tr ("New from template"), templates);
  9411. menu.addItem (tr ("Open...") + shortcutText ("file.open"), [this] { chooseFileToOpen(); });
  9412. // round 190ap: a project that will not open, or crashes while it loads: its plugins stay off until switched on
  9413. menu.addItem (tr ("Open without third-party plugins..."), [this] { chooseFileToOpenWithoutPlugins(); });
  9414. if (engine.pluginsOff())
  9415. menu.addItem (tr ("Switch plugins back on..."), [this] { showPluginsOff(); });
  9416. menu.addSeparator();
  9417. // FL's order (REA round 139): saving, then Export, then the recent projects listed in the menu itself
  9418. menu.addItem (tr ("Save") + shortcutText ("file.save"), [this] { save (false); });
  9419. menu.addItem (tr ("Save as...") + shortcutText ("file.saveAs"), [this] { save (true); });
  9420. menu.addItem (tr ("Save new version") + shortcutText ("file.saveNewVersion"), [this] { saveNewVersion(); });
  9421. menu.addItem (tr ("Save to new project folder..."), [this] { saveToNewProjectFolder(); });
  9422. menu.addItem (tr ("Save as template..."), [this] { saveAsTemplate(); });
  9423. menu.addItem (tr ("Save a copy for an older LYNX..."), [this] { saveCopyForOlder(); }); // (round 190hq, LYNX extra)
  9424. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  9425. menu.addSeparator();
  9426. {
  9427. // FL's File › Import (ImportMenu › ImportMIDIMenu → FileImportMIDIFileAction, REA round 143)
  9428. juce::PopupMenu imports;
  9429. imports.addItem (tr ("MIDI file..."), [this] { importMidiFile(); });
  9430. imports.addItem (tr ("Video file..."), [this] { videotracks::chooseAndImport (engine, this); }); // round 174d
  9431. menu.addSubMenu (tr ("Import"), imports);
  9432. }
  9433. {
  9434. // FL's File › Export (REA round 139): one entry per format, then the formats of the last export
  9435. juce::PopupMenu exports;
  9436. exports.addItem (tr ("Wave file..."), [this] { exportAudio (0); });
  9437. exports.addItem (tr ("MP3 file...") + shortcutText ("file.exportMp3"), [this] { exportAudio (1); });
  9438. exports.addItem (tr ("OGG file..."), [this] { exportAudio (2); });
  9439. exports.addItem (tr ("FLAC file..."), [this] { exportAudio (3); });
  9440. exports.addItem (tr ("AIFF file..."), [this] { exportAudio (4); }); // (LYNX's own; owner decision D5)
  9441. exports.addItem (tr ("MIDI file...") + shortcutText ("file.exportMidi"), [this] { exportMidiFile(); });
  9442. // FL's "M4A file..." (after MIDI, as FL lists it): only where the system has an AAC encoder (engine/AacEncoder.h)
  9443. if (aac::available())
  9444. exports.addItem (tr ("M4A file..."), [this] { exportAudio (5); });
  9445. exports.addItem (tr ("Last exported format(s)...") + shortcutText ("file.export"), [this] { exportAudio(); });
  9446. exports.addSeparator();
  9447. // FL's FileExportMasterAction ("Render the project to a file and master it"; FL Cloud there, on the computer here)
  9448. exports.addItem (tr ("Master...") + shortcutText ("file.exportMaster"), [this] { showMasterDialog (engine, currentFile.getParentDirectory(), projectName); });
  9449. exports.addSeparator();
  9450. // FL's ExportAllPLTracksMenu / ExportAllPLTrackGroupsMenu (FileExportPLTracks… / FileExportPLGroups…, REA round 168e)
  9451. exports.addSubMenu (tr ("All playlist tracks"), playlistTrackExportMenu (false));
  9452. exports.addSubMenu (tr ("All playlist track groups"), playlistTrackExportMenu (true));
  9453. exports.addSeparator();
  9454. exports.addItem (tr ("Project with samples (.zip)..."), [this] { exportPackage(); });
  9455. // Export to FL Studio (round 171e, idea by Tookolld): a .flp or FL's zipped loop package
  9456. exports.addItem (tr ("FL Studio project..."), [this] {
  9457. engine.capturePluginStates();
  9458. showFlStudioExportDialog (engine,
  9459. currentFile != juce::File() ? currentFile.getParentDirectory()
  9460. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  9461. projectStem (projectName));
  9462. });
  9463. // Export to Live 12 / Live 11 (round 175a, N2): "<name> Project/<name>.als" with the samples alongside
  9464. exports.addItem (tr ("Ableton Live set (.als)..."), [this] {
  9465. showAlsExportDialog (engine,
  9466. currentFile != juce::File() ? currentFile.getParentDirectory()
  9467. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  9468. projectStem (projectName));
  9469. });
  9470. // DAWproject (round 190jf, B22): the open format of Bitwig Studio, Studio One, Cubase...
  9471. exports.addItem (tr ("DAWproject (.dawproject)..."), [this] {
  9472. showDawProjectExport (engine, this,
  9473. currentFile != juce::File() ? currentFile.getParentDirectory()
  9474. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  9475. projectStem (projectName));
  9476. });
  9477. // Export for other apps (round 184a, S9): stems, MIDI, a Live set, an FL Studio project, the mixdown and a README
  9478. exports.addItem (tr ("For other apps..."), [this] { exportForOtherApps(); });
  9479. // FL's "Project bones..." (FileExportProjectBonesAction; REA round 168e)
  9480. exports.addItem (tr ("Project bones..."), [this] { exportProjectBones (engine, currentFile.getParentDirectory(), projectName); });
  9481. exports.addItem (tr ("Project data files (collect the samples into a folder)..."), [this] { collectSamples(); });
  9482. menu.addSubMenu (tr ("Export"), exports);
  9483. }
  9484. {
  9485. // Online Sessions, phase 1 (docs/design/ONLINE_SESSIONS.md, round 168a): a project goes to a friend as a
  9486. // .lynxpack, his part comes back the same way
  9487. const auto guestCopy = engine.getSong().session.isGuestCopy();
  9488. juce::PopupMenu online;
  9489. online.addItem (tr ("Send project..."), ! guestCopy, false, [this] { sessionui::sendProject (sessionContext()); });
  9490. online.addItem (tr ("Send my part back..."), guestCopy, false, [this] { sessionui::sendPartBack (sessionContext()); });
  9491. online.addItem (tr ("Merge a part..."), ! guestCopy, false, [this] { sessionui::mergePart (sessionContext()); });
  9492. online.addSeparator();
  9493. liveui::addMenuItems (online, liveContext());
  9494. menu.addSubMenu (tr ("Online session"), online);
  9495. }
  9496. menu.addSectionHeader (tr ("Recent projects"));
  9497. const auto shown = juce::jmin (recent.getNumFiles(), 10);
  9498. for (int i = 0; i < shown; ++i)
  9499. {
  9500. const auto file = recent.getFile (i);
  9501. // FL: the row's Alt+1 … Alt+0 on the right (round 190ld, DF-137); the folder stays beside the name
  9502. const auto id = "file.recent" + std::to_string (i + 1);
  9503. const auto keyText = shortcutText (id.c_str()).trimCharactersAtStart ("\t");
  9504. juce::PopupMenu::Item item (keyText.isEmpty() ? file.getFileName() : file.getFileName() + " (" + file.getParentDirectory().getFileName() + ")");
  9505. item.shortcutKeyDescription = keyText.isNotEmpty() ? keyText : file.getParentDirectory().getFileName(); // (else its folder on the right)
  9506. item.setEnabled (file.existsAsFile()).setAction ([this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  9507. menu.addItem (std::move (item));
  9508. }
  9509. if (recent.getNumFiles() > shown)
  9510. {
  9511. juce::PopupMenu more;
  9512. for (int i = shown; i < recent.getNumFiles(); ++i)
  9513. {
  9514. const auto file = recent.getFile (i);
  9515. more.addItem (file.getFileName() + " (" + file.getParentDirectory().getFullPathName() + ")", file.existsAsFile(),
  9516. false, [this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  9517. }
  9518. menu.addSubMenu (tr ("More recent projects"), more);
  9519. }
  9520. if (recent.getNumFiles() == 0)
  9521. menu.addItem (tr ("(none)"), false, false, [] {});
  9522. menu.addSeparator();
  9523. menu.addItem (tr ("Versions..."), [this] { showVersions(); }); // round 190ap: the saved versions and the backups in one list
  9524. menu.addItem (tr ("Revert to last backup..."), [this] { revertToLastBackup(); });
  9525. menu.addItem (tr ("Open autosave folder"), [] {
  9526. autosaveFolder().createDirectory();
  9527. autosaveFolder().startAsProcess();
  9528. });
  9529. menu.addSeparator();
  9530. menu.addItem (tr ("Exit"), [] { juce::JUCEApplication::getInstance()->systemRequestedQuit(); });
  9531. }
  9532. else if (index == 1)
  9533. {
  9534. // FL 2026's Edit menu (round 190mz, issue #214): "Undo <step>", and "Redo <step>" while something is undone, each
  9535. // with the key that does it now (core/UndoKeys.h); the Clip-launch and Simple layouts show Live's form
  9536. {
  9537. const auto liveStyle = layoutStyle != layoutstyle::Style::pattern;
  9538. const auto position = engine.getHistoryPosition();
  9539. const auto stepName = [this] (int step) {
  9540. const auto label = engine.getHistoryLabel (step);
  9541. auto name = tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) });
  9542. return name.length() > 48 ? name.substring (0, 47).trimEnd() + "..." : name;
  9543. };
  9544. const auto undoItem = undokeys::undoMenuItem (alternateUndo, position, engine.canUndo(), engine.canRedo());
  9545. const auto redoItem = undokeys::redoMenuItem (alternateUndo, liveStyle, position, engine.canRedo());
  9546. menu.addItem ((undoItem.step >= 0 ? tr ("Undo {0}", { stepName (undoItem.step) }) : liveStyle ? tr ("Nothing to undo") : tr ("Undo"))
  9547. + shortcutText (undoItem.action),
  9548. undoItem.enabled, false, [this] { undoRedo (false); });
  9549. if (redoItem.shown)
  9550. menu.addItem ((redoItem.step >= 0 ? tr ("Redo {0}", { stepName (redoItem.step) }) : tr ("Nothing to redo")) + shortcutText (redoItem.action),
  9551. redoItem.enabled, false, [this] { undoRedo (true); });
  9552. }
  9553. menu.addItem (tr ("Undo history...") + shortcutText ("edit.history"), [this] { showHistory(); });
  9554. menu.addItem (tr ("Audio editor..."), [this] { openAudioEditor (engine); });
  9555. menu.addSeparator();
  9556. menu.addItem (tr ("Plugin picker") + shortcutText ("view.pluginPicker"), [this] { togglePluginPicker(); });
  9557. menu.addItem (tr ("Quick-add palette...") + shortcutText ("panel.quickAdd"), [this] { showQuickAdd(); });
  9558. menu.addItem (tr ("Search the Browser") + shortcutText ("browser.search"), [this] {
  9559. showPanel (Panel::browser);
  9560. browser.focusSearch();
  9561. });
  9562. }
  9563. else if (index == 2)
  9564. {
  9565. // rollup 0.1.30 step 7 (owner, QA-8): in the Clip-launch and Simple layouts the View menu keeps the views and the
  9566. // switches people use often, and the rarely used window and tool items go to one "Windows and tools" submenu, so
  9567. // that the menu fits a 1080p screen at 150 % (it had 41 rows: taller than the screen, JUCE split it). The Pattern
  9568. // layout keeps FL's full menu, in FL's order (`rare` is the menu itself there).
  9569. const auto compact = layoutStyle != layoutstyle::Style::pattern;
  9570. juce::PopupMenu windowsAndTools;
  9571. auto& rare = compact ? windowsAndTools : menu;
  9572. for (auto panel : panelOrder)
  9573. menu.addItem (panelName (panel) + shortcutText (panelAction (panel)), true, workspace.isPanelVisible (panel), [this, panel] { togglePanel (panel); });
  9574. menu.addSeparator();
  9575. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  9576. workspace.toggleMaximised (Panel::playlist);
  9577. refreshPanelButtons();
  9578. });
  9579. {
  9580. juce::PopupMenu detach;
  9581. for (auto panel : panelOrder)
  9582. detach.addItem (panelName (panel), true, workspace.isDetached (panel), [this, panel] {
  9583. workspace.setDetached (panel, ! workspace.isDetached (panel));
  9584. refreshPanelButtons();
  9585. });
  9586. rare.addSubMenu (tr ("Detached panels (own window)"), detach);
  9587. }
  9588. menu.addSeparator();
  9589. menu.addItem (tr ("Reset layout"), [this] {
  9590. workspace.resetLayout();
  9591. refreshPanelButtons();
  9592. });
  9593. rare.addItem (tr ("Save layout as..."), [this] { saveLayoutAs(); });
  9594. rare.addSubMenu (tr ("Load layout"), layoutsMenu());
  9595. addLayoutStyleItems (menu);
  9596. if (compact)
  9597. rare.addSeparator();
  9598. rare.addItem (tr ("Bring back off-screen panels"), [this] { workspace.bringBackOffscreen(); });
  9599. rare.addItem (tr ("Close all windows (plugins, channel settings, tools)") + shortcutText ("view.closeWindows"), [this] { runAction ("view.closeWindows"); });
  9600. rare.addItem (tr ("Close all plugin windows") + shortcutText ("view.closePluginWindows"), [this] { runAction ("view.closePluginWindows"); });
  9601. rare.addItem (tr ("Close all windows except the focused one") + shortcutText ("view.closeUnfocusedWindows"), [this] { runAction ("view.closeUnfocusedWindows"); });
  9602. rare.addItem (tr ("Align all channel editors") + shortcutText ("view.alignChannelEditors"), [this] { runAction ("view.alignChannelEditors"); });
  9603. menu.addSeparator();
  9604. if (compact)
  9605. rare.addSeparator();
  9606. rare.addItem (tr ("Plugin database (in the Browser)") + shortcutText ("view.pluginDatabase"), [this] { runAction ("view.pluginDatabase"); });
  9607. rare.addItem (tr ("Project picker") + shortcutText ("view.projectPicker"), [this] { toggleProjectPicker(); }); // (round 190my, FL's View menu; Windows and tools in Clip-launch / Simple)
  9608. menu.addItem (tr ("Audio editor") + shortcutText ("view.audioEditor"), [this] { openAudioEditorForSelection(); });
  9609. rare.addItem (tr ("Tempo tapper") + shortcutText ("view.tempoTapper"), [this] { openTempoTapper (engine); });
  9610. rare.addItem (tr ("Sample browser (separate window)") + shortcutText ("view.sampleBrowser"), true, findToolWindow ("sampleBrowser") != nullptr,
  9611. [this] { toggleSampleBrowser(); });
  9612. // round 190ch (LYNX's own): the project's lyrics / notes beside the Playlist, and matching a reference track
  9613. menu.addItem (tr ("Lyrics and notes"), true, isLyricsShowing(), [this] { toggleLyrics(); });
  9614. rare.addItem (tr ("Reference match..."), [this] { showReferenceMatch(); });
  9615. menu.addSeparator();
  9616. if (compact)
  9617. rare.addSeparator();
  9618. rare.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  9619. menu.addItem (tr ("Touch keyboard") + shortcutText ("view.touchKeyboard"), true, isTouchKeyboardOpen(), [this] { toggleTouchKeyboard (engine); });
  9620. if (layoutStyle == layoutstyle::Style::simple) // round 190jc (owner decision 9): touch-size controls, Simple only
  9621. menu.addItem (tr ("Large controls (touch size)"), true, ui::simplelook::largeControls(),
  9622. [this] { setSimpleLargeControls (! ui::simplelook::largeControls()); });
  9623. {
  9624. // FL's View › Background (audit round 165z-a): the workspace image and colour of Options › Theme
  9625. juce::PopupMenu background;
  9626. background.addItem (tr ("Set image wallpaper..."), [] { themeui::setImageWallpaper(); });
  9627. background.addItem (tr ("Remove image wallpaper"), ! themeui::current().image.empty(), false, [] { themeui::removeImageWallpaper(); });
  9628. background.addItem (tr ("Set background color..."), [this] { openSettings ((int) SettingsPage::theme); });
  9629. rare.addSubMenu (tr ("Background"), background);
  9630. }
  9631. if (compact)
  9632. menu.addSubMenu (tr ("Windows and tools"), windowsAndTools);
  9633. menu.addSeparator();
  9634. // FL's "Auto scrolling" (round 162, issue #9)
  9635. menu.addItem (tr ("Playlist follows the playhead (auto scrolling)") + shortcutText ("playlist.follow"), true,
  9636. EditorGlobals::get().isFollowing (false), [this] { runAction ("playlist.follow"); });
  9637. menu.addItem (tr ("Piano Roll follows the playhead (auto scrolling)") + shortcutText ("pianoRoll.follow"), true,
  9638. EditorGlobals::get().isFollowing (true), [this] { runAction ("pianoRoll.follow"); });
  9639. }
  9640. else if (index == 3)
  9641. {
  9642. menu = makePatternMenu();
  9643. }
  9644. else if (index == 4)
  9645. {
  9646. // the Settings window's pages (Settings › General gathers the app options that were menu items here)
  9647. menu.addItem (tr ("Audio settings..."), [this] { openSettings ((int) SettingsPage::audio); });
  9648. menu.addItem (tr ("MIDI settings...") + shortcutText ("view.midiSettings"), [this] { openSettings ((int) SettingsPage::midi); });
  9649. // round 190gl: Ableton Link (LYNX's own in FL's menu: FL has no Link), the switch and its settings page
  9650. menu.addItem (tr ("Ableton Link"), true, engine.getLink().isEnabled(), [this] { engine.setLinkEnabled (! engine.getLink().isEnabled()); });
  9651. menu.addItem (tr ("Ableton Link settings..."), [this] { openSettings ((int) SettingsPage::link); });
  9652. menu.addItem (tr ("General settings...") + shortcutText ("view.settings"), [this] { openSettings ((int) SettingsPage::general); });
  9653. menu.addItem (tr ("Theme (colors, background)..."), [this] { openSettings ((int) SettingsPage::theme); });
  9654. menu.addItem (tr ("File settings (search folders)..."), [this] { openSettings ((int) SettingsPage::files); });
  9655. menu.addItem (tr ("LYNX extras..."), [this] { openSettings ((int) SettingsPage::extras); }); // round 190am
  9656. menu.addItem (tr ("Project settings (tempo, time signature)..."), [this] { openSettings ((int) SettingsPage::project); });
  9657. menu.addItem (tr ("Project info...") + shortcutText ("view.projectInfo"), [this] { openSettings ((int) SettingsPage::info); });
  9658. {
  9659. juce::PopupMenu mixerMenu; // round 163: clean mixer, inserts and Master chain of new projects
  9660. mixeroptions::addItems (mixerMenu, engine, true);
  9661. menu.addSubMenu (tr ("Mixer"), mixerMenu);
  9662. }
  9663. menu.addSeparator();
  9664. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  9665. const auto scanning = engine.getPluginHost().backgroundScan().running;
  9666. menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins ({0})", { platform::pluginFormatNames() }), [this, scanning] {
  9667. if (scanning)
  9668. engine.getPluginHost().cancelBackgroundScan();
  9669. else
  9670. engine.getPluginHost().startBackgroundScan(); // progress in the hint bar; LYNX stays usable
  9671. });
  9672. menu.addItem (tr ("Manage shortcuts..."), [this] { showShortcutManager(); });
  9673. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  9674. menu.addSeparator();
  9675. menu.addItem (tr ("Record input audio"), true, engine.isAudioRecordingArmed(), [this] {
  9676. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  9677. });
  9678. // FL's Options menu, "Switches" section (TFruityLoopsMainForm DFM: KBToMIDIMenu = OptionsTypingKbToPianoAction,
  9679. // "Typing keyboard to piano", Ctrl+T, checkable, right before Metronome; round 168t, issue #34)
  9680. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  9681. menu.addItem (tr ("Metronome") + shortcutText ("transport.metronome"), true, engine.getTransport().metronome.load(), [this] {
  9682. metronomeButton.setToggleState (! metronomeButton.getToggleState(), juce::sendNotification);
  9683. });
  9684. menu.addItem (tr ("Metronome volume ({0})...", { ui::utilityVolumeText (engine.getTransport().metronomeVolume.load()) }),
  9685. [this] { showMetronomeVolume(); });
  9686. {
  9687. // FL's Options › "Auto scrolling" (audit round 165z-a): one switch for every editor's Follow (Playlist,
  9688. // Piano roll, Channel rack, Audio editor); each window's own Follow button still sets just that window
  9689. auto& globals = EditorGlobals::get();
  9690. const auto on = globals.isFollowing (false) && globals.isFollowing (true);
  9691. menu.addItem (tr ("Auto scrolling"), true, on, [on] {
  9692. auto& g = EditorGlobals::get();
  9693. for (auto v : { EditorGlobals::FollowView::playlist, EditorGlobals::FollowView::pianoRoll,
  9694. EditorGlobals::FollowView::channelRack, EditorGlobals::FollowView::audioEditor })
  9695. g.setFollowingView (v, ! on);
  9696. });
  9697. // round 190im (R15, owner decision L3): Live's Follow pause after a scroll or an edit by hand; on by default
  9698. // in the Clip-launch layout, off in the others until FL's behaviour is captured
  9699. const auto pausing = globals.followPausing();
  9700. menu.addItem (tr ("Auto scrolling pauses on a scroll or an edit"), true, pausing, [this, pausing] {
  9701. EditorGlobals::get().followPausesOnEdit = pausing ? 0 : 1;
  9702. saveUiSettings();
  9703. });
  9704. }
  9705. // FL's "Multilink to controllers" (Ctrl+J), the last of FL's Switches (after Auto scrolling and Enable groups;
  9706. // round 177b-4): the controls moved while it is on link, in that order, to the controllers moved next
  9707. menu.addItem (tr ("Multilink to controllers") + shortcutText ("options.multilink"), true, engine.isMultilinkOn(),
  9708. [this] { runAction ("options.multilink"); });
  9709. // round 190ef: the reference's Options › Draw Mode (B), in the Clip-launch layout: a drag in an automation lane
  9710. // draws steps at the grid width, or freehand without a grid (core/DrawMode.h)
  9711. if (layoutStyle == layoutstyle::Style::clipLaunch)
  9712. menu.addItem (tr ("Draw Mode") + sessionkeys::menuKey (sessionkeys::Command::drawMode), true, drawmode::isOn(), [] { drawmode::toggle(); });
  9713. {
  9714. juce::PopupMenu recording;
  9715. addRecordOptions (recording);
  9716. menu.addSubMenu (tr ("Recording"), recording);
  9717. }
  9718. // LYNX's own ADR (round 174d, issue #83): cues, the record cycle with streamers and beeps, takes, comp, Align
  9719. menu.addItem (tr ("ADR (dialogue replacement)..."), [this] { adrwindow::show (engine); });
  9720. {
  9721. // LYNX's own (REA round 153): everything the Master plays, after the fader, goes to a WAV in the background
  9722. auto& logger = engine.getAudioLogger();
  9723. menu.addItem (tr ("Record the Master to a file"), true, logger.isLogging(), [this] {
  9724. auto& log = engine.getAudioLogger();
  9725. if (log.isLogging())
  9726. {
  9727. const auto file = log.currentFile();
  9728. const auto seconds = log.secondsWritten();
  9729. log.stop();
  9730. ui::postHint ({ tr ("Recording of the Master saved: {0} ({1} s)", { file.getFileName(), juce::String (seconds, 1) }), {}, false, false }, 5000);
  9731. }
  9732. else if (! log.start (AudioLogger::defaultFolder(), engine.getTransport().sampleRate.load()))
  9733. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Record the Master to a file"),
  9734. tr ("Could not create a file in {0}", { AudioLogger::defaultFolder().getFullPathName() }));
  9735. else
  9736. ui::postHint ({ tr ("Recording the Master to {0}", { log.currentFile().getFileName() }), {}, false, false }, 5000);
  9737. });
  9738. menu.addItem (tr ("Show the recordings of the Master"), [] {
  9739. const auto folder = AudioLogger::defaultFolder();
  9740. folder.createDirectory();
  9741. folder.startAsProcess();
  9742. });
  9743. }
  9744. menu.addSubMenu (tr ("Toolbar"), makeToolbarMenu());
  9745. menu.addSeparator();
  9746. menu.addItem (tr ("Setup wizard (language, audio, plugin folders)..."), [this] { showSetupWizard(); });
  9747. }
  9748. else
  9749. {
  9750. // round 190np: the welcome card, the first-song tour and Getting started in every layout (round 190dv had the tour
  9751. // and the Simple Welcome screen in the Simple layout only)
  9752. menu.addItem (tr ("Welcome..."), [this] { showWelcomeCard (false); });
  9753. menu.addItem (simpleWorkflow != nullptr && simpleWorkflow->tourCanContinue()
  9754. ? tr ("Continue the first-song tour (step {0} of {1})", { juce::String (simpleWorkflow->tourStep() + 1), juce::String (tour::stepCount) })
  9755. : tr ("First-song tour"),
  9756. [this] { startFirstSongTourAnywhere(); });
  9757. menu.addItem (tr ("Getting started"), [this] { showGettingStarted(); });
  9758. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr)
  9759. menu.addItem (tr ("Welcome screen..."), [this] {
  9760. if (simpleWorkflow != nullptr)
  9761. simpleWorkflow->showWelcome();
  9762. });
  9763. menu.addItem (tr ("Show tips and hints"), true, ! onboard.hintsOff, [this] {
  9764. onboard.hintsOff = ! onboard.hintsOff;
  9765. saveOnboarding();
  9766. if (onboard.hintsOff)
  9767. closeTip();
  9768. updateEmptyHint();
  9769. });
  9770. menu.addSeparator();
  9771. menu.addItem (tr ("Shortcuts") + shortcutText ("help.shortcuts"), [this] { showHelp(); });
  9772. menu.addItem (tr ("Missing files..."), [this] { showMissingFiles (false); });
  9773. menu.addItem (tr ("Last project import report"), [this] {
  9774. const auto& r = engine.getImportReport();
  9775. if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.notReproduced.empty() && r.droppedEffects.empty() && r.partialEffects.empty() && r.missingSamples == 0
  9776. && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty() && engine.getPluginsWithoutState().isEmpty()
  9777. && engine.getPluginHost().getLoadFailures().isEmpty())
  9778. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Project import"),
  9779. tr ("Nothing to report (no project from another app imported in this session, or everything was converted)."));
  9780. else
  9781. showImportReport();
  9782. });
  9783. menu.addItem (tr ("Built-in plugins (online list)..."), [] {
  9784. juce::URL ("https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/PLUGINS.md").launchInDefaultBrowser();
  9785. });
  9786. menu.addItem (tr ("Test audio output..."), [this] { showAudioCheck (engine); }); // (round 190gh, B23)
  9787. menu.addItem (tr ("Report a problem..."), [this] { crashreporter::showManualReport (&engine.getDeviceManager()); });
  9788. if (updater::offered()) // (not in the Store build: the Store updates it)
  9789. {
  9790. menu.addItem (tr ("Check for updates..."), [] { updater::checkNow(); });
  9791. // round 190gh (B2): back to the version before the last update
  9792. const auto previous = updater::previousVersion();
  9793. menu.addItem (previous.isNotEmpty() ? tr ("Go back to {0}...", { previous }) : tr ("Go back to the previous version..."),
  9794. [] { updater::goBack(); });
  9795. }
  9796. // round 190fq (LYNX's own): an optional way to donate, next to About in every layout; it never unlocks anything
  9797. menu.addItem (tr ("Support LYNX SHARE..."), [] { support::showSupportWindow(); });
  9798. menu.addItem (tr ("About LYNX SHARE"), [] {
  9799. auto* window = makeAboutWindow().release();
  9800. window->enterModalState (true, juce::ModalCallbackFunction::create ([] (int result) {
  9801. if (result == 2) // "Support LYNX SHARE"
  9802. support::showSupportWindow();
  9803. }),
  9804. true);
  9805. keepAboveMainWindow (*window);
  9806. });
  9807. }
  9808. return menu;
  9809. }
  9810. support::StartupNote& MainComponent::supportNoteForSnapshot()
  9811. {
  9812. if (supportNote == nullptr)
  9813. supportNote = std::make_unique<support::StartupNote> (*this, [this] { return supportNoteMoment(); }, [] { return 0; });
  9814. return *supportNote;
  9815. }
  9816. supportnote::Moment MainComponent::supportNoteMoment()
  9817. {
  9818. supportnote::Moment m;
  9819. m.playing = engine.getTransport().playing.load();
  9820. m.recording = engine.isRecording() || engine.isRecordingAudioTakes();
  9821. m.dialogOpen = juce::ModalComponentManager::getInstance()->getNumModalComponents() > 0 || setupOverlay != nullptr
  9822. || (simpleWorkflow != nullptr && (simpleWorkflow->tourRunning() || (simpleWorkflow->tourForSnapshot() != nullptr
  9823. && simpleWorkflow->tourForSnapshot()->isWelcomeShowing())));
  9824. auto* peer = getPeer();
  9825. m.windowShowing = isShowing() && (peer == nullptr || ! peer->isMinimised());
  9826. return m;
  9827. }
  9828. void MainComponent::startSupportNote (bool quietRun)
  9829. {
  9830. supportNoteForSnapshot().begin (quietRun);
  9831. }
  9832. std::unique_ptr<juce::AlertWindow> MainComponent::makeAboutWindow()
  9833. {
  9834. // round 190jp (design190ia SG-22): LYNX's own layout, every block on the dialog's centre line (JUCE's AlertWindow put
  9835. // the logo 56 px left of it and wrapped the donation line to a lone word); the version on a quiet line under the
  9836. // title, the logo 128 px, the texts in balanced centred lines; OK is the accent default, Support the secondary
  9837. static constexpr int width = 432, logoSize = 128; // (a local class can't have static members)
  9838. struct Body final : juce::Component
  9839. {
  9840. struct Block
  9841. {
  9842. std::vector<juce::TextLayout> lines;
  9843. };
  9844. Body()
  9845. {
  9846. const auto quiet = theme::colour::textSecondary;
  9847. add (version, tr ("Version {0}", { JUCE_APPLICATION_VERSION_STRING }), theme::font (theme::type::body), quiet);
  9848. add (about,
  9849. tr ("Lightweight C++/JUCE DAW: FL Studio-style patterns and Ableton Live-style clips.\n"
  9850. "Independent implementation: no Image-Line or Ableton code was copied.")
  9851. // round 190mw (owner rule: the app lists every project format it opens and exports)
  9852. + "\n" + tr ("Opens .flp, .als, .flm, .dawproject, .band and .blx projects; exports .flp, .als and .dawproject."),
  9853. theme::font (theme::type::body), theme::colour::textPrimary);
  9854. add (credits,
  9855. tr ("Logo by {0}", { "w3teal" }) // the community member who made it
  9856. // round 190gl: Ableton Link's credit (GPL-2.0-or-later; THIRD_PARTY.md lists every component)
  9857. + "\n" + tr ("Ableton Link by Ableton AG (GPL 2.0 or later). Every open-source component and its licence: THIRD_PARTY.md"),
  9858. theme::font (theme::type::small), quiet);
  9859. // round 190fq: one short line under the logo, and a button to the Support window (Help › Support LYNX SHARE...)
  9860. add (support, tr ("LYNX SHARE is free and open source. Donations are optional and help it keep going."), theme::font (theme::type::body), quiet);
  9861. setSize (width, top (version) + 14 + logoSize + 14 + height (about) + 10 + height (credits) + 14 + height (support));
  9862. }
  9863. // (each paragraph in lines of balanced length: no lone word on a line of its own)
  9864. void add (Block& b, const juce::String& text, const juce::Font& font, juce::Colour colour)
  9865. {
  9866. for (const auto& paragraph : juce::StringArray::fromLines (text))
  9867. {
  9868. juce::AttributedString s;
  9869. s.append (paragraph, font, colour);
  9870. s.setJustification (juce::Justification::centredTop);
  9871. s.setWordWrap (juce::AttributedString::byWord);
  9872. s.setLineSpacing (2.0f);
  9873. b.lines.emplace_back();
  9874. b.lines.back().createLayoutWithBalancedLineLengths (s, (float) width);
  9875. }
  9876. }
  9877. static int height (const Block& b)
  9878. {
  9879. auto h = 0;
  9880. for (const auto& l : b.lines)
  9881. h += (int) std::ceil (l.getHeight()) + 2;
  9882. return h;
  9883. }
  9884. static int top (const Block& b) { return height (b); }
  9885. void paint (juce::Graphics& g) override
  9886. {
  9887. auto y = 0.0f;
  9888. const auto block = [&] (const Block& b, float gapAfter) {
  9889. for (const auto& l : b.lines)
  9890. {
  9891. l.draw (g, { 0.0f, y, (float) width, l.getHeight() });
  9892. y += std::ceil (l.getHeight()) + 2.0f;
  9893. }
  9894. y += gapAfter;
  9895. };
  9896. block (version, 14.0f);
  9897. g.drawImageWithin (logoImage(), (width - logoSize) / 2, (int) y, logoSize, logoSize, juce::RectanglePlacement::centred);
  9898. y += (float) logoSize + 14.0f;
  9899. block (about, 10.0f);
  9900. block (credits, 14.0f);
  9901. block (support, 0.0f);
  9902. }
  9903. Block version, about, credits, support;
  9904. };
  9905. struct About final : ui::dialog::Dialog
  9906. {
  9907. About() : ui::dialog::Dialog ("LYNX SHARE", width + 2 * ui::dialog::padding)
  9908. {
  9909. setComponentID ("about.window");
  9910. addContent (body);
  9911. setButtonsCentred (true);
  9912. }
  9913. Body body;
  9914. };
  9915. auto window = std::make_unique<About>();
  9916. window->addDialogButton (tr ("Support LYNX SHARE"), 2).setComponentID ("about.support");
  9917. window->addDialogButton (tr ("OK"), 1, true);
  9918. return std::unique_ptr<juce::AlertWindow> (window.release());
  9919. }
  9920. void MainComponent::showLanguageChoice (const juce::String& id)
  9921. {
  9922. if (id == i18n::saved())
  9923. return;
  9924. i18n::save (id);
  9925. const auto restart = [this] {
  9926. confirmDiscard ([] {
  9927. lynx::platform::relaunchApp(); // through the package in the Store build (platform/Package.h)
  9928. juce::JUCEApplication::quit();
  9929. });
  9930. };
  9931. // the message is shown in the language just chosen
  9932. const auto table = i18n::tableText (id);
  9933. const juce::LocalisedStrings strings (table, false);
  9934. auto say = [&] (const char* text) { return table.isEmpty() ? juce::String::fromUTF8 (text) : strings.translate (juce::String::fromUTF8 (text)); };
  9935. auto* window = new juce::AlertWindow (say (TR_NOOP ("Language")), say (TR_NOOP ("The new language is applied when LYNX SHARE restarts.")),
  9936. juce::MessageBoxIconType::InfoIcon);
  9937. window->addButton (say (TR_NOOP ("Restart now")), 1, juce::KeyPress (juce::KeyPress::returnKey));
  9938. window->addButton (say (TR_NOOP ("Later")), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  9939. window->enterModalState (true, juce::ModalCallbackFunction::create ([restart] (int result) {
  9940. if (result == 1)
  9941. restart();
  9942. }),
  9943. true);
  9944. }
  9945. bool MainComponent::isProjectFile (const juce::File& file)
  9946. {
  9947. return file.hasFileExtension (juce::String (ProjectFile::extension) + ";dawproj;dawproject;flp;als;flm;blx;zip;" + sessionpack::extension);
  9948. }
  9949. bool MainComponent::isInterestedInFileDrag (const juce::StringArray& files)
  9950. {
  9951. return files.size() == 1 && isProjectFile (juce::File (files[0])) && ! projectLoadRunning();
  9952. }
  9953. void MainComponent::filesDropped (const juce::StringArray& files, int, int)
  9954. {
  9955. if (files.size() == 1 && isProjectFile (juce::File (files[0])))
  9956. openFileRequest (juce::File (files[0]));
  9957. }
  9958. // Round 190ih (PLAN R3, DF-51 / DF-37): with backups off, FL's "Never (just remind every 10 min)" puts a reminder in
  9959. // the hint bar (FL manual, File settings › Backup) and its Save As button "flashes as a save reminder" (Toolbar
  9960. // shortcut icons): after ten minutes of unsaved changes the bar says so and the toolbar's Save button blinks until the
  9961. // project is saved (steady lit with Settings › Animations off). Nothing runs while backups are on or nothing changed.
  9962. void MainComponent::updateSaveReminder()
  9963. {
  9964. const auto due = autosaveMinutes == 0 && engine.isModified();
  9965. if (! due)
  9966. {
  9967. saveReminderTicks = 0;
  9968. if (saveButton.getToggleState())
  9969. saveButton.setToggleState (false, juce::dontSendNotification);
  9970. return;
  9971. }
  9972. if (++saveReminderTicks % (30 * 60 * 10) == 0) // every 10 minutes at the 30 Hz timer
  9973. ui::postNotice ({ tr ("Reminder: this project has unsaved changes (backups are off: Settings > General > Save a backup copy)"), {}, false, false }, 8000);
  9974. if (saveReminderTicks >= 30 * 60 * 10)
  9975. {
  9976. const auto lit = ! ui::motion::enabled() || (juce::Time::getMillisecondCounter() / 500u) % 2u == 0u;
  9977. saveButton.setToggleState (lit, juce::dontSendNotification);
  9978. }
  9979. }
  9980. // round 190ih: Alt+1 … Alt+0, FL's keys for the ten most recent projects (asks to save the current one first)
  9981. void MainComponent::openRecent (int index)
  9982. {
  9983. if (index < 0 || index >= juce::jmin (10, recent.getNumFiles()))
  9984. return;
  9985. const auto file = recent.getFile (index);
  9986. if (file.existsAsFile())
  9987. openFileRequest (file);
  9988. }
  9989. void MainComponent::rememberRecent (const juce::File& file)
  9990. {
  9991. recent.addFile (file);
  9992. PluginHost::settingsFolder().getChildFile ("recentes.txt").replaceWithText (recent.toString());
  9993. menuItemsChanged();
  9994. }
  9995. std::unique_ptr<juce::Component> MainComponent::makeHelpContent (const keys::KeyMap* keyMapIn)
  9996. {
  9997. // shortcut sheet: sections of "keys - action" rows, in two columns
  9998. struct Row
  9999. {
  10000. const char* keys;
  10001. const char* action;
  10002. };
  10003. struct Section
  10004. {
  10005. const char* title;
  10006. std::vector<Row> rows;
  10007. };
  10008. static const std::vector<Section> sections {
  10009. { TR_NOOP ("General"),
  10010. { { TR_NOOP ("Space"), TR_NOOP ("Play / stop (back to where playback started)") },
  10011. { "Ctrl+Space", TR_NOOP ("Play / pause") },
  10012. { "Ctrl+Z / Ctrl+Y", TR_NOOP ("Undo / redo") },
  10013. { "Ctrl+N / Ctrl+O", TR_NOOP ("New project / open") },
  10014. { "Ctrl+S / Ctrl+Shift+S", TR_NOOP ("Save / save as") },
  10015. { "Ctrl+R", TR_NOOP ("Export audio") },
  10016. { "Enter", TR_NOOP ("Maximize or restore the Playlist") },
  10017. { "L", TR_NOOP ("Pattern / song mode") },
  10018. { "Ctrl+T", TR_NOOP ("Typing keyboard to piano on/off") },
  10019. { "Z..M Q..P", TR_NOOP ("PC keyboard as a piano (selected channels)") },
  10020. { "Numpad +/-", TR_NOOP ("Next / previous pattern") },
  10021. { "Ctrl+Shift+Ins", TR_NOOP ("Insert an empty pattern before the current one") } } },
  10022. { TR_NOOP ("Workspace"),
  10023. { { TR_NOOP ("Drag a panel title"), TR_NOOP ("Move (snaps; Alt: free)") },
  10024. { TR_NOOP ("Double-click a title"), TR_NOOP ("Maximize / restore") },
  10025. { TR_NOOP ("Title buttons"), TR_NOOP ("Detach into a window, maximize, close") },
  10026. { TR_NOOP ("View menu"), TR_NOOP ("Reset, save and load layouts") } } },
  10027. { TR_NOOP ("Channel Rack and Mixer"),
  10028. { { TR_NOOP ("Click the name"), TR_NOOP ("Open/close the editor (Alt keeps others open)") },
  10029. { TR_NOOP ("Ctrl+click the name"), TR_NOOP ("Audition the channel") },
  10030. { TR_NOOP ("Selector / Up, Down"), TR_NOOP ("Select (Ctrl: add, Shift: range)") },
  10031. { "Alt+Up / Alt+Down", TR_NOOP ("Move the selected channels") },
  10032. { "Alt+C / Alt+Del", TR_NOOP ("Clone / delete the selected channels") },
  10033. { "Ctrl+L", TR_NOOP ("Send the selected channels to free mixer inserts") },
  10034. { TR_NOOP ("1..0 / Ctrl+1..0"), TR_NOOP ("Mute / solo channels 1-10 (typing piano off)") },
  10035. { TR_NOOP ("Knobs and faders"), TR_NOOP ("Drag (Ctrl: fine), wheel, Alt+click or middle-click resets") },
  10036. { TR_NOOP ("Right-click a knob/fader"), TR_NOOP ("Type value, reset, automation, MIDI link") },
  10037. { TR_NOOP ("Right-click Pattern / Song"), TR_NOOP ("Show the Channel Rack / Playlist") },
  10038. { TR_NOOP ("Double-click Stop"), TR_NOOP ("All notes off") } } },
  10039. { "Piano Roll",
  10040. { { TR_NOOP ("Click"), TR_NOOP ("Create a note (or chord, via the selector)") },
  10041. { TR_NOOP ("Drag"), TR_NOOP ("Move; the right edge changes the length") },
  10042. { TR_NOOP ("Right-click"), TR_NOOP ("Delete") },
  10043. { TR_NOOP ("Ctrl+drag"), TR_NOOP ("Select (Ctrl+click adds to the selection)") },
  10044. { TR_NOOP ("Shift+drag"), TR_NOOP ("Copy") },
  10045. { "Ctrl+A/C/X/V", TR_NOOP ("Select all, copy, cut, paste") },
  10046. { "Ctrl+B / Ctrl+Q", TR_NOOP ("Duplicate / quantize") },
  10047. { "Alt+M / Shift+Alt+M", TR_NOOP ("Mute / unmute") },
  10048. { "Ctrl+P / Ctrl+D", TR_NOOP ("Portamento / deselect") },
  10049. { TR_NOOP ("Shift+arrows"), TR_NOOP ("Transpose a semitone / move by the grid (Ctrl+Up/Down: an octave)") },
  10050. { TR_NOOP ("Alt / Ctrl+wheel"), TR_NOOP ("Disable snap / zoom") } } },
  10051. { "Playlist",
  10052. { { TR_NOOP ("Click"), TR_NOOP ("Paint the current pattern") },
  10053. { TR_NOOP ("Drag on the ruler"), TR_NOOP ("Set the loop (right-click clears)") },
  10054. { TR_NOOP ("Right-click a clip name"), TR_NOOP ("Split, make unique...") },
  10055. { TR_NOOP ("Track LED"), TR_NOOP ("Mute the track") },
  10056. { "Ctrl+A/C/X/V Ctrl+B", TR_NOOP ("Edit and duplicate") } } },
  10057. };
  10058. // the fourth column: every F-key of the live key map (issue #23: the sheet listed no F-keys), custom keys included
  10059. const keys::KeyMap defaults;
  10060. const auto& map = keyMapIn != nullptr ? *keyMapIn : defaults;
  10061. std::vector<std::pair<juce::String, juce::String>> functionKeys;
  10062. for (const auto& b : map.functionKeyBindings())
  10063. if (const auto* action = keys::findAction (b.actionId))
  10064. {
  10065. auto text = tr (action->description);
  10066. if (b.context != keys::Context::global)
  10067. text << " (" << tr (b.context == keys::Context::browser ? "Browser"
  10068. : b.context == keys::Context::mixer ? "Mixer"
  10069. : b.context == keys::Context::playlist ? "Playlist"
  10070. : b.context == keys::Context::pianoRoll ? "Piano Roll"
  10071. : "Channel Rack")
  10072. << ")";
  10073. functionKeys.push_back ({ juce::String (keys::displayString (b.chord)), text });
  10074. }
  10075. struct Sheet final : juce::Component
  10076. {
  10077. explicit Sheet (std::vector<std::pair<juce::String, juce::String>> f) : fkeys (std::move (f))
  10078. {
  10079. setSize (1500, juce::jmax (520, 20 + 28 + (int) fkeys.size() * 22 + 20));
  10080. }
  10081. void paint (juce::Graphics& g) override
  10082. {
  10083. using namespace theme;
  10084. g.fillAll (colour::bg2);
  10085. const auto columnWidth = (getWidth() - 5 * 24) / 4;
  10086. int column = 0, y = 20;
  10087. for (std::size_t i = 0; i < sections.size(); ++i)
  10088. {
  10089. if (i == 2 || i == 3) // next column
  10090. {
  10091. ++column;
  10092. y = 20;
  10093. }
  10094. const auto x = 24 + column * (columnWidth + 24);
  10095. const auto& section = sections[i];
  10096. g.setColour (colour::accent);
  10097. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  10098. g.setColour (colour::textPrimary);
  10099. g.setFont (font (type::title, true));
  10100. g.drawText (tr (section.title), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  10101. y += 28;
  10102. for (const auto& row : section.rows)
  10103. {
  10104. const auto keys = tr (row.keys);
  10105. g.setFont (font (type::small, true));
  10106. const auto keyWidth = juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14;
  10107. g.setColour (colour::bg4);
  10108. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  10109. g.setColour (colour::textPrimary);
  10110. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  10111. g.setColour (colour::textSecondary);
  10112. g.setFont (font (type::body));
  10113. g.drawFittedText (tr (row.action), x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.85f);
  10114. y += 24;
  10115. }
  10116. y += 14;
  10117. }
  10118. // Function keys
  10119. const auto x = 24 + 3 * (columnWidth + 24);
  10120. y = 20;
  10121. g.setColour (colour::accent);
  10122. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  10123. g.setColour (colour::textPrimary);
  10124. g.setFont (font (type::title, true));
  10125. g.drawText (tr ("Function keys"), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  10126. y += 28;
  10127. g.setFont (font (type::small, true));
  10128. int keyWidth = 0;
  10129. for (const auto& [keys, text] : fkeys)
  10130. keyWidth = juce::jmax (keyWidth, juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14);
  10131. for (const auto& [keys, text] : fkeys)
  10132. {
  10133. g.setFont (font (type::small, true));
  10134. g.setColour (colour::bg4);
  10135. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  10136. g.setColour (colour::textPrimary);
  10137. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  10138. g.setColour (colour::textSecondary);
  10139. g.setFont (font (type::body));
  10140. g.drawFittedText (text, x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.8f);
  10141. y += 22;
  10142. }
  10143. }
  10144. std::vector<std::pair<juce::String, juce::String>> fkeys;
  10145. };
  10146. return std::make_unique<Sheet> (std::move (functionKeys));
  10147. }
  10148. void MainComponent::showHelp()
  10149. {
  10150. juce::DialogWindow::LaunchOptions options;
  10151. options.content.setOwned (makeHelpContent (&keyMap).release());
  10152. options.dialogTitle = tr ("LYNX SHARE shortcuts");
  10153. options.dialogBackgroundColour = theme::colour::bg2;
  10154. options.useNativeTitleBar = true;
  10155. options.resizable = true;
  10156. options.escapeKeyTriggersCloseButton = true;
  10157. if (auto* dialog = options.launchAsync())
  10158. {
  10159. keepAboveMainWindow (*dialog);
  10160. helpWindow = dialog;
  10161. }
  10162. }
  10163. void MainComponent::closeHelp()
  10164. {
  10165. // (the key may come from the sheet itself: delete it after this call stack)
  10166. if (helpWindow == nullptr)
  10167. return;
  10168. helpWindow->setVisible (false);
  10169. juce::MessageManager::callAsync ([w = helpWindow] { delete w.getComponent(); });
  10170. helpWindow = nullptr;
  10171. }
  10172. void MainComponent::closeUnfocusedWindows()
  10173. {
  10174. // FL's Ctrl+F12 (CloseAllUnfocusedWindowsAction, round 167o): every window but the focused one closes. LYNX's
  10175. // docked or detached panels and dialogs that wait for an answer stay, as for F12.
  10176. auto* focused = juce::TopLevelWindow::getActiveTopLevelWindow();
  10177. auto* main = getTopLevelComponent();
  10178. juce::Array<juce::Component::SafePointer<juce::DocumentWindow>> close;
  10179. for (int i = 0; i < juce::TopLevelWindow::getNumTopLevelWindows(); ++i)
  10180. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (i)))
  10181. if (w != focused && w != main && w->isVisible() && ! w->isCurrentlyModal() && ! (bool) w->getProperties()["lynxPanel"])
  10182. close.add (w);
  10183. for (auto& w : close)
  10184. if (w != nullptr)
  10185. w->closeButtonPressed();
  10186. }
  10187. void MainComponent::showSetupWizard()
  10188. {
  10189. // on top of the main window (round 140), so the DAW is visible behind it from the first start on
  10190. if (setupOverlay != nullptr)
  10191. return;
  10192. auto safe = juce::Component::SafePointer<MainComponent> (this);
  10193. setupOverlay = lynx::makeSetupWizardOverlay (
  10194. engine,
  10195. [safe] (const juce::String& language) {
  10196. if (safe != nullptr)
  10197. safe->showLanguageChoice (language);
  10198. },
  10199. [safe] {
  10200. juce::MessageManager::callAsync ([safe] { // the overlay's own button is still running
  10201. if (safe != nullptr)
  10202. safe->setupOverlay.reset();
  10203. });
  10204. },
  10205. (int) layoutStyle,
  10206. [safe] (int style) { // round 184a S17: the workflow chosen in the wizard (Pattern stays selected unless changed)
  10207. juce::MessageManager::callAsync ([safe, style] {
  10208. if (safe == nullptr)
  10209. return;
  10210. safe->setLayoutStyle ((layoutstyle::Style) juce::jlimit (0, layoutstyle::count - 1, style));
  10211. safe->saveUiSettings();
  10212. });
  10213. });
  10214. addAndMakeVisible (*setupOverlay);
  10215. setupOverlay->setBounds (getLocalBounds());
  10216. setupOverlay->toFront (true);
  10217. hostSetupOverlayNatively();
  10218. }
  10219. void MainComponent::showImportReport()
  10220. {
  10221. // summary of what the .flp had that LYNX doesn't reproduce exactly (only when there is something to say)
  10222. const auto& r = engine.getImportReport();
  10223. const auto& missing = engine.getMissingPlugins();
  10224. auto list = [] (const std::map<std::string, int>& items) {
  10225. std::vector<std::pair<int, std::string>> sorted;
  10226. for (const auto& [name, count] : items)
  10227. sorted.push_back ({ count, name });
  10228. std::sort (sorted.rbegin(), sorted.rend());
  10229. juce::StringArray lines;
  10230. for (const auto& [count, name] : sorted)
  10231. lines.add (" " + juce::String::fromUTF8 (name.c_str()) + (count > 1 ? " (" + juce::String (count) + ")" : juce::String()));
  10232. return lines.joinIntoString ("\n");
  10233. };
  10234. juce::String text;
  10235. if (! r.approximated.empty())
  10236. text << tr ("Approximated by the built-in synth:") << "\n" << list (r.approximated) << "\n\n";
  10237. if (! r.unsupported.empty())
  10238. text << tr ("No equivalent (played with a synth preset):") << "\n" << list (r.unsupported) << "\n\n";
  10239. // round qafix190kq (QA of 0.1.30): automation, clip data, grooves, scenes, MIDI / note effects... are not instruments
  10240. // played with a synth preset; they have a heading of their own
  10241. if (! r.notReproduced.empty())
  10242. text << tr ("Not reproduced (left out or played differently):") << "\n" << list (r.notReproduced) << "\n\n";
  10243. if (const auto& matched = engine.getMatchedPlugins(); ! matched.isEmpty())
  10244. text << tr ("Plugins found on this PC:") << "\n " << matched.joinIntoString ("\n ") << "\n\n";
  10245. if (! missing.isEmpty())
  10246. text << tr ("Plugins not installed on this PC (or in a folder LYNX SHARE doesn't scan; Options > Setup wizard):") << "\n "
  10247. << missing.joinIntoString ("\n ") << "\n\n";
  10248. if (const auto& lost = engine.getPluginsWithoutState(); ! lost.isEmpty())
  10249. text << tr ("Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):") << "\n "
  10250. << lost.joinIntoString ("\n ") << "\n\n";
  10251. if (const auto failed = engine.getPluginHost().getLoadFailures(); ! failed.isEmpty())
  10252. text << tr ("Plugins installed but not loaded (silent):") << "\n " << failed.joinIntoString ("\n ") << "\n\n";
  10253. if (! r.droppedEffects.empty())
  10254. text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
  10255. if (! r.partialEffects.empty())
  10256. text << tr ("Effects kept but approximated or partly reproduced:") << "\n" << list (r.partialEffects) << "\n\n";
  10257. if (r.missingSamples > 0)
  10258. text << tr ("Samples missing on this machine: {0}", { juce::String (r.missingSamples) }) << "\n";
  10259. if (r.relocatedSamples > 0)
  10260. text << tr ("Samples found in another folder than the project says (FL Studio's folders or next to the project): {0}",
  10261. { juce::String (r.relocatedSamples) }) << "\n";
  10262. if (text.isEmpty())
  10263. return;
  10264. text = text.trimEnd();
  10265. // round 190kp (QA of 0.1.30): a long report (a big Live set has 40+ lines) was cut at the screen's height, with no way
  10266. // to read the rest. Past a screenful the lines go into a read-only text box of a fixed size that scrolls (JUCE's own
  10267. // text block grows with the text and ran under the OK button); a short report shows as before.
  10268. constexpr int plainLines = 30;
  10269. if (juce::StringArray::fromLines (text).size() <= plainLines)
  10270. {
  10271. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Project import"), text);
  10272. return;
  10273. }
  10274. struct ReportWindow final : juce::AlertWindow
  10275. {
  10276. explicit ReportWindow (const juce::String& report, int height)
  10277. : juce::AlertWindow (tr ("Project import"), {}, juce::MessageBoxIconType::InfoIcon)
  10278. {
  10279. box.setMultiLine (true, true);
  10280. box.setReadOnly (true);
  10281. box.setScrollbarsShown (true);
  10282. box.setCaretVisible (false);
  10283. box.setColour (juce::TextEditor::backgroundColourId, juce::Colours::transparentBlack);
  10284. box.setColour (juce::TextEditor::outlineColourId, juce::Colours::transparentBlack);
  10285. box.setColour (juce::TextEditor::focusedOutlineColourId, juce::Colours::transparentBlack);
  10286. box.setColour (juce::TextEditor::shadowColourId, juce::Colours::transparentBlack);
  10287. if (isColourSpecified (juce::AlertWindow::textColourId))
  10288. box.setColour (juce::TextEditor::textColourId, findColour (juce::AlertWindow::textColourId));
  10289. box.setFont (getLookAndFeel().getAlertWindowMessageFont());
  10290. box.setText (report, false);
  10291. box.setSize (760, height);
  10292. addCustomComponent (&box);
  10293. addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey), juce::KeyPress (juce::KeyPress::escapeKey));
  10294. }
  10295. juce::TextEditor box;
  10296. };
  10297. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  10298. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea.getHeight()
  10299. : 800;
  10300. auto* window = new ReportWindow (text, juce::jlimit (240, 600, area - 260));
  10301. window->enterModalState (true, nullptr, true);
  10302. keepAboveMainWindow (*window);
  10303. }
  10304. void MainComponent::showAudioSettings()
  10305. {
  10306. openSettings ((int) SettingsPage::audio);
  10307. }
  10308. // --- the Channel Rack's filter box ---------------------------------------------------------------
  10309. void MainComponent::FilterBox::paint (juce::Graphics& g)
  10310. {
  10311. using namespace theme;
  10312. auto area = getLocalBounds().toFloat();
  10313. g.setColour (hovered ? colour::bg3 : colour::bg1);
  10314. g.fillRoundedRectangle (area, radius::sm);
  10315. g.setColour (hovered ? colour::borderStrong : colour::border);
  10316. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  10317. // round 170e2: a funnel names the box (it showed only "All")
  10318. icons::draw (g, Icon::filter, area.withWidth (22.0f).withSizeKeepingCentre (13.0f, 13.0f), colour::textSecondary);
  10319. g.setColour (colour::textPrimary);
  10320. g.setFont (font (type::small));
  10321. g.drawText (text, getLocalBounds().withTrimmedLeft (22).withTrimmedRight (16), juce::Justification::centredLeft, true);
  10322. icons::draw (g, Icon::chevronDown, area.removeFromRight (16.0f).reduced (3.0f).translated (-2.0f, 0.0f), colour::textSecondary);
  10323. }
  10324. // FL's Tools › Macros › Prepare for performance mode ([DECOMP] FUN_0122d010, its "Marker settings" dialog: marker count
  10325. // 4 / 8 / 16 / 32 / 64, default 16; spacing 1…128 steps, default 16 = a bar): room for a launch grid before the song,
  10326. // a marker per column, a Start marker, Performance mode on, the zone in view. FL warns it can't be undone; in LYNX it
  10327. // is one undo step.
  10328. void MainComponent::prepareForPerformance()
  10329. {
  10330. auto* window = new juce::AlertWindow (tr ("Prepare for performance mode"),
  10331. tr ("Inserts empty columns before the song for the clips to launch, a marker on each, and a Start "
  10332. "marker where the song begins; Performance mode is turned on."),
  10333. juce::MessageBoxIconType::NoIcon);
  10334. window->addComboBox ("count", { "4", "8", "16", "32", "64" }, tr ("Marker count"));
  10335. window->addComboBox ("spacing", { tr ("1 step"), tr ("2 steps"), tr ("1 beat"), tr ("2 beats"), tr ("1 bar"), tr ("2 bars"), tr ("4 bars"), tr ("8 bars") },
  10336. tr ("Spacing"));
  10337. if (auto* c = window->getComboBoxComponent ("count"))
  10338. c->setSelectedItemIndex (2, juce::dontSendNotification);
  10339. if (auto* c = window->getComboBoxComponent ("spacing"))
  10340. c->setSelectedItemIndex (4, juce::dontSendNotification);
  10341. window->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  10342. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  10343. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  10344. if (result != 1)
  10345. return;
  10346. const auto count = 4 << juce::jlimit (0, 4, window->getComboBoxComponent ("count")->getSelectedItemIndex());
  10347. const auto steps = 1 << juce::jlimit (0, 7, window->getComboBoxComponent ("spacing")->getSelectedItemIndex());
  10348. engine.editSong ([count, steps] (Song& s) { perf::prepareForPerformance (s, count, (std::int64_t) steps * (ppq / 4)); });
  10349. showPanel (Panel::playlist);
  10350. playlist.runAction ("playlist.zoomPerformance");
  10351. }),
  10352. true);
  10353. keepAboveMainWindow (*window);
  10354. }
  10355. } // namespace lynx
  10356. // --- the game controller (round 184a, S16) ---------------------------------------------------------------------------
  10357. namespace lynx
  10358. {
  10359. void MainComponent::updateGamepad()
  10360. {
  10361. const auto on = engine.getMidiPrefs().gamepad;
  10362. if (on == (gamepadInput != nullptr))
  10363. return;
  10364. if (! on)
  10365. {
  10366. gamepadInput.reset();
  10367. if (gamepadHints != nullptr)
  10368. removeChildComponent (gamepadHints.get());
  10369. gamepadHints.reset();
  10370. return;
  10371. }
  10372. gamepadInput = std::make_unique<GamepadInput> ([safe = juce::Component::SafePointer<MainComponent> (this)] (const gamepad::Changes& c,
  10373. const gamepad::State& s, double dt) {
  10374. if (safe != nullptr)
  10375. safe->gamepadChanges (c, s, dt);
  10376. });
  10377. if (! gamepadInput->available())
  10378. ui::postHint ({ tr ("Game controllers are not supported on this system yet."), {} }, 5000);
  10379. }
  10380. int MainComponent::gamepadInsert() const
  10381. {
  10382. const auto& song = engine.getSong();
  10383. const auto track = playlist.getCurrentTrack();
  10384. if (track >= 0 && track < (int) song.playlistTracks.size())
  10385. if (const auto insert = song.playlistTracks[(std::size_t) track].mixerTrack; insert >= 0 && insert < (int) song.mixer.size())
  10386. return insert;
  10387. const auto channel = engine.getSelectedChannel();
  10388. if (channel >= 0 && channel < (int) song.channels.size())
  10389. if (const auto insert = song.channels[(std::size_t) channel].mixerTrack; insert >= 0 && insert < (int) song.mixer.size())
  10390. return insert;
  10391. return -1;
  10392. }
  10393. void MainComponent::gamepadChanges (const gamepad::Changes& c, const gamepad::State& s, double seconds)
  10394. {
  10395. using namespace gamepad;
  10396. // every change is also a MIDI controller on channel 16, so Link to controller can learn it
  10397. for (int i = 0; i < c.controllerCount; ++i)
  10398. engine.injectMidiInput (juce::MidiMessage::controllerEvent (midiChannel, c.controller[(std::size_t) i], c.value[(std::size_t) i]));
  10399. if (c.connectedChanged)
  10400. ui::postHint ({ s.connected ? tr ("Game controller connected") : tr ("Game controller disconnected"), {} }, 3000);
  10401. const auto& map = defaultMap();
  10402. for (int i = 0; i < c.pressedCount; ++i)
  10403. {
  10404. const auto action = map[(std::size_t) c.pressed[(std::size_t) i]];
  10405. switch (action)
  10406. {
  10407. case Action::playStop: runAction ("transport.playStop"); break;
  10408. case Action::record: runAction ("transport.record"); break;
  10409. case Action::undo: runAction ("edit.undo"); break;
  10410. case Action::metronome: runAction ("transport.metronome"); break;
  10411. case Action::previousPattern: runAction ("pattern.previous"); break;
  10412. case Action::nextPattern: runAction ("pattern.next"); break;
  10413. case Action::finish: runAction ("file.export"); break;
  10414. case Action::previousTrack:
  10415. case Action::nextTrack:
  10416. {
  10417. const auto t = playlist.getCurrentTrack();
  10418. playlist.selectTrack (t < 0 ? 0 : t + (action == Action::nextTrack ? 1 : -1));
  10419. const auto& song = engine.getSong();
  10420. const auto now = playlist.getCurrentTrack();
  10421. if (now >= 0 && now < (int) song.playlistTracks.size())
  10422. if (const auto ch = song.playlistTracks[(std::size_t) now].channel; ch >= 0 && ch < (int) song.channels.size())
  10423. engine.setSelectedChannel (ch); // an instrument track: its channel plays the keys
  10424. break;
  10425. }
  10426. case Action::barBack:
  10427. case Action::barForward:
  10428. {
  10429. // to the previous / next bar line (from inside a bar, back goes to its start)
  10430. const auto bar = (double) engine.getSong().barTicks();
  10431. const auto at = engine.getTransport().positionTicks.load() / bar;
  10432. const auto target = action == Action::barForward ? std::floor (at + 1e-6) + 1.0 : std::ceil (at - 1e-6) - 1.0;
  10433. engine.seek (juce::jmax (0.0, target) * bar);
  10434. break;
  10435. }
  10436. case Action::hints:
  10437. if (gamepadHints == nullptr)
  10438. {
  10439. gamepadHints = makeGamepadHints();
  10440. addChildComponent (*gamepadHints);
  10441. }
  10442. gamepadHints->setCentrePosition (getLocalBounds().getCentre());
  10443. gamepadHints->setVisible (true);
  10444. gamepadHints->toFront (false);
  10445. break;
  10446. case Action::none:
  10447. break;
  10448. }
  10449. }
  10450. for (int i = 0; i < c.releasedCount; ++i)
  10451. if (map[(std::size_t) c.released[(std::size_t) i]] == Action::hints && gamepadHints != nullptr)
  10452. gamepadHints->setVisible (false);
  10453. // the triggers: the selected track's volume; the left stick's X: its pan (only while pushed)
  10454. const auto insert = gamepadInsert();
  10455. if (insert < 0)
  10456. return;
  10457. if (const auto db = volumeStepDb (s, seconds); db != 0.0)
  10458. engine.editLevels ([insert, db] (Song& song) {
  10459. auto& v = song.mixer[(std::size_t) insert].volume;
  10460. v = juce::jlimit (0.0f, 1.0f, faderPosition (faderGain (v) * juce::Decibels::decibelsToGain ((float) db)));
  10461. });
  10462. if (const auto pan = axis (s, Axis::leftX); pan != 0.0f)
  10463. engine.editLevels ([insert, pan] (Song& song) { song.mixer[(std::size_t) insert].pan = juce::jlimit (-1.0f, 1.0f, pan); });
  10464. }
  10465. } // namespace lynx
  10466. // round 190iv: the toolbar per layout style (Simple capsules, Live control bar); kept in its own file
  10467. #include "ui/ToolbarLooks.inc"