MainComponent.cpp 419 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153
  1. #include "ui/ControllerBridge.h"
  2. #include "ui/AudioClipboard.h"
  3. #include "ui/MidiClipboard.h"
  4. #include "ui/VideoTracks.h"
  5. #include "ui/AdrWindow.h"
  6. #include "ui/GamepadInput.h"
  7. #include "ui/ThemeSettings.h"
  8. #include "ui/ColourPicker.h"
  9. #include "core/EditorLimit.h"
  10. #include "core/PlaylistOps.h"
  11. #include "core/ClipOps.h"
  12. #include "core/NoteNames.h"
  13. #include "core/KeyGuess.h"
  14. #include "core/ProjectKey.h"
  15. #include "ui/FileChoosers.h"
  16. #include "ui/ProjectLoading.h"
  17. #include "ui/UiTrace.h"
  18. #include "core/LoadTrace.h"
  19. #include "ui/MainComponent.h"
  20. #include "ui/NativeChild.h"
  21. #include "core/PlaylistOps.h"
  22. #include "core/Performance.h"
  23. #include "core/TransportEdit.h"
  24. #include "ui/CrashReporter.h"
  25. #include "ui/DanceView.h"
  26. #include "engine/AudioLogger.h"
  27. #include "ui/PluginSkin.h"
  28. #include "platform/Paths.h"
  29. #include "ui/SetupWizard.h"
  30. #include "core/FlPluginDb.h"
  31. #include "core/Preferences.h"
  32. #include "core/EditorPolish.h"
  33. #include "ui/HistoryPanel.h"
  34. #include "ui/VersionsPanel.h"
  35. #include "ui/PluginsOffPanel.h"
  36. #include "ui/MissingFilesDialog.h"
  37. #include "ui/SettingsDialog.h"
  38. #include "ui/PluginManager.h"
  39. #include "ui/ShortcutManager.h"
  40. #include "ui/WaveformView.h"
  41. #include "ui/QuickAddPalette.h"
  42. #include "ui/PluginPickerView.h"
  43. #include "ui/PatcherEditor.h"
  44. #include "ui/ToolWindow.h"
  45. #include "ui/RackEditor.h"
  46. #include "ui/LoopStarterWindow.h"
  47. #include "ui/WindowOwner.h"
  48. #include "engine/PluginSandbox.h"
  49. #include "platform/FileTypes.h"
  50. #include "platform/CrashGuard.h"
  51. #include "platform/LinuxRealtime.h"
  52. #include "platform/Package.h"
  53. #include "engine/Text.h"
  54. #include "core/MetronomeVoice.h"
  55. #include "core/RackOps.h"
  56. #include "core/Templates.h"
  57. #include "ui/NewProjectDialog.h"
  58. #include "ui/PluginMonitorWindow.h"
  59. #include "ui/TouchKeyboard.h"
  60. #include "engine/MidiFileIo.h"
  61. #include "engine/ProjectFile.h"
  62. #include "engine/ProjectPackage.h"
  63. #include "engine/SessionPack.h"
  64. #include "ui/SessionDialogs.h"
  65. #include "engine/LiveSessions.h"
  66. #include "ui/LiveChat.h"
  67. #include "ui/LiveRemoteUi.h"
  68. #include "core/ProjectSafety.h"
  69. #include "core/MissingFiles.h"
  70. #include "ui/AutomationUi.h"
  71. #include "ui/ChannelSettings.h"
  72. #include "core/ClipLauncher.h"
  73. #include "ui/ClipGridComponent.h"
  74. #include "ui/Dialogs.h"
  75. #include "ui/EventEditor.h"
  76. #include "ui/EditorTools.h"
  77. #include "ui/AudioEditor.h"
  78. #include "ui/TempoTapper.h"
  79. #include "ui/ExportDialog.h"
  80. #include "ui/AlsExportDialog.h"
  81. #include "ui/OtherAppsExport.h"
  82. #include "ui/FlStudioExportDialog.h"
  83. #include "ui/ParametricEqEditor.h"
  84. #include "ui/PluginWindow.h"
  85. #include "ui/I18n.h"
  86. #include "ui/Theme.h"
  87. #include "ui/WaveformView.h"
  88. #include "core/HintMarkup.h"
  89. #include "core/SongStats.h"
  90. #if JUCE_PLUGINHOST_VST3
  91. namespace juce
  92. {
  93. // cmake/LynxPatchJuce.cmake fix 20 (round 177b): LYNX's items at the top of a VST3 plugin's parameter context menu
  94. extern void (*lynxVst3ParamMenuHook) (AudioPluginInstance&, int, PopupMenu&);
  95. } // namespace juce
  96. #endif
  97. namespace lynx
  98. {
  99. // round 177b: the engine LYNX's VST3 parameter-menu hook uses (set while the main window lives)
  100. static AudioEngine*& vst3MenuEngine()
  101. {
  102. static AudioEngine* engine = nullptr;
  103. return engine;
  104. }
  105. namespace
  106. {
  107. using workspace::Panel;
  108. constexpr Panel panelOrder[] = { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser };
  109. const char* panelAction (Panel p)
  110. {
  111. switch (p)
  112. {
  113. case Panel::playlist: return "panel.playlist";
  114. case Panel::channelRack: return "panel.channelRack";
  115. case Panel::pianoRoll: return "panel.pianoRoll";
  116. case Panel::mixer: return "panel.mixer";
  117. case Panel::browser: return "panel.browser";
  118. }
  119. return "";
  120. }
  121. juce::String panelName (Panel p)
  122. {
  123. switch (p)
  124. {
  125. case Panel::playlist: return "Playlist";
  126. case Panel::channelRack: return "Channel Rack";
  127. case Panel::pianoRoll: return "Piano Roll";
  128. case Panel::mixer: return "Mixer";
  129. case Panel::browser: return "Browser";
  130. }
  131. return {};
  132. }
  133. } // namespace
  134. MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
  135. : persistent (restoreUserSettings),
  136. engine (e),
  137. rack (e),
  138. pianoRoll (e),
  139. playlist (e),
  140. mixer (e),
  141. browser (e)
  142. {
  143. rackcards::install(); // (round 183c: racks show as their own card in the Device View)
  144. heldKeys.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on, true); });
  145. connectBrowser (browser);
  146. addChildComponent (updateBar);
  147. updateBar.onVisibilityChanged = [this] { resized(); };
  148. if (restoreUserSettings) // (the real window: Update saves the project as on quit and reopens it)
  149. updater::setHost ({ [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  150. if (safe != nullptr)
  151. safe->confirmDiscard (std::move (then));
  152. },
  153. [safe = juce::Component::SafePointer<MainComponent> (this)] {
  154. return safe != nullptr ? safe->currentFile : juce::File();
  155. } });
  156. mixeroptions::changed = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  157. if (safe != nullptr)
  158. {
  159. safe->saveUiSettings();
  160. safe->playlist.repaint();
  161. }
  162. };
  163. mixeroptions::setShowUsedOnly = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  164. if (safe != nullptr)
  165. safe->mixer.getStripsForSnapshot().setShowUsedOnly (on);
  166. };
  167. mixeroptions::setShowLoudness = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  168. if (safe != nullptr)
  169. safe->mixer.getStripsForSnapshot().setShowLoudness (on);
  170. };
  171. mixeroptions::renderTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks,
  172. std::function<void (const std::vector<juce::File>&)> done) {
  173. if (safe != nullptr)
  174. showExportDialogForTracks (safe->engine, safe->currentFile.getParentDirectory(), safe->projectName, tracks, std::move (done));
  175. };
  176. if (persistent)
  177. {
  178. engine.getRollingLog().setEnabled (true); // on by default, as in FL (Tools › Audio logger)
  179. loadUiSettings();
  180. // the start-up song follows Options › Mixer too (round 163) and the automatic crossfades of new projects (166e)
  181. engine.setSong (makeNewProject());
  182. skin::onStyleSettingsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // an editor's own style was picked
  183. if (safe != nullptr) safe->saveUiSettings();
  184. };
  185. messages::onChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // "Remember my choice" / Manage messages
  186. if (safe != nullptr) safe->saveUiSettings();
  187. };
  188. loadKeyMap();
  189. startSession();
  190. if (BrowserComponent::sampleBrowserWasOpen()) // it was open when LYNX closed (round 163)
  191. juce::Timer::callAfterDelay (800, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  192. if (safe != nullptr && findToolWindow ("sampleBrowser") == nullptr)
  193. safe->openSampleBrowser();
  194. });
  195. EditorGlobals::get().onOptionsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // Follow on/off
  196. if (safe != nullptr) safe->saveUiSettings();
  197. };
  198. }
  199. PianoRollComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  200. PlaylistComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  201. pianoRoll.onNoteNamesChanged = [this] { saveUiSettings(); };
  202. // FL's EEPlayBtnClick (FLEngine 0xe4bd40, REA round 169f): Pattern mode first (also while the song plays), then the
  203. // play / pause of the transport. EEPlayBtnMouseDown (0xe4bda0), right button: FL's Stop (FUN_011ca520 (0, 0), the very
  204. // call of the toolbar's StopBtnClick), which in FL goes back to where playback started, pressed again to the start
  205. // (measured in FL 2026, round 169f, Pattern mode after a ruler click)
  206. pianoRoll.onPlayPause = [this] {
  207. if (engine.getSong().mode != PlayMode::pattern)
  208. toggleMode();
  209. playPause();
  210. };
  211. pianoRoll.onPlayRightClick = [this] {
  212. const auto playing = engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn();
  213. const auto target = transportedit::rollPlayRightClickTarget (playing, engine.getTransport().positionTicks.load(), playStartTicks);
  214. engine.stop();
  215. if (target > 0)
  216. engine.seek (target);
  217. else
  218. engine.rewind();
  219. playStartTicks = target;
  220. };
  221. pianoRoll.onBrowseScores = [this] { // (round 168g: the Piano roll's File › Browse scores)
  222. showPanel (Panel::browser);
  223. browser.showScores();
  224. };
  225. EventEditorHooks::onBrowseAutomations = [this] { // (the Event editor's File › Browse automations: FL's Scores\\Automation)
  226. showPanel (Panel::browser);
  227. browser.showScores ("Automation");
  228. };
  229. newButton.setTooltip (tr ("New project") + " (Ctrl+N)");
  230. newButton.onClick = [this] { newProject(); };
  231. openButton.setTooltip (tr ("Open project") + " (Ctrl+O)");
  232. openButton.onClick = [this] { chooseFileToOpen(); };
  233. saveButton.setTooltip (tr ("Save project") + " (Ctrl+S)");
  234. saveButton.onClick = [this] { save (false); };
  235. exportButton.setTooltip (tr ("Export audio: WAV, FLAC or OGG") + " (Ctrl+R)");
  236. exportButton.onClick = [this] { exportAudio(); };
  237. auto withKey = [this] (const juce::String& text, const char* id) {
  238. const auto key = shortcutText (id).trim();
  239. return key.isEmpty() ? text : text + " (" + key + ")";
  240. };
  241. undoButton.setTooltip (withKey (tr ("Undo"), "edit.undo"));
  242. undoButton.onClick = [this] { flUndo(); }; // FL's toolbar Undo is its Edit › Undo (UndoAction)
  243. undoButton.onRightClick = [this] { showHistory(); };
  244. redoButton.setTooltip (withKey (tr ("Redo"), "edit.redo"));
  245. redoButton.onClick = [this] { undoRedo (true); };
  246. redoButton.onRightClick = [this] { showHistory(); };
  247. // FL's toolbar picker button (round 171c): a click opens the Plugin picker (F8); a right-click LYNX's quick-add palette
  248. 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)"),
  249. "view.pluginPicker"));
  250. pluginPickerButton.onClick = [this] { togglePluginPicker(); };
  251. pluginPickerButton.onRightClick = [this] { showQuickAdd(); };
  252. // transport: Play toggles play / stop-and-back; Stop returns to the start; double-click Stop = all notes off
  253. playButton.setTooltip (tr ("Play; pressed again, stops and goes back to where it started") + " (Space; Ctrl+Space pauses)");
  254. playButton.onClick = [this] { playStop(); };
  255. stopButton.setTooltip (tr ("Stop and return to the start (double-click: back to the start and all notes off)"));
  256. stopButton.onClick = [this] { stopAndRewind(); };
  257. stopButton.onDoubleClick = [this] { // FL-like: a double Stop goes back to the very start (and silences hanging notes)
  258. engine.panic();
  259. stopAndRewind (true);
  260. };
  261. stopButton.onRightClick = [this] { showStopMenu(); };
  262. output.onModeChanged = [this] { saveUiSettings(); };
  263. recordButton.setOnColour (theme::colour::record);
  264. recordButton.setIconColour (theme::colour::record.withMultipliedSaturation (0.8f));
  265. recordButton.onClick = [this] { toggleRecording(); };
  266. recordMenuButton.setTooltip (tr ("Recording options: what to record"));
  267. recordMenuButton.onClick = [this] { showRecordMenu(); };
  268. recordButton.onRightClick = [this] { showRecordMenu(); };
  269. // Pattern / Song: a two-segment switch (L toggles); right-click shows the matching panel
  270. // as in FL, a two-line switch in front of the transport buttons: pattern on top, song below
  271. patternModeButton.setText (tr ("Pattern"));
  272. songModeButton.setText (tr ("Song"));
  273. for (auto* b : { &patternModeButton, &songModeButton })
  274. {
  275. b->setOnColour (theme::colour::bg6);
  276. b->setIconColourWhenOn (theme::colour::textPrimary);
  277. }
  278. patternModeButton.setTooltip (tr ("Pattern mode: plays the current pattern in a loop") + " (L)\n" + tr ("Right-click: show the Channel Rack"));
  279. songModeButton.setTooltip (tr ("Song mode: plays the Playlist arrangement") + " (L)\n" + tr ("Right-click: show the Playlist"));
  280. patternModeButton.onClick = [this] {
  281. if (engine.getSong().mode != PlayMode::pattern)
  282. toggleMode();
  283. };
  284. songModeButton.onClick = [this] {
  285. if (engine.getSong().mode != PlayMode::song)
  286. toggleMode();
  287. };
  288. patternModeButton.onRightClick = [this] { showPanel (Panel::channelRack); };
  289. songModeButton.onRightClick = [this] { showPanel (Panel::playlist); };
  290. metronomeButton.setClickingTogglesState (true);
  291. metronomeButton.setOnColour (theme::colour::bg6);
  292. metronomeButton.setIconColourWhenOn (theme::colour::accent);
  293. metronomeButton.setTooltip (tr ("Metronome"));
  294. metronomeButton.onClick = [this] { engine.getTransport().metronome.store (metronomeButton.getToggleState()); };
  295. midiLight.onReconnect = [this] {
  296. engine.reconnectMidiInputs();
  297. midiInputTicks = 0; // shows the reopened inputs at the next tick
  298. };
  299. metronomeButton.onRightClick = [this] { showMetronomeMenu(); };
  300. // FL's MultiLinkBtn (round 177b-4): lit while "Multilink to controllers" is on; [RMB] FL's MultilinkMenu
  301. multilinkButton.setFlat (true);
  302. multilinkButton.setWantsKeyboardFocus (false);
  303. multilinkButton.onClick = [this] { runAction ("options.multilink"); };
  304. multilinkButton.onRightClick = [this] {
  305. juce::PopupMenu menu;
  306. menu.addItem (tr ("Link to controller"), engine.isMultilinkOn(), false, [this] { engine.multilinkToControllers (false); });
  307. menu.addItem (tr ("Override global links"), engine.isMultilinkOn(), false, [this] { engine.multilinkToControllers (true); });
  308. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&multilinkButton));
  309. };
  310. typingPianoButton.setOnColour (theme::colour::bg6);
  311. typingPianoButton.setIconColourWhenOn (theme::colour::accent);
  312. typingPianoButton.onClick = [this] { toggleTypingPiano(); };
  313. typingPianoButton.onRightClick = [this] { showTypingPianoMenu(); };
  314. // count-in and wait-for-input switches next to the metronome, as in FL's recording panel
  315. for (auto* b : { &countInButton, &waitInputButton })
  316. {
  317. b->setOnColour (theme::colour::bg6);
  318. b->setIconColourWhenOn (theme::colour::accent);
  319. }
  320. countInButton.onClick = [this] { runAction ("record.countIn"); };
  321. waitInputButton.onClick = [this] { runAction ("record.waitForInput"); };
  322. // round 170e2: FL's "Blend recorded notes" switch (on = overdub, off = replace) and its tempo tapper button
  323. blendButton.setOnColour (theme::colour::bg6);
  324. blendButton.setIconColourWhenOn (theme::colour::accent);
  325. blendButton.onClick = [this] { runAction ("record.blend"); };
  326. tapTempoButton.onClick = [this] { openTempoTapper (engine); };
  327. // round 170e3: loop record, step edit and punch in/out as switches beside them
  328. for (auto* b : { &loopRecordButton, &stepEditButton, &punchButton })
  329. {
  330. b->setOnColour (theme::colour::bg6);
  331. b->setIconColourWhenOn (theme::colour::accent);
  332. }
  333. loopRecordButton.onClick = [this] { runAction ("record.loop"); };
  334. stepEditButton.onClick = [this] { runAction ("record.stepEdit"); };
  335. punchButton.onClick = [this] { runAction ("record.punch"); };
  336. for (int i = 0; i < workspace::panelCount; ++i)
  337. {
  338. const auto panel = (Panel) i;
  339. auto& b = panelButtons[(std::size_t) i];
  340. b.setFlat (true);
  341. b.setOnColour (theme::colour::bg5);
  342. b.setIconColourWhenOn (theme::colour::textPrimary);
  343. b.setTooltip (panelName (panel) + " (" + keys::displayString (keyMap.chordsFor (panelAction (panel)).empty() ? keys::Chord {}
  344. : keyMap.chordsFor (panelAction (panel)).front()) + ")\n"
  345. + tr ("Click: show, focus or hide. Right-click: show maximized"));
  346. b.onClick = [this, panel] { togglePanel (panel); };
  347. b.onRightClick = [this, panel] {
  348. showPanel (panel);
  349. if (! workspace.isMaximised (panel) && ! workspace.isDetached (panel))
  350. workspace.toggleMaximised (panel);
  351. refreshPanelButtons();
  352. };
  353. }
  354. patternBox.setTooltip (tr ("Current pattern (Numpad +/-: next/previous, F4: next empty, F2: rename)"));
  355. patternBox.onStep = [this] (int delta) { stepPatternFromSelector (delta); };
  356. gridBox.setScrollWheelEnabled (true);
  357. patternBox.onChange = [this]
  358. {
  359. const auto index = patternBox.getSelectedItemIndex();
  360. if (index >= 0 && index != engine.getSong().currentPattern)
  361. selectPattern (index);
  362. };
  363. newPatternButton.setTooltip (tr ("New pattern"));
  364. newPatternButton.onClick = [this]
  365. {
  366. engine.editSong ([] (Song& s) {
  367. Pattern p;
  368. p.name = newPatternName (s);
  369. s.patterns.push_back (std::move (p));
  370. s.currentPattern = (int) s.patterns.size() - 1;
  371. });
  372. };
  373. swingSlider.setRange (0.0, 1.0, 0.01);
  374. swingSlider.setDoubleClickReturnValue (true, 0.0);
  375. swingSlider.setValue (engine.getSong().swing, juce::dontSendNotification);
  376. swingSlider.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  377. swingSlider.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  378. swingSlider.onValueChange = [this] { engine.editSong ([v = (float) swingSlider.getValue()] (Song& s) { s.swing = v; }); };
  379. swingSlider.setTooltip (tr ("Swing of the Channel Rack (all channels)"));
  380. swingSlider.setMouseClickGrabsKeyboardFocus (false);
  381. swingSlider.setWantsKeyboardFocus (false);
  382. patternMenuButton.setTooltip (tr ("Pattern: rename, color, clone, insert, split, length, delete"));
  383. patternMenuButton.onClick = [this] { showPatternMenu(); };
  384. // the workspace panels
  385. rack.onOpenPianoRoll = [this] { openPianoRoll(); };
  386. mixerinput::openAudioSettings = [this] { openSettings ((int) SettingsPage::audio); };
  387. PatcherWindows::onBrowsePluginDatabase = [this] (bool) {
  388. showPanel (Panel::browser);
  389. browser.showPluginDatabaseForSnapshot(); // (its Generators and Effects folders open)
  390. if (auto* w = getTopLevelComponent())
  391. w->toFront (true);
  392. };
  393. rack.onOpenMixerInsert = [this] (int insert) { // double-click on a channel's route box
  394. showPanel (Panel::mixer);
  395. mixer.selectTrack (insert);
  396. };
  397. openMixerInsertHandler() = rack.onOpenMixerInsert; // and on the channel window's TRACK box (round 168s)
  398. mixer.onInstrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); };
  399. rackViewport.setViewedComponent (&rack, false);
  400. rackViewport.setScrollBarsShown (true, true);
  401. workspace.setContent (Panel::playlist, playlistArea, "Playlist", Icon::playlist);
  402. workspace.setContent (Panel::channelRack, rackViewport, "Channel Rack", Icon::channelRack);
  403. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll);
  404. workspace.setContent (Panel::mixer, mixer, "Mixer", Icon::mixer);
  405. workspace.setContent (Panel::browser, browser, "Browser", Icon::browser);
  406. workspace.setTitleTooltip (Panel::channelRack, tr ("Shift+wheel here changes the pattern"));
  407. // FL keeps the channel filter, the global swing and the graph editor switch in the rack's title bar
  408. rackFilterBox.text = rack.filterName();
  409. rackFilterBox.onClick = [this] { rack.showFilterMenu (&rackFilterBox); };
  410. rack.onFilterChanged = [this] {
  411. rackFilterBox.text = rack.filterName();
  412. rackFilterBox.repaint();
  413. rackGraphButton.setToggleState (rack.areGraphLanesShown(), juce::dontSendNotification);
  414. rackPianoRollButton.setToggleState (rack.isPianoRollView(), juce::dontSendNotification);
  415. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  416. };
  417. rackGraphButton.setClickingTogglesState (false);
  418. rackGraphButton.onClick = [this] { rack.toggleGraphLanes(); };
  419. // the step sequencer / piano-roll view switch (FL keeps it in the rack's title bar too)
  420. rackPianoRollButton.setClickingTogglesState (false);
  421. rackPianoRollButton.setOnColour (theme::colour::bg6);
  422. rackPianoRollButton.setIconColourWhenOn (theme::colour::accent);
  423. rackPianoRollButton.onClick = [this] { runAction ("rack.pianoRollView"); };
  424. ui::setHint (rackPianoRollButton, tr ("Piano-roll view: every channel shows its notes as a miniature piano roll (click one to edit it) "
  425. "instead of the step buttons; click again for the steps"));
  426. rackTitleTools.addAndMakeVisible (rackPianoRollButton);
  427. // Follow (issue #12): a long pattern pages along with the playing step
  428. rackFollowButton.setClickingTogglesState (false);
  429. rackFollowButton.setOnColour (theme::colour::bg6);
  430. rackFollowButton.setIconColourWhenOn (theme::colour::accent);
  431. rackFollowButton.setWantsKeyboardFocus (false);
  432. rackFollowButton.setMouseClickGrabsKeyboardFocus (false);
  433. rackFollowButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  434. rackFollowButton.setTooltip (tr ("Follow: a pattern longer than the Channel Rack pages along with the playing step; off, it stays where you scrolled"));
  435. ui::setQuickTip (rackFollowButton, tr ("Follow the playhead"));
  436. rackFollowButton.onClick = [this] { runAction ("rack.follow"); };
  437. rackTitleTools.addAndMakeVisible (rackFollowButton);
  438. // FL's Loop button (round 165f-rack): click switches the pattern's channel looping, right-click its loop type and burns
  439. rackLoopButton.setClickingTogglesState (false);
  440. rackLoopButton.setOnColour (theme::colour::bg6);
  441. rackLoopButton.setIconColourWhenOn (theme::colour::accent);
  442. rackLoopButton.onClick = [this] { rack.toggleLooping(); };
  443. rackLoopButton.onRightClick = [this] { rack.showLoopMenu (&rackLoopButton); };
  444. ui::setHint (rackLoopButton, tr ("Channel looping: channels shorter than the pattern repeat to its end (polyrhythms) [LMB] on / off "
  445. "[RMB] loop type (step channels, all channels, advanced) and Burn to pattern"));
  446. rackTitleTools.addAndMakeVisible (rackLoopButton);
  447. // Loop Starter (round 168b; FL 25's dice in the Channel Rack): a drum loop of the genre's kit, re-rolled with dice
  448. rackLoopStarterButton.setWantsKeyboardFocus (false);
  449. rackLoopStarterButton.onClick = [this] { loopstarterui::open (engine); };
  450. 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"));
  451. rackTitleTools.addAndMakeVisible (rackLoopStarterButton);
  452. // the pattern selector (issue #9): change the pattern the rack edits right from its title bar
  453. rackPatternSelector.onStep = [this] (int delta) { stepPatternFromSelector (delta); };
  454. rackPatternSelector.onMenu = [this] { showRackPatternList(); };
  455. 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"));
  456. rackTitleTools.addAndMakeVisible (rackPatternSelector);
  457. rackTitleTools.addAndMakeVisible (rackFilterBox);
  458. rackTitleTools.addAndMakeVisible (swingSlider);
  459. // the pattern length in bars (issue #12)
  460. rackLengthBox.onSet = [this] (int bars) {
  461. const auto index = engine.getSong().currentPattern;
  462. const auto ticks = (std::int64_t) juce::jlimit (0, 999, bars) * ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  463. if (index >= 0 && index < (int) engine.getSong().patterns.size() && engine.getSong().patterns[(std::size_t) index].lengthTicks != ticks)
  464. engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; });
  465. refreshRackLengthBox();
  466. };
  467. rackLengthBox.onMenu = [this] { showPatternLengthMenu(); };
  468. ui::setHint (rackLengthBox, tr ("Pattern length in bars: [LMB] drag or [Wheel] change it [2xLMB] automatic (from the notes) [RMB] menu"));
  469. ui::setQuickTip (rackLengthBox, tr ("Pattern length (bars)"));
  470. rackTitleTools.addAndMakeVisible (rackLengthBox);
  471. rackTitleTools.addAndMakeVisible (rackGraphButton);
  472. rackTitleTools.layout = [this] {
  473. auto r = rackTitleTools.getLocalBounds();
  474. rackPatternSelector.setBounds (r.removeFromLeft (rackPatternSelectorWidth).reduced (0, 3));
  475. r.removeFromLeft (6);
  476. rackFilterBox.setBounds (r.removeFromLeft (rackFilterBoxWidth).reduced (0, 3));
  477. r.removeFromLeft (4);
  478. swingSlider.setBounds (r.removeFromLeft (26));
  479. r.removeFromLeft (4);
  480. rackLengthBox.setBounds (r.removeFromLeft (rackLengthBoxWidth).reduced (0, 3));
  481. r.removeFromLeft (4);
  482. rackGraphButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  483. r.removeFromLeft (4);
  484. rackPianoRollButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  485. r.removeFromLeft (4);
  486. rackFollowButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  487. r.removeFromLeft (4);
  488. rackLoopButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  489. r.removeFromLeft (4);
  490. rackLoopStarterButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  491. };
  492. workspace.setTitleAccessory (Panel::channelRack, &rackTitleTools, rackTitleToolsWidth);
  493. workspace.setTitleAccessory (Panel::mixer, &mixer.getLayoutBox(), MixerLayoutBox::width); // FL's "Mixer layout" (issue #52)
  494. mixer.getStripsForSnapshot().onLayoutChanged = [this] {
  495. mixer.getLayoutBox().repaint();
  496. mixer.selectTrack (mixer.getStripsForSnapshot().getSelectedTrack()); // keep the selected strip in view
  497. saveUiSettings();
  498. };
  499. workspace.onPanelMenu = [this] (Panel panel, juce::PopupMenu& menu) { addPanelMenuItems (panel, menu); };
  500. workspace.onFocusChanged = [this] (Panel panel) {
  501. refreshPanelButtons();
  502. // another panel took over (a click, F5..F9): the Browser's search box gives the keys back (issue #9)
  503. if (panel != Panel::browser)
  504. browser.leaveSearchBox();
  505. };
  506. workspace.onKeyInDetachedWindow = [this] (const juce::KeyPress& key) { return keyPressed (key); };
  507. PluginWindows::setDockWorkspace (&workspace); // FL's docked plugin windows float there (issue #116, developer switch)
  508. workspace.onTitleWheel = [this] (Panel panel, const juce::MouseEvent& ev, const juce::MouseWheelDetails& wheel) {
  509. if (panel == Panel::channelRack && ev.mods.isShiftDown())
  510. selectPattern (stepPattern (engine.getSong(), (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1));
  511. };
  512. workspace.onTitleRightClick = [this] (Panel panel, const juce::MouseEvent&) {
  513. if (panel == Panel::channelRack)
  514. showPatternMenu();
  515. };
  516. workspace.onDefaultLayout = [this] { fitChannelRack (true); };
  517. workspace.setPersistent (persistent);
  518. playlist.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  519. playlist.onOpenPianoRoll = [this] {
  520. // edit a channel that plays in this pattern
  521. const auto& song = engine.getSong();
  522. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  523. const auto channel = engine.getSelectedChannel();
  524. if (! notes.empty() && std::none_of (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }))
  525. engine.setSelectedChannel (notes.front().channel);
  526. openPianoRoll();
  527. };
  528. picker.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  529. picker.onPatternMenu = [this] { makePatternMenu (picker.pickedPatterns()).showMenuAsync (juce::PopupMenu::Options().withMousePosition()); };
  530. picker.onNewPattern = [this] { newPatternButton.onClick(); };
  531. playlist.onRenamePattern = [this] (int p) { showRenamePattern (p); };
  532. playlist.onViewOptionChanged = [this] { saveUiSettings(); };
  533. playlist.onOpenInSampler = [this] (int channel) {
  534. // the audio clip's file in a new Sampler channel (to play it from notes), its settings open
  535. const auto& song = engine.getSong();
  536. if (channel < 0 || channel >= (int) song.channels.size())
  537. return;
  538. ChannelDef c;
  539. c.name = song.channels[(std::size_t) channel].name;
  540. c.instrument = InstrumentKind::sampler;
  541. c.samplePath = song.channels[(std::size_t) channel].samplePath;
  542. c.colour = song.channels[(std::size_t) channel].colour;
  543. const auto added = rack.addChannel (c, false);
  544. showPanel (Panel::channelRack);
  545. rack.toggleEditor (added, false);
  546. };
  547. ui::setHint (pianoRoll, tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  548. ui::setHint (playlist, tr ("Playlist: [LMB] paint the current pattern [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  549. // recent files (stored in %APPDATA%\LYNX)
  550. recent.setMaxNumberOfItems (12);
  551. recent.restoreFromString (PluginHost::settingsFolder().getChildFile ("recentes.txt").loadFileAsString());
  552. addAndMakeVisible (menuBar);
  553. for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  554. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  555. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton, &tempoDisplay, &patternBox, &newPatternButton, &patternMenuButton, &pluginPickerButton, &timeDisplay,
  556. &songPosition, &masterVolume, &masterPitch, &perfMeter, &chordPanel, &keyPanel, &output, &hintBar, &tweakReadout, &workspace, &midiLight,
  557. &multilinkButton })
  558. {
  559. addAndMakeVisible (c);
  560. c->setMouseClickGrabsKeyboardFocus (false); // the PC keyboard stays with the main window
  561. }
  562. // the dancers of the project's dance channels (FL's Fruity Dance) over the workspace (round 165e)
  563. danceStage = std::make_unique<DanceStage> (engine);
  564. danceStage->setMouseClickGrabsKeyboardFocus (false);
  565. addAndMakeVisible (*danceStage);
  566. for (auto& b : panelButtons)
  567. {
  568. addAndMakeVisible (b);
  569. b.setMouseClickGrabsKeyboardFocus (false);
  570. b.setWantsKeyboardFocus (false);
  571. }
  572. for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  573. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  574. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton, &newPatternButton, &patternMenuButton, &pluginPickerButton })
  575. b->setWantsKeyboardFocus (false);
  576. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton, &patternMenuButton,
  577. &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton })
  578. b->setFlat (true);
  579. // a light header: every toolbar button is flat; "on" is a faint wash, in the accent for the states that
  580. // matter while working (playing, recording, metronome, recording options)
  581. {
  582. using namespace theme;
  583. const auto onWash = colour::accent.withAlpha (0.24f), onIcon = colour::accentHover; // (round 170e3: a clearer "on")
  584. for (auto* b : { &playButton, &stopButton, &recordButton, &patternModeButton, &songModeButton })
  585. b->setFlat (true);
  586. playButton.setOnColour (onWash);
  587. playButton.setIconColourWhenOn (onIcon);
  588. recordButton.setOnColour (colour::record.withAlpha (0.2f));
  589. recordButton.setIconColourWhenOn (colour::record);
  590. for (auto* b : { &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton, &stepEditButton, &punchButton,
  591. &patternModeButton, &songModeButton, &multilinkButton })
  592. {
  593. b->setOnColour (onWash);
  594. b->setIconColourWhenOn (onIcon);
  595. }
  596. for (auto& b : panelButtons)
  597. {
  598. b.setOnColour (colour::textPrimary.withAlpha (0.08f));
  599. b.setIconColourWhenOn (colour::textPrimary);
  600. }
  601. }
  602. quickTips = std::make_unique<ui::QuickTipWindow>();
  603. ui::installSliderContract();
  604. // FL's Last tweaked and automation recording (REA round 143): every automatable control reports its moves
  605. ui::onTweak = [this] (const AutomationTarget& t) { engine.noteTweaked (t); };
  606. // Options › Theme › Startup sound: its Play button (issue #12)
  607. themeui::previewStartupSound = [this] (const juce::String& path) {
  608. std::shared_ptr<const SampleData> sound;
  609. if (path.isNotEmpty() && juce::File (path).existsAsFile())
  610. sound = engine.getSampleLibrary().load (path);
  611. engine.previewSample (sound != nullptr ? sound : makeStartupSample());
  612. };
  613. // the toolbar's last-tweaked read-out opens the parameter's own menu (FL's Tools › Last tweaked; round 162d)
  614. tweakReadout.onClick = [this] {
  615. makeLastTweakedMenu (0).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&tweakReadout));
  616. };
  617. // FL's "Edit events in piano roll" (REA round 146): the channel's own parameter selects its channel
  618. onEditEventsInPianoRoll = [this] (const AutomationTarget& t) {
  619. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  620. || t.kind == AutomationTargetKind::channelParam;
  621. if (onChannel && t.index >= 0 && t.index < (int) engine.getSong().channels.size())
  622. engine.setSelectedChannel (t.index);
  623. openPianoRoll();
  624. pianoRoll.showEventLane (t);
  625. };
  626. PluginWindows::onGesture = [this] (const juce::AudioPluginInstance& plugin, int param, bool starting) {
  627. if (const auto t = engine.targetOfPlugin (plugin, param))
  628. {
  629. if (starting)
  630. engine.noteTweaked (*t, true);
  631. else
  632. engine.tweakReleased (*t);
  633. }
  634. };
  635. engine.nameAutomation = [this] (const AutomationTarget& t) { return describeAutomationTarget (engine, t).toStdString(); };
  636. #if JUCE_PLUGINHOST_VST3
  637. // round 177b: a right-click on a VST3 plugin's knob (when the plugin asks the host for the parameter's menu) offers
  638. // LYNX's parameter items first: Create automation clip, Edit events, Link to MIDI / internal controller...
  639. vst3MenuEngine() = &engine;
  640. juce::lynxVst3ParamMenuHook = [] (juce::AudioPluginInstance& plugin, int param, juce::PopupMenu& menu) {
  641. if (auto* e = vst3MenuEngine())
  642. if (const auto t = e->targetOfPlugin (plugin, param))
  643. {
  644. menu.addSectionHeader ("LYNX SHARE - " + describeAutomationTarget (*e, *t));
  645. addAutomationItem (menu, *e, *t, true);
  646. }
  647. };
  648. #endif
  649. addAndMakeVisible (gridBox); // global grid (editors)
  650. snapToggleButton.setFlat (true);
  651. snapToggleButton.setOnColour (juce::Colours::transparentBlack);
  652. snapToggleButton.setIconColourWhenOn (theme::colour::accent);
  653. snapToggleButton.setWantsKeyboardFocus (false);
  654. snapToggleButton.setMouseClickGrabsKeyboardFocus (false);
  655. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  656. snapToggleButton.onClick = [this] {
  657. EditorGlobals::get().toggleGrid();
  658. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  659. };
  660. addAndMakeVisible (snapToggleButton);
  661. engine.addChangeListener (this);
  662. // MIDI controller profiles (round 190aw): LYNX as the controllers see it
  663. controllerBridge = std::make_unique<ControllerBridge> (engine, ControllerBridge::Window {
  664. [this] (const std::string& action) { return runAction (action); },
  665. [this] { return mixer.getSelectedTrack(); },
  666. [this] (int track) { mixer.selectTrack (track); } });
  667. engine.setControllerSurface (controllerBridge.get());
  668. setTypingPiano (typingPiano);
  669. refreshRecordOptionButtons();
  670. refreshToolbar();
  671. refreshPanelButtons();
  672. setToolbarLayout (toolbarLayout, false); // icon sizes and row height (loaded with the UI options)
  673. if (persistent && toolbarLayout.uiScale != 100)
  674. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  675. addChildComponent (chordNearHint);
  676. chordPanel.onMenu = [this] { showChordPanelMenu(); };
  677. keyPanel.onClick = [this] { showKeyMenu(); };
  678. refreshKeyPanel();
  679. PianoRollComponent::onSelectedKeys = [this] (const std::vector<int>& keys) {
  680. if (! chordPanel.isVisible())
  681. return;
  682. refreshChordOptions();
  683. chordReadout.selection (keys, juce::Time::getMillisecondCounter());
  684. auto text = juce::String::fromUTF8 (chordReadout.text().c_str());
  685. chordPanel.setText (chordReadout.lastWasNovelty() ? tr (text) : text);
  686. };
  687. setControlHints();
  688. fittedChannelCount = (int) engine.getSong().channels.size();
  689. hintBar.setHint ({ idleHint(), {}, false, false });
  690. setWantsKeyboardFocus (true);
  691. installDialogTextFocus(); // dialogs open with their text field focused (round 165q)
  692. setSize (1180, 642);
  693. startTimerHz (30);
  694. uiTraceMonitor.start ([this, last = std::make_shared<RtStats::Snapshot>()] {
  695. // the audio side of the second (the watchdog thread: atomics only)
  696. const auto rt = engine.getRtStats().snapshot();
  697. const auto calls = rt.callbacks - last->callbacks;
  698. juce::String text;
  699. text << "audio: callbacks " << juce::String ((juce::int64) calls) << ", over deadline " << juce::String ((juce::int64) (rt.overBudget - last->overBudget))
  700. << ", late " << juce::String ((juce::int64) (rt.lateCalls - last->lateCalls)) << ", max load since start " << juce::String (rt.maxLoad * 100.0, 0)
  701. << "%, cpu " << juce::String (engine.getDeviceManager().getCpuUsage() * 100.0, 1) << "%";
  702. *last = rt;
  703. return text;
  704. });
  705. // new or updated plugins since the last run: an incremental scan in the background (unchanged files are
  706. // skipped), a few seconds after start so it doesn't compete with loading; the first run asks in the wizard
  707. if (persistent && setupWizardDone() && backgroundScanAtStart() && platform::testMode())
  708. platform::testModeLog ("background plugin scan at start");
  709. else if (persistent && setupWizardDone() && backgroundScanAtStart())
  710. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  711. if (safe != nullptr)
  712. safe->engine.getPluginHost().startBackgroundScan();
  713. });
  714. // round 168t (the YouTube review, 168d #9: "How do we get back to the playlist? Where is the playlist?"): the first
  715. // three starts name the window buttons and their keys in the hint bar for a while
  716. if (persistent)
  717. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  718. if (safe != nullptr)
  719. safe->showWindowsTip();
  720. });
  721. // Online Sessions P2 (round 169b): live sessions
  722. live = std::make_unique<LiveSessionManager> (engine);
  723. liveui::attach (*live);
  724. liveui::setRemoteSession (live.get(), &engine); // (P5-A1: the shared plugins in the menus, the guest's editor)
  725. live->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  726. if (safe != nullptr)
  727. {
  728. safe->repaint (safe->titleArea);
  729. safe->menuItemsChanged();
  730. safe->updateTitle(); // (the session's state is in the window title too: narrow layouts hide the badge)
  731. }
  732. };
  733. live->onJoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  734. if (safe == nullptr)
  735. return;
  736. const auto* host = song.session.find (session::hostTag);
  737. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  738. safe->startNewProject (std::move (song), {});
  739. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  740. safe->updateTitle();
  741. };
  742. // round 169j: the host's LYNX SHARE restarted during a session: its journal's song becomes the open project again
  743. live->onResumed = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  744. if (safe == nullptr)
  745. return;
  746. const auto journal = LiveSessionManager::readJournal (LiveSessionManager::defaultJournal());
  747. safe->startNewProject (std::move (song), {});
  748. if (journal && journal->projectFile.existsAsFile())
  749. {
  750. safe->currentFile = journal->projectFile;
  751. safe->projectName = journal->projectFile.getFileNameWithoutExtension();
  752. }
  753. safe->updateTitle();
  754. };
  755. // round 190ah: a guest's LYNX SHARE restarted during a session: the project it had is open again
  756. live->onRejoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  757. if (safe == nullptr)
  758. return;
  759. const auto* host = song.session.find (session::hostTag);
  760. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  761. safe->startNewProject (std::move (song), {});
  762. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  763. safe->updateTitle();
  764. };
  765. engine.onSessionUndoSkipped = [] (const juce::StringArray& skipped) {
  766. ui::postHint ({ tr ("Undo left alone what someone else changed since: {0}", { skipped.joinIntoString (", ") }), {} }, 4000);
  767. };
  768. if (startStyle.style != layoutstyle::Style::pattern)
  769. setLayoutStyle (startStyle.style, false); // (the saved workspace layout is already this style's)
  770. updateGamepad(); // (round 184a, S16: only when the option is on)
  771. juce::Timer::callAfterDelay (1500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  772. if (safe != nullptr)
  773. safe->startLiveFromCommandLine();
  774. });
  775. // the keys a secondary window (tool, plugin, channel window) leaves unused run the global shortcuts, as in FL
  776. // FL's Auto select linked modules [DECOMP FUN_00f5c340] (round 187a): a focused channel / plugin window selects its
  777. // channel and that channel's mixer track; a mixer effect's window selects its track
  778. setLinkedWindowFocusHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (int channel, int insert) {
  779. if (safe == nullptr || ! ChannelRackComponent::autoSelectLinked)
  780. return;
  781. const auto& song = safe->engine.getSong();
  782. if (channel >= 0 && channel < (int) song.channels.size())
  783. {
  784. if (safe->engine.getSelectedChannel() != channel || safe->engine.getSelectedChannels().size() != 1)
  785. safe->engine.setSelectedChannel (channel);
  786. insert = song.channels[(std::size_t) channel].mixerTrack;
  787. }
  788. if (insert >= 0 && insert < (int) song.mixer.size())
  789. safe->mixer.selectTrack (insert);
  790. });
  791. setSecondaryWindowKeyHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  792. return safe != nullptr && safe->keyFromSecondaryWindow (key);
  793. });
  794. // 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
  795. setPluginViewPlainKeyHandler ([] (juce::Component& window) { return PluginWindows::letsHostProcessKeys (window); },
  796. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  797. return safe != nullptr && safe->keyFromPluginView (key, true);
  798. },
  799. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  800. return safe != nullptr && safe->keyFromPluginView (key, false);
  801. });
  802. }
  803. MainComponent::~MainComponent()
  804. {
  805. engine.setControllerSurface (nullptr); // (the controllers get their closing messages)
  806. gamepadInput.reset();
  807. if (detailView != nullptr) // (round 183a: a docked Piano roll goes home while the workspace still exists)
  808. detailView->releaseEditor();
  809. juce::Desktop::getInstance().removeGlobalMouseListener (&dockClickWatcher);
  810. workspace.onWillShow = nullptr;
  811. engine.onSessionUndoSkipped = nullptr;
  812. PianoRollComponent::onSelectedKeys = nullptr;
  813. liveui::closeChat();
  814. liveui::setRemoteSession (nullptr, nullptr);
  815. live.reset(); // (a session still on ends: the others are told)
  816. setPluginViewPlainKeyHandler (nullptr, nullptr, nullptr);
  817. setSecondaryWindowKeyHandler (nullptr);
  818. setLinkedWindowFocusHandler (nullptr);
  819. cancelProjectLoad(); // an open in progress uses the engine from its thread
  820. if (sessionLock != nullptr) // a clean exit: no "LYNX did not close properly" next time
  821. sessionMarker.deleteFile();
  822. mixerinput::openAudioSettings = nullptr;
  823. openMixerInsertHandler() = nullptr;
  824. PatcherWindows::onBrowsePluginDatabase = nullptr;
  825. EditorGlobals::get().onOptionsChanged = nullptr;
  826. PianoRollComponent::shortcutText = nullptr;
  827. PlaylistComponent::shortcutText = nullptr;
  828. saveUiSettings();
  829. workspace.saveState();
  830. ui::uninstallSliderContract();
  831. ui::onTweak = nullptr;
  832. themeui::previewStartupSound = nullptr;
  833. onEditEventsInPianoRoll = nullptr;
  834. PluginWindows::onGesture = nullptr;
  835. #if JUCE_PLUGINHOST_VST3
  836. juce::lynxVst3ParamMenuHook = nullptr;
  837. vst3MenuEngine() = nullptr;
  838. #endif
  839. removeDialogTextFocus();
  840. engine.nameAutomation = nullptr;
  841. PluginWindows::closeAll(); // plugin UIs before the engine
  842. PluginWindows::setDockWorkspace (nullptr); // (issue #116: the docked ones were in the workspace)
  843. ParametricEqWindows::closeAll();
  844. closeAutomationEditors();
  845. closeChannelSettings();
  846. closeAllToolWindows(); // note tools, history, quick-add (they edit the song)
  847. engine.removeChangeListener (this);
  848. stopTimer();
  849. }
  850. void MainComponent::paint (juce::Graphics& g)
  851. {
  852. const uitrace::Scope trace ("MainComponent paint", true, g.getClipBounds());
  853. using namespace theme;
  854. g.fillAll (colour::bg1);
  855. // the toolbar: one band, its panels separated by hairlines
  856. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  857. g.setColour (colour::bg3);
  858. g.fillRect (bar);
  859. g.setColour (colour::border);
  860. g.fillRect (bar.withHeight (1).withY (bar.getBottom() - 1));
  861. // round 170e3: each panel sits in its own quiet well (transport, master, recording, snap and pattern, windows,
  862. // file, meters), so the groups read at a glance; with "Separators" off, only hairlines between them
  863. if (toolbarLayout.separators) // (the toolbar menu's "Separators")
  864. {
  865. for (const auto& r : panelBounds)
  866. if (! r.isEmpty())
  867. {
  868. const auto well = r.toFloat().reduced (1.0f, 2.0f);
  869. g.setColour (colour::bg1.withAlpha (0.55f));
  870. g.fillRoundedRectangle (well, radius::lg);
  871. g.setColour (colour::border);
  872. g.drawRoundedRectangle (well.reduced (0.5f), radius::lg, 1.0f);
  873. }
  874. }
  875. else
  876. {
  877. g.setColour (colour::border.brighter (0.08f));
  878. for (auto x : dividers)
  879. g.fillRect (x, bar.getY() + 12, 1, bar.getHeight() - 24);
  880. }
  881. // Pattern / Song: one switch of two halves (round 170e3), the playing mode lit
  882. if (! modeArea.isEmpty())
  883. {
  884. g.setColour (colour::bg2);
  885. g.fillRoundedRectangle (modeArea.toFloat(), radius::lg);
  886. g.setColour (colour::borderStrong);
  887. g.drawRoundedRectangle (modeArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  888. }
  889. // play, stop and record share one quiet well
  890. if (! transportArea.isEmpty())
  891. {
  892. g.setColour (colour::bg2);
  893. g.fillRoundedRectangle (transportArea.toFloat(), radius::lg);
  894. g.setColour (colour::border);
  895. g.drawRoundedRectangle (transportArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  896. }
  897. // the hint bar sits in an inset well under the menu
  898. if (! hintBar.getBounds().isEmpty())
  899. {
  900. g.setColour (colour::bg1);
  901. g.fillRoundedRectangle (hintBar.getBounds().toFloat(), radius::md);
  902. }
  903. // the project name, beside the menus (FL's title/hint panel: the title above the hint bar)
  904. if (! titleArea.isEmpty())
  905. {
  906. // the people of a live session first (round 169b), the project's name after them
  907. const auto people = live != nullptr ? liveui::paintPresence (g, titleArea, *live) : 0;
  908. const auto name = projectName.isNotEmpty() ? projectName : tr ("Untitled");
  909. g.setFont (font (type::small, true));
  910. g.setColour (colour::textSecondary);
  911. if (const auto rest = titleArea.withTrimmedLeft (people > 0 ? people + 10 : 0); rest.getWidth() >= 50)
  912. g.drawFittedText ((engine.isModified() ? juce::String ("* ") : juce::String()) + name
  913. + (engine.pluginsOff() ? " " + tr ("(third-party plugins off)") : juce::String()), // round 190ap
  914. rest, juce::Justification::centredRight, 1, 0.8f);
  915. }
  916. // captions that name the snap and pattern selectors, after their icons (the magnet is a button)
  917. g.setFont (font (type::caption - 1.0f, true));
  918. g.setColour (colour::textDisabled);
  919. if (! snapLabelArea.isEmpty())
  920. if (snapLabelArea.getWidth() > rowHeight + 20) // (the narrowest toolbar keeps only the magnet)
  921. g.drawText (tr ("SNAP"), snapLabelArea.withTrimmedLeft (rowHeight + 1), juce::Justification::centredLeft, true);
  922. if (! patternLabelArea.isEmpty())
  923. {
  924. const auto iconBox = patternLabelArea.withWidth (rowHeight).toFloat();
  925. icons::draw (g, Icon::pattern, iconBox.withSizeKeepingCentre (14.0f, 14.0f), colour::textDisabled);
  926. if (patternLabelArea.getWidth() > rowHeight + 20)
  927. g.drawText (tr ("PATTERN"), patternLabelArea.withTrimmedLeft (rowHeight + 1), juce::Justification::centredLeft, true);
  928. }
  929. }
  930. void MainComponent::resized()
  931. {
  932. using toolbarlayout::Group;
  933. if (const auto size = toolbarlayout::effectiveIconSize (toolbarLayout.iconSize, getWidth()); size != appliedIconSize)
  934. applyIconSizing (size);
  935. dividers.clear();
  936. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  937. auto toolbar = bar.reduced (8, toolbarLayout.visible ? 5 : 3);
  938. const auto row1 = toolbar.getY(), row2 = toolbar.getY() + rowHeight + 2, h = rowHeight;
  939. auto big = h + 14; // transport buttons: big, centred on both rows (round 170e3)
  940. auto bigWidth = h + 14;
  941. int gap = 17; // a divider and the space around it (13 when compact)
  942. const auto grow = h - toolbarlayout::rowHeight (toolbarlayout::IconSize::medium); // wider panels for bigger rows
  943. // panel widths
  944. auto& lf = getLookAndFeel();
  945. auto measureMenu = [&] {
  946. int w = 0;
  947. for (const auto& name : getMenuBarNames())
  948. w += lf.getMenuBarItemWidth (menuBar, 0, name);
  949. return w;
  950. };
  951. menuBar.getProperties().set ("lynxTightMenuBar", false);
  952. int menuWidth = measureMenu();
  953. if (menuWidth > 390) // translated menu titles (German, Russian...): English stays as it was
  954. {
  955. menuBar.getProperties().set ("lynxTightMenuBar", true);
  956. menuWidth = measureMenu();
  957. }
  958. const auto modeWidth = juce::jmax (patternModeButton.getIdealWidth (h - 2), songModeButton.getIdealWidth (h - 2));
  959. int tempoWidth = 96 + grow, timeWidth = 140 + grow;
  960. const int gridWidth = 148;
  961. // the snap and pattern captions: an icon (the magnet button / the pattern icon) and the longer of the two names
  962. const juce::Font captionFont (theme::font (theme::type::caption - 1.0f, true));
  963. int captionWidth = h + 3 + juce::jlimit (30, 80, juce::roundToInt (juce::jmax (juce::GlyphArrangement::getStringWidth (captionFont, tr ("SNAP")),
  964. juce::GlyphArrangement::getStringWidth (captionFont, tr ("PATTERN"))))) + 6;
  965. std::array<int, toolbarlayout::groupCount> widths {};
  966. const int tapWidth = juce::roundToInt (h * 0.8f); // the tempo tapper, right of the tempo (round 170e3)
  967. widths[(std::size_t) Group::transport] = modeWidth + 8 + 3 * (bigWidth + 4) + 4 + tempoWidth + 2 + tapWidth + 4 + timeWidth;
  968. widths[(std::size_t) Group::master] = 2 * (h + 26) + 4; // two big knobs side by side (round 170e3)
  969. widths[(std::size_t) Group::record] = 5 * h + 8; // five per row (round 170e3)
  970. widths[(std::size_t) Group::snap] = captionWidth + gridWidth;
  971. widths[(std::size_t) Group::windows] = 3 * h + 4;
  972. widths[(std::size_t) Group::file] = 3 * h + 4;
  973. widths[(std::size_t) Group::meters] = 118;
  974. widths[(std::size_t) Group::output] = 116 + grow * 2;
  975. widths[(std::size_t) Group::chord] = 96; // (FL's panel: 96 px)
  976. widths[(std::size_t) Group::multilink] = h; // one button (FL's MultiLinkBtn)
  977. widths[(std::size_t) Group::key] = 112; // "Key" over "C# harmonic minor" (round 184a S11; the name shrinks to fit)
  978. const auto room = toolbar.getWidth();
  979. // room for most hints on two lines; on a very wide window the hint bar takes more (round 170e3)
  980. auto minHint = juce::jmax (menuWidth + 8, 320);
  981. const auto maxHint = room >= 3000 ? 1000 : 620;
  982. auto visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  983. // round 181b: the Chord detection panel is on the default toolbar, as in FL. At 1920 px it misses by about 90 px:
  984. // tighter displays and gaps make the room (they get wider again when there is more); all the panels stay
  985. if (toolbarLayout.visible && toolbarLayout.isShown (Group::chord) && ! visible[(std::size_t) Group::chord] && visible[(std::size_t) Group::record])
  986. {
  987. auto tighter = widths;
  988. tighter[(std::size_t) Group::transport] -= 12 + 36; // the tempo and the song position, as narrow as the compact ones
  989. tighter[(std::size_t) Group::snap] -= 16;
  990. tighter[(std::size_t) Group::chord] = 88;
  991. if (const auto fits = toolbarlayout::fit (toolbarLayout, tighter, 13, room, minHint); fits[(std::size_t) Group::chord])
  992. {
  993. widths = tighter;
  994. tempoWidth -= 12;
  995. timeWidth -= 36;
  996. gap = 13;
  997. visible = fits;
  998. }
  999. }
  1000. // round 170e3: rather than dropping the recording switches on a narrow window (1280-1440 px), the panels get
  1001. // tighter: four switches per row (the typing piano and the MIDI light go; Ctrl+T and the View menu keep the piano),
  1002. // a narrower snap box and displays
  1003. compactRecord = false;
  1004. narrowSnap = false;
  1005. if (toolbarLayout.visible && toolbarLayout.isShown (Group::record) && ! visible[(std::size_t) Group::record])
  1006. {
  1007. compactRecord = true;
  1008. const auto before = 3 * (bigWidth + 4) + tempoWidth + timeWidth;
  1009. big = h + 6;
  1010. bigWidth = h + 4;
  1011. tempoWidth = 84 + grow;
  1012. timeWidth = 104 + grow;
  1013. widths[(std::size_t) Group::transport] -= before - (3 * (bigWidth + 4) + tempoWidth + timeWidth);
  1014. widths[(std::size_t) Group::master] = 92; // the knobs over each other, as before
  1015. widths[(std::size_t) Group::record] = 4 * h + 6;
  1016. widths[(std::size_t) Group::snap] -= 16;
  1017. gap = 13;
  1018. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1019. // round 170e5: still too narrow (1280 px): the snap and pattern captions keep only their icons, the hint
  1020. // column only the menu's width, tighter displays and gaps; the recording switches stay
  1021. if (! visible[(std::size_t) Group::record])
  1022. {
  1023. const auto icons = h + 4;
  1024. widths[(std::size_t) Group::snap] -= captionWidth - icons;
  1025. captionWidth = icons;
  1026. tempoWidth -= 6;
  1027. timeWidth -= 8;
  1028. widths[(std::size_t) Group::transport] -= 14;
  1029. minHint = menuWidth + 8;
  1030. gap = 11;
  1031. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1032. }
  1033. // and still (1280 px, measured: the switches missed it by a few px): a narrower snap box, tight gaps; then
  1034. // the window buttons go before the recording switches (F5-F9 and the View menu open the same windows)
  1035. if (! visible[(std::size_t) Group::record])
  1036. {
  1037. widths[(std::size_t) Group::snap] -= 24;
  1038. narrowSnap = true;
  1039. gap = 8;
  1040. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1041. }
  1042. if (! visible[(std::size_t) Group::record])
  1043. {
  1044. auto narrow = toolbarLayout;
  1045. for (auto& e : narrow.entries)
  1046. if (e.group == Group::windows)
  1047. e.shown = false;
  1048. visible = toolbarlayout::fit (narrow, widths, gap, room, minHint);
  1049. }
  1050. }
  1051. if (! toolbarLayout.visible) // Ctrl+F11: only the menu and the hint bar, on one row
  1052. visible.fill (false);
  1053. panelBounds = {};
  1054. int used = 0;
  1055. for (int i = 0; i < toolbarlayout::groupCount; ++i)
  1056. used += visible[(std::size_t) i] ? widths[(std::size_t) i] + gap : 0;
  1057. auto hintWidth = juce::jlimit (juce::jmin (minHint, juce::jmax (160, room - used)), maxHint, room - used);
  1058. // round 170e3: the spare room goes to useful things first (a wider output monitor, snap and pattern boxes, song
  1059. // position and hint bar), then a little air between the panels, so no dead zone opens anywhere on a wide window
  1060. auto spare = juce::jmax (0, room - used - hintWidth);
  1061. auto grant = [&spare] (int share, int most) {
  1062. const auto g = juce::jmax (0, juce::jmin (most, spare * share / 100));
  1063. spare -= g;
  1064. return g;
  1065. };
  1066. if (visible[(std::size_t) Group::output])
  1067. widths[(std::size_t) Group::output] += grant (40, 900);
  1068. if (visible[(std::size_t) Group::snap])
  1069. widths[(std::size_t) Group::snap] += grant (20, 220);
  1070. if (const auto more = grant (15, 120); more > 0)
  1071. {
  1072. timeWidth += more;
  1073. widths[(std::size_t) Group::transport] += more;
  1074. }
  1075. hintWidth += grant (25, 500);
  1076. const auto shownGroups = (int) std::count (visible.begin(), visible.end(), true);
  1077. // at most twice the normal gap between the panels; what is still left goes to the output monitor and the hint bar
  1078. const auto extra = toolbarlayout::extraGap (spare, shownGroups, gap);
  1079. spare -= extra * shownGroups;
  1080. if (spare > 0)
  1081. {
  1082. const auto toOutput = visible[(std::size_t) Group::output] ? spare / 2 : 0;
  1083. widths[(std::size_t) Group::output] += toOutput;
  1084. hintWidth += spare - toOutput;
  1085. spare = 0;
  1086. }
  1087. auto take = [&toolbar] (int width) { return toolbar.removeFromLeft (juce::jmin (width, toolbar.getWidth())); };
  1088. auto divide = [&] {
  1089. take (gap / 2 + extra / 2);
  1090. dividers.push_back (toolbar.getX());
  1091. take (gap - gap / 2 + extra - extra / 2);
  1092. };
  1093. auto hide = [] (std::initializer_list<juce::Component*> components) {
  1094. for (auto* c : components)
  1095. {
  1096. c->setVisible (false);
  1097. c->setBounds ({});
  1098. }
  1099. };
  1100. auto put = [] (juce::Component& c, juce::Rectangle<int> r) {
  1101. c.setVisible (true);
  1102. c.setBounds (r);
  1103. };
  1104. // a block of icon buttons, three per row on both rows
  1105. auto grid = [&] (juce::Rectangle<int> panel, std::initializer_list<juce::Component*> buttons, int columns = 3) {
  1106. int i = 0;
  1107. for (auto* b : buttons)
  1108. {
  1109. const auto x = panel.getX() + (i % columns) * (h + 2);
  1110. put (*b, juce::Rectangle<int> (x, i < columns ? row1 : row2, h, h));
  1111. ++i;
  1112. }
  1113. };
  1114. // 1. the menu (and the project name beside it) over the hint bar; always first
  1115. if (! toolbarLayout.visible)
  1116. {
  1117. const auto row = toolbar.withHeight (h);
  1118. const auto menu = row.withWidth (juce::jmin (menuWidth + 8, row.getWidth()));
  1119. put (menuBar, menu);
  1120. titleArea = {};
  1121. placeHintBar (row.withTrimmedLeft (menu.getWidth() + 12).withWidth (juce::jmin (900, row.getWidth() - menu.getWidth() - 12)).reduced (0, 1));
  1122. fixedToolbarArea = bar;
  1123. }
  1124. else
  1125. {
  1126. auto column = take (hintWidth);
  1127. const auto menu = column.withY (row1).withHeight (h).removeFromLeft (juce::jmin (menuWidth + 8, column.getWidth()));
  1128. put (menuBar, menu);
  1129. titleArea = column.withY (row1).withHeight (h).withTrimmedLeft (menu.getWidth() + 12).withTrimmedRight (4);
  1130. if (titleArea.getWidth() < 60)
  1131. titleArea = {};
  1132. placeHintBar (column.withY (row2).withHeight (h).reduced (0, 1));
  1133. fixedToolbarArea = juce::Rectangle<int> (column.getX() - 4, 0, column.getWidth() + 8, toolbarHeight);
  1134. }
  1135. snapLabelArea = patternLabelArea = transportArea = modeArea = {};
  1136. for (const auto& entry : toolbarLayout.entries)
  1137. {
  1138. const auto group = entry.group;
  1139. if (! visible[(std::size_t) group])
  1140. {
  1141. switch (group)
  1142. {
  1143. case Group::transport:
  1144. hide ({ &patternModeButton, &songModeButton, &playButton, &stopButton, &recordButton, &tempoDisplay, &tapTempoButton, &timeDisplay, &songPosition });
  1145. break;
  1146. case Group::master: hide ({ &masterVolume, &masterPitch }); break;
  1147. case Group::record: hide ({ &metronomeButton, &typingPianoButton, &recordMenuButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton, &stepEditButton, &punchButton, &midiLight }); break;
  1148. case Group::snap: hide ({ &gridBox, &snapToggleButton, &patternBox, &newPatternButton, &patternMenuButton }); break;
  1149. case Group::windows:
  1150. for (auto& b : panelButtons)
  1151. hide ({ &b });
  1152. hide ({ &pluginPickerButton });
  1153. break;
  1154. case Group::file: hide ({ &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton }); break;
  1155. case Group::meters: hide ({ &perfMeter }); break;
  1156. case Group::output: hide ({ &output }); break;
  1157. case Group::chord: hide ({ &chordPanel }); break;
  1158. case Group::multilink: hide ({ &multilinkButton }); break;
  1159. case Group::key: hide ({ &keyPanel }); break;
  1160. case Group::count_: break;
  1161. }
  1162. continue;
  1163. }
  1164. if (toolbarlayout::rightAligned (group) && spare > 0)
  1165. {
  1166. take (spare);
  1167. spare = 0;
  1168. }
  1169. divide();
  1170. auto panel = take (widths[(std::size_t) group]);
  1171. panelBounds[(std::size_t) group] = juce::Rectangle<int> (panel.getX() - 5, 0, panel.getWidth() + 10, toolbarHeight);
  1172. switch (group)
  1173. {
  1174. case Group::transport: // Pattern/Song switch, play, stop, record, tempo, time display with the song position under it
  1175. {
  1176. auto mode = panel.removeFromLeft (modeWidth);
  1177. modeArea = mode.withY (row1).withHeight (2 * h + 2).expanded (3, 2);
  1178. put (patternModeButton, mode.withY (row1).withHeight (h).reduced (0, 1));
  1179. put (songModeButton, mode.withY (row2).withHeight (h).reduced (0, 1));
  1180. panel.removeFromLeft (8);
  1181. const auto y = panel.getCentreY() - big / 2;
  1182. transportArea = juce::Rectangle<int> (panel.getX(), y, 3 * bigWidth + 2 * 4, big);
  1183. for (auto* b : { &playButton, &stopButton, &recordButton })
  1184. {
  1185. put (*b, juce::Rectangle<int> (panel.getX(), y, bigWidth, big).reduced (0, 3));
  1186. panel.removeFromLeft (bigWidth + 4);
  1187. }
  1188. panel.removeFromLeft (4);
  1189. const auto displays = juce::Rectangle<int> (panel.getX(), row1 + 3, panel.getWidth(), 2 * h - 6);
  1190. const auto displayHeight = displays.getHeight() - 10;
  1191. put (tempoDisplay, displays.withWidth (tempoWidth).withHeight (displayHeight));
  1192. put (tapTempoButton, displays.withTrimmedLeft (tempoWidth + 2).withWidth (tapWidth).withHeight (displayHeight));
  1193. put (timeDisplay, displays.withTrimmedLeft (tempoWidth + 2 + tapWidth + 4).withWidth (timeWidth).withHeight (displayHeight));
  1194. put (songPosition, displays.withTop (displays.getY() + displayHeight + 1).withWidth (tempoWidth + 2 + tapWidth + 4 + timeWidth));
  1195. break;
  1196. }
  1197. case Group::master: // master volume beside master pitch, each a big knob with its name and value under it
  1198. {
  1199. if (compactRecord)
  1200. {
  1201. put (masterVolume, panel.withY (row1).withHeight (h).reduced (0, 1));
  1202. put (masterPitch, panel.withY (row2).withHeight (h).reduced (0, 1));
  1203. break;
  1204. }
  1205. const auto both = panel.withY (row1).withHeight (2 * h + 2);
  1206. put (masterVolume, both.withWidth (both.getWidth() / 2 - 2));
  1207. put (masterPitch, both.withTrimmedLeft (both.getWidth() / 2 + 2));
  1208. break;
  1209. }
  1210. case Group::record: // the recording switches (round 170e3, as FL's recording panel): metronome, wait for input, count-in,
  1211. // blend and the typing piano over loop record, step edit, punch, the recording options menu and the MIDI light
  1212. if (compactRecord)
  1213. {
  1214. hide ({ &typingPianoButton, &midiLight });
  1215. grid (panel, { &metronomeButton, &waitInputButton, &countInButton, &blendButton,
  1216. &loopRecordButton, &stepEditButton, &punchButton, &recordMenuButton }, 4);
  1217. }
  1218. else
  1219. grid (panel, { &metronomeButton, &waitInputButton, &countInButton, &blendButton, &typingPianoButton,
  1220. &loopRecordButton, &stepEditButton, &punchButton, &recordMenuButton, &midiLight }, 5);
  1221. break;
  1222. case Group::snap: // global snap over the pattern selector, each with its name
  1223. {
  1224. auto first = juce::Rectangle<int> (panel.getX(), row1, panel.getWidth(), h);
  1225. snapLabelArea = first.removeFromLeft (captionWidth);
  1226. put (snapToggleButton, snapLabelArea.withWidth (h));
  1227. put (gridBox, first.reduced (0, 1));
  1228. auto second = juce::Rectangle<int> (panel.getX(), row2, panel.getWidth(), h);
  1229. patternLabelArea = second.removeFromLeft (captionWidth);
  1230. put (patternMenuButton, second.removeFromRight (h));
  1231. if (narrowSnap) // (the pattern box keeps room for a name)
  1232. {
  1233. put (newPatternButton, patternLabelArea.withWidth (h));
  1234. patternLabelArea = {};
  1235. }
  1236. else
  1237. {
  1238. put (newPatternButton, second.removeFromRight (h));
  1239. second.removeFromRight (2);
  1240. }
  1241. put (patternBox, second.reduced (0, 1));
  1242. break;
  1243. }
  1244. case Group::windows: // the windows and the plugin picker
  1245. grid (panel, { &panelButtons[(std::size_t) Panel::playlist], &panelButtons[(std::size_t) Panel::channelRack],
  1246. &panelButtons[(std::size_t) Panel::pianoRoll], &panelButtons[(std::size_t) Panel::mixer],
  1247. &panelButtons[(std::size_t) Panel::browser], &pluginPickerButton });
  1248. break;
  1249. case Group::file: // new, open, save over export, undo, redo
  1250. grid (panel, { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton });
  1251. break;
  1252. case Group::meters: put (perfMeter, panel.withY (row1).withHeight (2 * h + 2)); break;
  1253. case Group::output: put (output, panel.withY (row1).withHeight (2 * h + 2)); break;
  1254. case Group::chord: put (chordPanel, panel.withY (row1).withHeight (2 * h + 2)); break;
  1255. case Group::multilink: put (multilinkButton, panel.withY (row1).withHeight (h)); break;
  1256. case Group::key: put (keyPanel, panel.withY (row1).withHeight (2 * h + 2)); break;
  1257. case Group::count_: break;
  1258. }
  1259. }
  1260. // the toolbar's edit mode: its overlay over the toolbar, and its tray between the toolbar and the windows
  1261. const auto tray = toolbarEditor != nullptr ? toolbar::EditOverlay::trayHeight : 0;
  1262. if (toolbarEditor != nullptr)
  1263. {
  1264. toolbarEditor->setBounds (0, 0, getWidth(), toolbarHeight + tray);
  1265. toolbarEditor->setToolbarHeight (toolbarHeight);
  1266. toolbarEditor->toFront (false);
  1267. }
  1268. auto below = getLocalBounds().withTrimmedTop (toolbarHeight + tray);
  1269. if (updateBar.isVisible())
  1270. updateBar.setBounds (below.removeFromTop (updater::UpdateBar::height));
  1271. workspace.setBounds (below);
  1272. if (danceStage != nullptr)
  1273. {
  1274. danceStage->setBounds (getLocalBounds());
  1275. danceStage->toFront (false);
  1276. }
  1277. if (setupOverlay != nullptr)
  1278. {
  1279. hostSetupOverlayNatively();
  1280. nativechild::place (*setupOverlay, *this, getLocalBounds());
  1281. setupOverlay->toFront (false);
  1282. }
  1283. }
  1284. void MainComponent::hostSetupOverlayNatively()
  1285. {
  1286. // issue #116: in front of the native panels and docked plugin windows too (a native child window of its own, showing
  1287. // what is under it); without a native window yet, a plain overlay until there is one
  1288. if (setupOverlay == nullptr || ! nativechild::dockingEnabled() || nativechild::isAttached (*setupOverlay) || getPeer() == nullptr)
  1289. return;
  1290. removeChildComponent (setupOverlay.get());
  1291. if (auto host = nativechild::makeOverlayHost (setupOverlay, *this))
  1292. {
  1293. nativechild::forwardUnusedKeys (*host);
  1294. setupOverlay = std::move (host);
  1295. return;
  1296. }
  1297. addAndMakeVisible (*setupOverlay);
  1298. }
  1299. // --- toolbar layout ------------------------------------------------------------------------------
  1300. // The toolbar's rows and icons, and the editors' tool strips, for one icon size (round 170e3: the size in effect can be
  1301. // one step above the chosen one on a very wide window, toolbarlayout::effectiveIconSize).
  1302. void MainComponent::applyIconSizing (toolbarlayout::IconSize size)
  1303. {
  1304. appliedIconSize = size;
  1305. rowHeight = toolbarlayout::rowHeight (size);
  1306. toolbarHeight = toolbarLayout.visible ? 2 * rowHeight + 12 : rowHeight + 6; // (round 170e3: room for the panel wells)
  1307. const auto fraction = toolbarlayout::iconFraction (size), maxPx = toolbarlayout::iconMaxPx (size);
  1308. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton,
  1309. &patternMenuButton, &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &snapToggleButton,
  1310. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton })
  1311. b->setIconSizing (fraction, maxPx);
  1312. for (auto& b : panelButtons)
  1313. b.setIconSizing (fraction, maxPx);
  1314. for (auto* b : { &playButton, &stopButton, &recordButton }) // solid transport glyphs on big buttons (round 170e3)
  1315. b->setIconSizing (0.42f, maxPx + 2.0f);
  1316. ToolStrip::iconSize = size;
  1317. pianoRoll.resized();
  1318. playlist.resized();
  1319. }
  1320. void MainComponent::setToolbarLayout (const toolbarlayout::Layout& layout, bool save)
  1321. {
  1322. const auto scaleChanged = layout.uiScale != toolbarLayout.uiScale;
  1323. if (save && layout.isShown (toolbarlayout::Group::key) != toolbarLayout.isShown (toolbarlayout::Group::key))
  1324. keyPanelFollowsStyle = false; // shown or hidden by hand (round 184a S11): the layout decides from now on
  1325. toolbarLayout = layout;
  1326. applyIconSizing (toolbarlayout::effectiveIconSize (toolbarLayout.iconSize, getWidth()));
  1327. if (save && scaleChanged)
  1328. {
  1329. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  1330. // the windows grow with the zoom: keep their title bars and close buttons on the screen (round 163)
  1331. juce::Timer::callAfterDelay (200, [] { fitAllWindowsOnScreen(); });
  1332. }
  1333. resized();
  1334. repaint();
  1335. if (toolbarEditor != nullptr)
  1336. toolbarEditor->layoutChanged();
  1337. if (save)
  1338. saveUiSettings();
  1339. }
  1340. juce::PopupMenu MainComponent::makeToolbarMenu()
  1341. {
  1342. using toolbarlayout::Group;
  1343. juce::PopupMenu menu;
  1344. // FL's toolbar menu (Edit, Separators, Hide, Presets), then LYNX's direct switches per panel
  1345. menu.addSectionHeader (tr ("Toolbar"));
  1346. menu.addItem (tr ("Edit toolbar (drag panels to move, add or remove them)"), true, toolbarEditor != nullptr,
  1347. [this] { setToolbarEditing (toolbarEditor == nullptr); });
  1348. menu.addItem (tr ("Separators"), true, toolbarLayout.separators, [this] {
  1349. auto layout = toolbarLayout;
  1350. layout.separators = ! layout.separators;
  1351. setToolbarLayout (layout);
  1352. });
  1353. menu.addItem (tr ("Hide the toolbar panels") + shortcutText ("view.toolbar"), true, ! toolbarLayout.visible, [this] {
  1354. auto layout = toolbarLayout;
  1355. layout.visible = ! layout.visible;
  1356. setToolbarLayout (layout);
  1357. });
  1358. juce::PopupMenu presets;
  1359. const auto current = toolbarlayout::matchingPreset (toolbarLayout);
  1360. for (int p = 0; p < toolbarlayout::presetCount; ++p)
  1361. presets.addItem (tr (toolbarlayout::presetName ((toolbarlayout::Preset) p)), true, current == p, [this, p] {
  1362. auto layout = toolbarlayout::applyPreset (toolbarLayout, (toolbarlayout::Preset) p);
  1363. layout.visible = true;
  1364. setToolbarLayout (layout);
  1365. });
  1366. menu.addSubMenu (tr ("Presets"), presets);
  1367. menu.addSectionHeader (tr ("Panels"));
  1368. for (const auto& entry : toolbarLayout.entries)
  1369. {
  1370. const auto group = entry.group;
  1371. menu.addItem (tr (toolbarlayout::groupName (group)), true, entry.shown, [this, group] {
  1372. auto layout = toolbarLayout;
  1373. layout.setShown (group, ! layout.isShown (group));
  1374. layout.visible = true;
  1375. setToolbarLayout (layout);
  1376. });
  1377. }
  1378. menu.addSeparator();
  1379. menu.addItem (tr ("Show detected MIDI chords near the hint bar"), true, chordShowNearHint, [this] {
  1380. chordShowNearHint = ! chordShowNearHint;
  1381. chordNearHint.setVisible (false);
  1382. saveUiSettings();
  1383. });
  1384. menu.addSeparator();
  1385. juce::PopupMenu sizes;
  1386. const char* sizeNames[] = { TR_NOOP ("Small icons"), TR_NOOP ("Medium icons"), TR_NOOP ("Large icons") };
  1387. for (int i = 0; i < 3; ++i)
  1388. sizes.addItem (tr (sizeNames[i]), true, (int) toolbarLayout.iconSize == i, [this, i] {
  1389. auto layout = toolbarLayout;
  1390. layout.iconSize = (toolbarlayout::IconSize) i;
  1391. setToolbarLayout (layout);
  1392. });
  1393. menu.addSubMenu (tr ("Icon size"), sizes);
  1394. juce::PopupMenu scales;
  1395. for (auto percent : toolbarlayout::uiScales)
  1396. scales.addItem (juce::String (percent) + "%", true, toolbarLayout.uiScale == percent, [this, percent] {
  1397. auto layout = toolbarLayout;
  1398. layout.uiScale = percent;
  1399. setToolbarLayout (layout);
  1400. });
  1401. menu.addSubMenu (tr ("UI scale"), scales);
  1402. menu.addSeparator();
  1403. menu.addItem (tr ("Customize toolbar..."), [this] { showCustomizeToolbar(); });
  1404. menu.addItem (tr ("Reset toolbar to default"), ! toolbarLayout.isDefault(), false, [this] {
  1405. setToolbarLayout (toolbarlayout::Layout::makeDefault());
  1406. });
  1407. return menu;
  1408. }
  1409. void MainComponent::setToolbarEditing (bool editing)
  1410. {
  1411. if (editing == (toolbarEditor != nullptr))
  1412. return;
  1413. if (! editing)
  1414. {
  1415. removeChildComponent (toolbarEditor.get());
  1416. toolbarEditor.reset();
  1417. resized();
  1418. repaint();
  1419. return;
  1420. }
  1421. if (! toolbarLayout.visible) // editing shows the panels
  1422. {
  1423. auto layout = toolbarLayout;
  1424. layout.visible = true;
  1425. setToolbarLayout (layout);
  1426. }
  1427. toolbar::EditOverlay::Host host;
  1428. host.layout = [this] { return toolbarLayout; };
  1429. host.setLayout = [this] (const toolbarlayout::Layout& layout) { setToolbarLayout (layout); };
  1430. host.panels = [this] { return panelBounds; };
  1431. host.fixedArea = [this] { return fixedToolbarArea; };
  1432. host.snapshot = [this] (juce::Rectangle<int> area) {
  1433. // the panel as it looks, without the edit overlay on it
  1434. if (toolbarEditor != nullptr)
  1435. toolbarEditor->setVisible (false);
  1436. auto image = createComponentSnapshot (area, true);
  1437. if (toolbarEditor != nullptr)
  1438. toolbarEditor->setVisible (true);
  1439. return image;
  1440. };
  1441. host.done = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  1442. // after the click that asked for it
  1443. juce::MessageManager::callAsync ([safe] {
  1444. if (safe != nullptr)
  1445. safe->setToolbarEditing (false);
  1446. });
  1447. };
  1448. toolbarEditor = std::make_unique<toolbar::EditOverlay> (std::move (host), toolbarHeight);
  1449. addAndMakeVisible (*toolbarEditor);
  1450. resized();
  1451. repaint();
  1452. if (isShowing())
  1453. toolbarEditor->grabKeyboardFocus();
  1454. }
  1455. void MainComponent::runUndoStep (undokeys::Step step)
  1456. {
  1457. if (step != undokeys::Step::none)
  1458. undoRedo (step == undokeys::Step::redo);
  1459. }
  1460. void MainComponent::flUndo()
  1461. {
  1462. // FL's default: undo, or redo when something is undone ("undo/redo on the same shortcut"); "Alternate undo mode":
  1463. // every press one more step back (core/UndoKeys.h)
  1464. runUndoStep (undokeys::undoKey (alternateUndo, engine.canUndo(), engine.canRedo()));
  1465. }
  1466. void MainComponent::flUndoBackwards()
  1467. {
  1468. // FL's Undo backwards: one more step back; "Alternate undo mode" swaps the two shortcuts, so there it is the
  1469. // undo/redo key (round 190b)
  1470. runUndoStep (undokeys::backwardsKey (alternateUndo, engine.canUndo(), engine.canRedo()));
  1471. }
  1472. void MainComponent::undoRedo (bool redo)
  1473. {
  1474. // FL says in the hint bar what was undone and the undo level ("Undone: ... Level 2/3")
  1475. if (redo ? ! engine.canRedo() : ! engine.canUndo())
  1476. return;
  1477. const auto label = engine.getHistoryLabel (engine.getHistoryPosition() + (redo ? 1 : 0));
  1478. if (redo)
  1479. engine.redo();
  1480. else
  1481. engine.undo();
  1482. ui::Hint h;
  1483. h.text = (redo ? tr ("Redone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) })
  1484. : tr ("Undone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) }));
  1485. h.value = tr ("Level {0}/{1}", { juce::String (engine.getHistoryPosition() + 1), juce::String (engine.getHistorySize()) });
  1486. ui::postHint (h, 2500);
  1487. }
  1488. ui::Hint MainComponent::hintAt (juce::Point<int> p)
  1489. {
  1490. ui::Hint h;
  1491. if (p.y < toolbarHeight)
  1492. {
  1493. h.text = tr ("Toolbar: [RMB] toolbar menu (edit the panels: move, add, remove; presets; hide with Ctrl+F11)");
  1494. h.hasMenu = true;
  1495. }
  1496. return h;
  1497. }
  1498. void MainComponent::showToolbarMenu()
  1499. {
  1500. makeToolbarMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1501. }
  1502. void MainComponent::showCustomizeToolbar()
  1503. {
  1504. auto panel = std::make_unique<toolbar::CustomizePanel> (toolbarLayout);
  1505. panel->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] (const toolbarlayout::Layout& layout) {
  1506. if (safe != nullptr)
  1507. safe->setToolbarLayout (layout);
  1508. };
  1509. juce::DialogWindow::LaunchOptions options;
  1510. options.content.setOwned (fitContentToScreen (std::move (panel)).release());
  1511. options.dialogTitle = tr ("Customize toolbar");
  1512. options.dialogBackgroundColour = theme::colour::bg2;
  1513. options.useNativeTitleBar = true;
  1514. options.resizable = false;
  1515. options.escapeKeyTriggersCloseButton = true;
  1516. if (auto* dialog = options.launchAsync())
  1517. keepAboveMainWindow (*dialog);
  1518. }
  1519. void MainComponent::mouseDown (const juce::MouseEvent& e)
  1520. {
  1521. // a right-click on the toolbar's background (between the panels): show / hide groups, icon size, customize
  1522. if (e.mods.isPopupMenu() && e.y < toolbarHeight)
  1523. showToolbarMenu();
  1524. }
  1525. juce::Rectangle<int> MainComponent::getToolStripAreaForSnapshot (bool playlistStrip)
  1526. {
  1527. auto& editor = playlistStrip ? (juce::Component&) playlist : (juce::Component&) pianoRoll;
  1528. if (! editor.isVisible() || editor.getParentComponent() == nullptr || ! isParentOf (&editor))
  1529. return {};
  1530. const auto area = getLocalArea (&editor, editor.getLocalBounds());
  1531. return area.withHeight (40).withWidth (juce::jmin (area.getWidth(), 900)).getIntersection (getLocalBounds());
  1532. }
  1533. // --- keys --------------------------------------------------------------------------------------
  1534. keys::Context MainComponent::focusContext() const
  1535. {
  1536. if (pianoRollKeysHere()) // (round 183a: docked in the Clip-launch workflow's detail view)
  1537. return keys::Context::pianoRoll;
  1538. switch (workspace.getFocused())
  1539. {
  1540. case Panel::playlist: return keys::Context::playlist;
  1541. case Panel::channelRack: return keys::Context::channelRack;
  1542. case Panel::pianoRoll: return keys::Context::pianoRoll;
  1543. case Panel::mixer: return keys::Context::mixer;
  1544. case Panel::browser: return keys::Context::browser;
  1545. }
  1546. return keys::Context::global;
  1547. }
  1548. void MainComponent::dragOperationStarted (const juce::DragAndDropTarget::SourceDetails&)
  1549. {
  1550. // a drop on a window above this one (the Sampler's waveform, a plugin...) lands there, not on the panel under it
  1551. matchWindowOrderToScreen();
  1552. }
  1553. bool MainComponent::keyPressed (const juce::KeyPress& key)
  1554. {
  1555. const auto chord = chordFromKeyPress (key);
  1556. // 1. the typing piano: the keys its layout takes (notes, FL's LOCK) win over the shortcuts; FL's FREE keys don't
  1557. const auto typed = typingKey (chord);
  1558. if (typed.taken)
  1559. {
  1560. const auto code = key.getKeyCode();
  1561. if (! heldKeys.hasTag (code) && typingLaunches.count (code) == 0) // key repeat: the notes are already sounding
  1562. {
  1563. // FL sends the typing keyboard's notes as MIDI channel 1 (FUN_011828c0 -> FUN_01181620 channel 0): with
  1564. // "MIDI channel used for playlist live mode" = 1 and Performance mode on, they launch the Playlist's clips
  1565. // (what "Layout Performance mode" is for), else they play the selected channels
  1566. if (engine.typingNotesLaunchClips())
  1567. {
  1568. for (auto note : typed.notes)
  1569. if (perf::Command c; typingPerformance.note (note, true, c))
  1570. engine.performanceCommand (c);
  1571. typingLaunches[code] = typed.notes;
  1572. }
  1573. else
  1574. for (auto c : engine.getSelectedChannels())
  1575. for (auto note : typed.notes) // (a chord layout's key plays several)
  1576. heldKeys.press (c, note, 0.8f, code);
  1577. }
  1578. return true;
  1579. }
  1580. const auto pianoKeys = typingPiano && ! isPlainKey (chord); // (a FREE plain key is a shortcut as with the piano off)
  1581. // 2. a key the user gave an action himself (Options › Shortcuts) wins over the panels' built-in keys
  1582. // (issue #12: Metronome on 'C' did nothing while the Playlist, whose Knife is 'C', had the focus)
  1583. if (const auto own = keyMap.findUserBound (chord, focusContext(), pianoKeys); ! own.empty() && runAction (own))
  1584. return true;
  1585. // 3. the focused panel's own keys
  1586. const auto focused = workspace.getFocused();
  1587. const auto panelShown = workspace.isPanelVisible (focused);
  1588. if (((panelShown && focused == Panel::pianoRoll) || pianoRollKeysHere()) && pianoRoll.handleKey (key))
  1589. return true;
  1590. if (panelShown && focused == Panel::playlist && ! pianoRollKeysHere() && playlist.handleKey (key))
  1591. return true;
  1592. // 4. the key map
  1593. const auto action = keyMap.find (chord, focusContext(), pianoKeys);
  1594. return ! action.empty() && runAction (action);
  1595. }
  1596. bool MainComponent::isPlainKey (const keys::Chord& chord) noexcept
  1597. {
  1598. return (chord.mods & (keys::ctrl | keys::alt | keys::shift)) == 0;
  1599. }
  1600. keys::TypingKey MainComponent::typingKey (const keys::Chord& chord) const
  1601. {
  1602. return typingPiano && isPlainKey (chord) ? keys::typingPianoKey (chord.key, typingOctave, typingRoot, typingLayout) : keys::TypingKey {};
  1603. }
  1604. void MainComponent::releaseTypingLaunches (bool all)
  1605. {
  1606. for (auto it = typingLaunches.begin(); it != typingLaunches.end();)
  1607. if (all || ! juce::KeyPress::isKeyCurrentlyDown (it->first))
  1608. {
  1609. for (auto note : it->second)
  1610. if (perf::Command c; typingPerformance.note (note, false, c))
  1611. engine.performanceCommand (c);
  1612. it = typingLaunches.erase (it);
  1613. }
  1614. else
  1615. ++it;
  1616. }
  1617. bool MainComponent::keyFromSecondaryWindow (const juce::KeyPress& key)
  1618. {
  1619. // (round 165q / issue #12) a text field keeps its typing keys; the rest runs the global actions
  1620. const auto typingIntoText = dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) != nullptr;
  1621. const auto chord = chordFromKeyPress (key);
  1622. // issue #117: the typing piano plays from Sytrus's window (any LYNX window) too; its release is polled (timer)
  1623. if (keys::KeyMap::secondaryWindowPlaysNote (typingKey (chord).taken, typingIntoText))
  1624. return keyPressed (key);
  1625. const auto action = keyMap.findFromSecondaryWindow (chord, typingIntoText, typingPiano && (! isPlainKey (chord) || typingKey (chord).taken));
  1626. return ! action.empty() && runAction (action);
  1627. }
  1628. bool MainComponent::keyFromPluginView (const juce::KeyPress& key, bool optionOn)
  1629. {
  1630. // the typing piano as over the main window (its release is polled, MainComponent::keyStateChanged). With the
  1631. // plugin's "Typing keyboard priority" off (LYNX first) the shortcuts run too; keys that do nothing here stay the plugin's.
  1632. if (typingKey (chordFromKeyPress (key)).taken)
  1633. return keyPressed (key);
  1634. return optionOn && keyFromSecondaryWindow (key);
  1635. }
  1636. bool MainComponent::runAction (const std::string& id)
  1637. {
  1638. auto is = [&id] (const char* name) { return id == name; };
  1639. if (id.rfind ("view.detail", 0) == 0) // round 183a: Clip-launch workflow only (false: the chord falls through as before)
  1640. return runDetailAction (id);
  1641. if (id == "rack.follow")
  1642. {
  1643. auto& g = EditorGlobals::get();
  1644. g.setFollowingView (EditorGlobals::FollowView::channelRack, ! g.isFollowingView (EditorGlobals::FollowView::channelRack));
  1645. rackFollowButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  1646. return true;
  1647. }
  1648. if (id.rfind ("pianoRoll.", 0) == 0 && pianoRoll.runKeyAction (id)) return true; // tools, slide, channel keys
  1649. if (id.rfind ("playlist.tool.", 0) == 0 && playlist.runKeyAction (id)) return true;
  1650. if (is ("transport.playStop")) playStop();
  1651. else if (is ("transport.pause")) playPause();
  1652. else if (is ("transport.playFromStart")) playFromStart();
  1653. else if (is ("transport.toggleMode")) toggleMode();
  1654. else if (is ("transport.nextMarker")) engine.jumpToNextMarker (true);
  1655. else if (is ("transport.previousMarker")) engine.jumpToNextMarker (false);
  1656. else if (is ("view.typingPiano")) toggleTypingPiano();
  1657. else if (is ("options.multilink")) engine.setMultilink (! engine.isMultilinkOn());
  1658. else if (is ("view.toolbar"))
  1659. {
  1660. auto layout = toolbarLayout;
  1661. layout.visible = ! layout.visible;
  1662. setToolbarLayout (layout);
  1663. }
  1664. else if (is ("panel.playlist")) togglePanel (Panel::playlist);
  1665. else if (is ("panel.channelRack")) togglePanel (Panel::channelRack);
  1666. else if (is ("panel.pianoRoll"))
  1667. {
  1668. togglePanel (Panel::pianoRoll);
  1669. if (workspace.isPanelVisible (Panel::pianoRoll))
  1670. pianoRoll.scrollToNotes();
  1671. }
  1672. else if (is ("panel.browser")) togglePanel (Panel::browser);
  1673. else if (is ("panel.mixer")) togglePanel (Panel::mixer);
  1674. else if (is ("panel.maximisePlaylist"))
  1675. {
  1676. workspace.toggleMaximised (Panel::playlist);
  1677. refreshPanelButtons();
  1678. }
  1679. else if (is ("pattern.next")) selectPattern (stepPattern (engine.getSong(), 1));
  1680. else if (is ("pattern.previous")) selectPattern (stepPattern (engine.getSong(), -1));
  1681. else if (is ("pattern.nextEmpty")) nextEmptyPattern();
  1682. else if (is ("pattern.firstEmpty")) { engine.editSong ([] (Song& s) { gotoFirstEmptyPattern (s); }); showRenamePattern (engine.getSong().currentPattern); }
  1683. else if (is ("pattern.nextEmptyNoName")) engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  1684. else if (is ("pattern.delete")) deleteCurrentPattern();
  1685. else if (is ("pattern.rename")) showRenamePattern (engine.getSong().currentPattern);
  1686. else if (is ("pattern.insert")) insertPatternHere();
  1687. else if (is ("pattern.clone")) clonePatternNow();
  1688. else if (is ("pattern.moveUp")) movePatternNow (-1);
  1689. else if (is ("pattern.moveDown")) movePatternNow (1);
  1690. else if (id.rfind ("pattern.select", 0) == 0) selectPattern (std::stoi (id.substr (14)) - 1);
  1691. else if (is ("view.pluginPicker")) togglePluginPicker();
  1692. else if (is ("panel.quickAdd"))
  1693. {
  1694. // FL's F8 opens the plugin picker or closes it (FLEngine 0xebf510, round 167o)
  1695. if (auto* open = findToolWindow ("quickadd"))
  1696. closeToolWindowOf (*open->getContentComponent());
  1697. else
  1698. showQuickAdd();
  1699. }
  1700. else if (is ("edit.history")) showHistory();
  1701. else if (is ("tools.stopSound")) engine.stopSound();
  1702. else if (is ("browser.search"))
  1703. {
  1704. showPanel (Panel::browser);
  1705. browser.focusSearch();
  1706. }
  1707. else if (is ("transport.record")) toggleRecording();
  1708. else if (is ("record.quickAudio")) quickRecordAudio();
  1709. else if (is ("transport.metronome"))
  1710. {
  1711. engine.getTransport().metronome.store (! engine.getTransport().metronome.load());
  1712. refreshModeButton();
  1713. }
  1714. else if (is ("record.countIn"))
  1715. {
  1716. auto o = engine.getRecordOptions();
  1717. o.countInBars = o.countInBars > 0 ? 0 : 1;
  1718. engine.setRecordOptions (o);
  1719. refreshRecordOptionButtons();
  1720. }
  1721. else if (is ("record.captureMidi")) // round 170d (Ableton's Capture MIDI, Logic's Capture as Recording)
  1722. {
  1723. const auto r = engine.captureMidi();
  1724. if (r.notes > 0)
  1725. ui::postHint ({ tr ("Capture MIDI: {0} notes put in the pattern", { juce::String (r.notes) }), {}, false, false }, 4000);
  1726. else
  1727. ui::postHint ({ tr ("Capture MIDI: nothing to capture (play some notes first, without recording)"), {}, false, false }, 4000);
  1728. }
  1729. else if (is ("record.waitForInput"))
  1730. {
  1731. auto o = engine.getRecordOptions();
  1732. o.waitForInput = ! o.waitForInput;
  1733. engine.setRecordOptions (o);
  1734. refreshRecordOptionButtons();
  1735. }
  1736. else if (is ("record.blend") || is ("record.loop") || is ("record.punch"))
  1737. {
  1738. auto o = engine.getRecordOptions();
  1739. if (is ("record.blend"))
  1740. o.mode = o.mode == RecordMode::overdub ? RecordMode::replace : RecordMode::overdub;
  1741. else if (is ("record.loop"))
  1742. o.loopRecord = ! o.loopRecord;
  1743. else
  1744. o.punchLoopRegion = ! o.punchLoopRegion;
  1745. engine.setRecordOptions (o);
  1746. refreshRecordOptionButtons();
  1747. saveUiSettings();
  1748. }
  1749. else if (is ("record.stepEdit"))
  1750. {
  1751. engine.setStepEdit (! engine.isStepEdit());
  1752. stepSeekTick = stepPrevTick = -1.0; // starts at the position shown now
  1753. refreshRecordOptionButtons();
  1754. }
  1755. else if (is ("rack.graphEditor")) rack.toggleGraphLanes();
  1756. else if (is ("rack.pianoRollView"))
  1757. {
  1758. rack.setPianoRollView (! rack.isPianoRollView());
  1759. saveUiSettings();
  1760. }
  1761. else if (is ("view.audioEditor")) openAudioEditorForSelection();
  1762. else if (is ("channel.soloSelected")) rack.solo (engine.getSelectedChannel());
  1763. else if (is ("automation.lastTweaked"))
  1764. {
  1765. // FL's Add › Automation for last tweaked parameter (round 143) from a key (round 190an): LYNX's own controls
  1766. // and a hosted plugin's parameters alike (AudioEngine::noteTweaked keeps the last moved one)
  1767. if (const auto t = engine.getLastTweaked (0))
  1768. createAutomationClip (engine, *t);
  1769. else
  1770. ui::postHint ({ tr ("Automation for last tweaked parameter"), tr ("Last tweaked: none") }, 3000);
  1771. }
  1772. else if (is ("view.tempoTapper")) openTempoTapper (engine);
  1773. else if (is ("view.sampleBrowser")) toggleSampleBrowser();
  1774. else if (is ("view.pluginDatabase"))
  1775. {
  1776. showPanel (Panel::browser);
  1777. browser.showPluginDatabase();
  1778. }
  1779. else if (is ("view.midiSettings") || is ("view.projectInfo"))
  1780. {
  1781. // FL's F10 / F11 (round 167o, issue #23): the same key closes Settings showing that page; on another page it
  1782. // switches in place
  1783. const auto page = is ("view.midiSettings") ? SettingsPage::midi : SettingsPage::info;
  1784. const auto shown = shownSettingsPage();
  1785. switch (keys::settingsKeyPress (shown >= 0, shown, (int) page))
  1786. {
  1787. case keys::SettingsKey::close: closeSettings(); break;
  1788. case keys::SettingsKey::switchPage: switchSettingsPage (page); break;
  1789. case keys::SettingsKey::open: openSettings ((int) page); break;
  1790. }
  1791. }
  1792. else if (is ("view.closeUnfocusedWindows")) closeUnfocusedWindows();
  1793. else if (is ("view.alignChannelEditors")) alignAllChannelEditors (engine.getSelectedChannel());
  1794. else if (is ("view.touchKeyboard")) toggleTouchKeyboard (engine);
  1795. else if (is ("view.closePluginWindows") || is ("view.closeWindows"))
  1796. {
  1797. PluginWindows::closeAll();
  1798. ParametricEqWindows::closeAll(); // every native effect / controller editor
  1799. if (is ("view.closeWindows")) // FL's F12: the editors and tool windows too (LYNX's docked panels stay)
  1800. {
  1801. closeAutomationEditors();
  1802. closeChannelSettings();
  1803. closeAllToolWindows();
  1804. closeHelp();
  1805. }
  1806. }
  1807. else if (is ("rack.groupSelected")) rack.groupSelected();
  1808. else if (is ("rack.rotateLeft")) rack.rotateSelected (-1);
  1809. else if (is ("rack.rotateRight")) rack.rotateSelected (1);
  1810. else if (is ("browser.previous")) browser.step (-1, false);
  1811. else if (is ("browser.next")) browser.step (1, false);
  1812. else if (is ("browser.swapPrevious")) browser.step (-1, true);
  1813. else if (is ("browser.swapNext")) browser.step (1, true);
  1814. else if (is ("browser.load")) browser.loadSelected();
  1815. else if (is ("browser.closeFolder")) browser.openFolder (false);
  1816. else if (is ("browser.openFolder")) browser.openFolder (true);
  1817. else if (is ("browser.rename"))
  1818. {
  1819. if (! browser.renameSelectedPlugin()) // not a plugin: F2's global action (rename the pattern)
  1820. showRenamePattern (engine.getSong().currentPattern);
  1821. }
  1822. else if (id.rfind ("pianoRoll.", 0) == 0) return pianoRoll.runAction (id);
  1823. else if (id.rfind ("playlist.", 0) == 0) return playlist.runAction (id);
  1824. else if (id.rfind ("mixer.", 0) == 0) return mixer.runAction (id);
  1825. else if (is ("file.new")) newProject();
  1826. else if (is ("file.open")) chooseFileToOpen();
  1827. else if (is ("file.save")) save (false);
  1828. else if (is ("file.saveAs")) save (true);
  1829. else if (is ("file.saveNewVersion")) saveNewVersion();
  1830. else if (is ("file.export")) exportAudio();
  1831. else if (is ("file.exportMaster")) showMasterDialog (engine, currentFile.getParentDirectory(), projectName);
  1832. else if (is ("file.exportMp3")) exportAudio (1);
  1833. else if (is ("file.exportMidi")) exportMidiFile();
  1834. else if (is ("tools.consolidateSelection")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), false);
  1835. else if (is ("tools.consolidateSelectionSongStart")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), true);
  1836. else if (is ("edit.undo")) flUndo();
  1837. else if (is ("edit.undoBackwards")) flUndoBackwards();
  1838. else if (is ("edit.redo")) undoRedo (true);
  1839. else if (is ("help.shortcuts"))
  1840. {
  1841. if (helpWindow != nullptr) // F1 again closes the sheet (issue #23)
  1842. closeHelp();
  1843. else
  1844. showHelp();
  1845. }
  1846. else if (is ("rack.selectPrevious")) rack.selectRelative (-1, false);
  1847. else if (is ("rack.selectNext")) rack.selectRelative (1, false);
  1848. else if (is ("rack.extendUp")) rack.selectRelative (-1, true);
  1849. else if (is ("rack.extendDown")) rack.selectRelative (1, true);
  1850. else if (is ("rack.moveUp")) rack.moveSelected (-1);
  1851. else if (is ("rack.moveDown")) rack.moveSelected (1);
  1852. else if (is ("rack.selectAll")) rack.selectAll();
  1853. else if (is ("rack.clone")) rack.cloneSelected();
  1854. else if (is ("rack.deleteSelected")) rack.deleteSelected();
  1855. else if (is ("rack.cut")) rack.cutSelected();
  1856. else if (is ("rack.copy")) rack.copySelected();
  1857. else if (is ("rack.paste")) rack.pasteSelected();
  1858. else if (is ("rack.sendToInserts")) rack.sendSelectedToInserts();
  1859. else if (id.rfind ("rack.mute", 0) == 0) rack.toggleMute (std::stoi (id.substr (9)) - 1);
  1860. else if (id.rfind ("rack.solo", 0) == 0) rack.solo (std::stoi (id.substr (9)) - 1);
  1861. else
  1862. return false;
  1863. return true;
  1864. }
  1865. bool MainComponent::keyStateChanged (bool)
  1866. {
  1867. // JUCE has no per-key "keyReleased"; check which held keys were released (each held note remembers its
  1868. // channel and key, so the selection changing meanwhile can't leave one sounding)
  1869. std::vector<int> released;
  1870. heldKeys.forEachTag ([&released] (int code) {
  1871. if (! juce::KeyPress::isKeyCurrentlyDown (code))
  1872. released.push_back (code);
  1873. });
  1874. for (auto code : released)
  1875. heldKeys.releaseTag (code);
  1876. releaseTypingLaunches (false);
  1877. return false;
  1878. }
  1879. juce::String MainComponent::shortcutText (const char* actionId) const
  1880. {
  1881. const auto& chords = keyMap.chordsFor (actionId);
  1882. return chords.empty() ? juce::String() : "\t" + juce::String (keys::displayString (chords.front()));
  1883. }
  1884. void MainComponent::toggleTypingPiano()
  1885. {
  1886. setTypingPiano (! typingPiano);
  1887. // say what changed in the hint bar (issue #34: people did not find the typing piano; Ctrl+T gave no feedback)
  1888. ui::Hint hint;
  1889. hint.text = typingPiano ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  1890. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)");
  1891. ui::postHint (hint, 2500);
  1892. }
  1893. void MainComponent::setTypingPiano (bool on)
  1894. {
  1895. typingPiano = on;
  1896. EditorGlobals::get().typingPiano = on; // the editors' single-letter tool keys only work while it is off
  1897. typingPianoButton.setToggleState (on, juce::dontSendNotification);
  1898. typingPianoButton.setTooltip ((on ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  1899. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)"))
  1900. + juce::String (" (") + juce::String (keys::displayString (keyMap.chordsFor ("view.typingPiano").empty() ? keys::Chord {}
  1901. : keyMap.chordsFor ("view.typingPiano").front()))
  1902. + ")");
  1903. // release anything still sounding from the keyboard
  1904. heldKeys.releaseAll();
  1905. releaseTypingLaunches (true);
  1906. }
  1907. void MainComponent::loadKeyMap()
  1908. {
  1909. keyMap.resetToDefaults();
  1910. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  1911. if (file.existsAsFile())
  1912. {
  1913. std::vector<std::string> errors;
  1914. if (! keyMap.loadJson (file.loadFileAsString().toStdString(), &errors))
  1915. juce::Logger::writeToLog ("keys.json is not a JSON object; using the default keys");
  1916. for (const auto& e : errors)
  1917. juce::Logger::writeToLog ("keys.json: " + juce::String (e));
  1918. }
  1919. auto keyOf = [this] (const std::string& id) {
  1920. const auto& chords = keyMap.chordsFor (id);
  1921. return chords.empty() ? juce::String() : juce::String (keys::displayString (chords.front()));
  1922. };
  1923. pianoRoll.refreshToolKeys (keyOf);
  1924. playlist.refreshToolKeys (keyOf);
  1925. }
  1926. // --- Browsers ------------------------------------------------------------------------------------
  1927. // The main Browser and the separate Sample browser window (round 163) act on the project the same way.
  1928. void MainComponent::connectBrowser (BrowserComponent& b)
  1929. {
  1930. b.onOpenProject = [this] (const juce::File& file) { confirmDiscard ([this, file] { openFile (file); }); };
  1931. b.onLoadIntoChannel = [this] (const juce::File& file) { return rack.loadSampleIntoSelected (file); };
  1932. b.onOpenMixerPreset = [this] (const juce::File& file) {
  1933. if (! mixerpresets::isMixerPreset (file))
  1934. return false;
  1935. if (! mixer.loadPresetOnSelection (file))
  1936. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Open mixer track state"),
  1937. tr ("This file is not a mixer track state LYNX SHARE can read."));
  1938. return true;
  1939. };
  1940. // the Browser's "Current project" items (REA_rodada115)
  1941. b.onOpenPattern = [this] (int pattern) {
  1942. selectPattern (pattern);
  1943. openPianoRoll();
  1944. };
  1945. b.onPatternMenu = [this] (int pattern) {
  1946. selectPattern (pattern);
  1947. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1948. };
  1949. b.onOpenChannel = [this] (int channel) {
  1950. engine.setSelectedChannel (channel);
  1951. rack.toggleEditor (channel, true);
  1952. };
  1953. b.onOpenEffect = [this] (int track, int slot) {
  1954. showPanel (Panel::mixer);
  1955. mixer.openSlotEditor (track, slot);
  1956. };
  1957. b.onShowInsert = [this] (int track) {
  1958. showPanel (Panel::mixer);
  1959. mixer.selectTrack (track);
  1960. };
  1961. b.onOpenAutomation = [this] (int automation) { openAutomationEditor (engine, automation); };
  1962. // the Browser's Plugin database (round 142): the same targets as the quick-add palette
  1963. b.onAddInstrument = [this] (ChannelDef c) {
  1964. if (PatcherWindows::takeInstrumentFromBrowser (c)) // a Patcher's Add plugin › Browse plugin database (round 162)
  1965. return;
  1966. rack.addChannel (std::move (c), true);
  1967. showPanel (Panel::channelRack);
  1968. };
  1969. b.onAddEffect = [this] (EffectSlot slot) {
  1970. if (PatcherWindows::takeEffectFromBrowser (slot))
  1971. return;
  1972. if (! mixer.addEffectToSelected (std::move (slot)))
  1973. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  1974. tr ("The selected insert has no free effect slot."));
  1975. else
  1976. showPanel (Panel::mixer);
  1977. };
  1978. b.onPreviewVolumeChanged = [this] { saveUiSettings(); };
  1979. b.onSendToPlaylist = [this] (const juce::File& file) {
  1980. playlist.addAudioClipAtPlayhead (file);
  1981. showPanel (Panel::playlist);
  1982. };
  1983. b.onToggleSampleBrowser = [this] { toggleSampleBrowser(); };
  1984. }
  1985. void MainComponent::toggleSampleBrowser()
  1986. {
  1987. if (auto* w = findToolWindow ("sampleBrowser"))
  1988. {
  1989. w->closeButtonPressed(); // (hidden, then deleted: remembered as closed)
  1990. return;
  1991. }
  1992. openSampleBrowser();
  1993. }
  1994. void MainComponent::openSampleBrowser()
  1995. {
  1996. auto* window = openToolWindow (BrowserComponent::makeSampleBrowserContent (engine, [this] (BrowserComponent& b) { connectBrowser (b); }),
  1997. tr ("Sample browser"), "sampleBrowser");
  1998. if (window == nullptr)
  1999. return;
  2000. window->setResizable (true, false);
  2001. window->setResizeLimits (240, 260, 4000, 4000);
  2002. const auto saved = BrowserComponent::sampleBrowserBounds();
  2003. const auto area = juce::Desktop::getInstance().getDisplays().getTotalBounds (true);
  2004. if (saved.getWidth() >= 240 && saved.getHeight() >= 260 && area.intersects (saved))
  2005. window->setBounds (saved);
  2006. else if (auto* top = getTopLevelComponent())
  2007. window->setBounds (top->getScreenBounds().getRight() - 360, top->getScreenY() + 80, 340, juce::jmax (400, top->getHeight() - 160));
  2008. }
  2009. // --- UI options ----------------------------------------------------------------------------------
  2010. juce::File MainComponent::uiSettingsFile() const
  2011. {
  2012. return PluginHost::settingsFolder().getChildFile ("ui-options.txt");
  2013. }
  2014. void MainComponent::loadUiSettings()
  2015. {
  2016. juce::StringArray lines;
  2017. lines.addLines (uiSettingsFile().loadFileAsString());
  2018. // the sound in FL's order (0.1.20) wins over the old key, wherever each line is
  2019. const auto flMetronomeSound = std::any_of (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("metronomeSoundFl"); });
  2020. // "Blend recorded notes" (round 177c): see startingRecordMode() for who starts with what
  2021. {
  2022. const auto saved = std::find_if (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("recordBlend="); });
  2023. auto o = engine.getRecordOptions();
  2024. o.mode = startingRecordMode (uiSettingsFile().existsAsFile(), saved != lines.end(),
  2025. saved != lines.end() && saved->fromFirstOccurrenceOf ("=", false, false).trim() == "1");
  2026. engine.setRecordOptions (o);
  2027. }
  2028. for (const auto& line : lines)
  2029. {
  2030. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  2031. const auto on = line.fromFirstOccurrenceOf ("=", false, false).trim() == "1";
  2032. if (key == "typingPiano")
  2033. typingPiano = on;
  2034. else if (key == "typingOctave")
  2035. typingOctave = keys::typingpiano::clampOctave (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2036. else if (key == "typingRoot")
  2037. typingRoot = keys::typingpiano::clampRoot (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2038. else if (key == "typingLayout") // FL's layout name, so the list can grow
  2039. typingLayout = keys::typingpiano::layoutIndex (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2040. else if (key == "keepEditorsOpen")
  2041. ChannelRackComponent::keepEditorsOpen = on;
  2042. else if (key == "selFirstChanPatChanges")
  2043. ChannelRackComponent::selectFirstChannelWithNotes = on;
  2044. else if (key == "prPaintMode") // FL's PRPaintMode (round 189o)
  2045. PianoRollComponent::monophonicPainting = on;
  2046. else if (key == "limitEditors") // FL's LimitEditors (round 189o; on unless saved off)
  2047. editorlimit::enabled() = on;
  2048. else if (key == "detachNewPlugins") // FL's General › "Detach all new plugins" (issue #116)
  2049. engine.setDetachNewPlugins (on);
  2050. else if (key == "autoSelectLinked")
  2051. ChannelRackComponent::autoSelectLinked = on;
  2052. else if (key == "muteRemovedSteps")
  2053. ChannelRackComponent::muteRemovedSteps = on;
  2054. else if (key == "audioTrackControls") // round 190w: Playlist › View › Track headers
  2055. PlaylistComponent::showAudioTrackControls = on;
  2056. else if (key == "audioTrackLevels")
  2057. PlaylistComponent::showAudioTrackLevels = on;
  2058. else if (key == "instrumentTrackLevels")
  2059. PlaylistComponent::showInstrumentTrackLevels = on;
  2060. else if (key == "automationLanes") // round 177b: Playlist › Automation lanes
  2061. autolanes::setShown (on);
  2062. else if (key == "alternateUndo")
  2063. alternateUndo = on;
  2064. else if (key == "waveSpectral") // ("waveColours", the old spectral-by-default key, is ignored)
  2065. ui::WaveformCache::spectral = on;
  2066. else if (key == "pluginStyle") // "Automatic" or a style forced on every plugin
  2067. {
  2068. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim();
  2069. skin::setForcedStyle (v.equalsIgnoreCase ("Automatic") || v.isEmpty() ? -1 : (int) skin::styleFromName (v));
  2070. }
  2071. else if (key == "pluginStyleOverrides")
  2072. skin::overridesFromString (line.fromFirstOccurrenceOf ("=", false, false).trim());
  2073. else if (key == "reducedEffects")
  2074. skin::setReducedEffects (on);
  2075. else if (key == "animationRate") // round 174e2: 0 = the display's refresh, else 60 / 30
  2076. {
  2077. const auto hz = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2078. ui::FrameTicker::rateLimit() = hz == 30 || hz == 60 ? hz : 0;
  2079. }
  2080. else if (key == "uiAnimations") // round 179a (ui/Motion.h)
  2081. ui::motion::enabled() = on;
  2082. else if (key == "artMotion")
  2083. skin::setArtMotion (on);
  2084. else if (key == "waveStereo")
  2085. ui::WaveformCache::stereo = on;
  2086. else if (key == "noteNames")
  2087. notenames::currentStyle.store (juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2088. else if (key == "noteFlats")
  2089. notenames::currentFlats.store (on);
  2090. else if (key == "noteNamesEveryKey")
  2091. notenames::everyKey.store (on);
  2092. else if (key == "rackPlayheadColumn")
  2093. ChannelRackComponent::playheadColumn.store (on);
  2094. else if (key == "rackStepsChannelColour")
  2095. ChannelRackComponent::stepsChannelColour.store (on);
  2096. else if (key == "rememberSeek")
  2097. EditorGlobals::get().rememberSeek = on;
  2098. else if (key == "createVariants")
  2099. EditorGlobals::get().createVariants = on;
  2100. else if (key == "plLeftResizing") // round 189g: FL's Playlist Edit / Select options
  2101. EditorGlobals::get().leftResizing = on;
  2102. else if (key == "plWheelNudging")
  2103. EditorGlobals::get().wheelNudging = on;
  2104. else if (key == "plManualFades")
  2105. EditorGlobals::get().manualFades = on;
  2106. else if (key == "plSnapFadeHandles")
  2107. EditorGlobals::get().snapFadeHandles = on;
  2108. else if (key == "plMagicLasso")
  2109. EditorGlobals::get().magicLasso = on;
  2110. else if (key == "dropAudioOnHeaders") // round 189e: FL's Edit › Drop audio on track headers (DropAudioToPLMode)
  2111. {
  2112. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2113. trackmodes::headerDropOptions().mode = v == 256 || v == 257 || v == 258 ? (trackmodes::HeaderDrop) v : trackmodes::HeaderDrop::ask;
  2114. }
  2115. else if (key == "dropLocksToContent")
  2116. trackmodes::headerDropOptions().lockToContent = on;
  2117. else if (key == "selectTracksOnDrop")
  2118. trackmodes::headerDropOptions().selectTracks = on;
  2119. else if (key == "prGridHighlights") // (round 168g: the Piano roll's View items)
  2120. PianoRollComponent::gridHighlights = on;
  2121. else if (key == "prShowChordName")
  2122. PianoRollComponent::showChordName = on;
  2123. else if (key == "prSongBars")
  2124. PianoRollComponent::songBarsRuler = on;
  2125. else if (key == "prKeyStyle") // (round 190j: 0 = flat, FL's; 1 = piano keys)
  2126. PianoRollComponent::keyStyle = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue() == 1 ? pianokeys::Style::piano
  2127. : pianokeys::Style::flat;
  2128. else if (key == "audioLogEnabled")
  2129. engine.getRollingLog().setEnabled (on);
  2130. else if (key == "audioLogSeconds")
  2131. {
  2132. const auto seconds = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2133. if (seconds == 60 || seconds == 120 || seconds == 300 || seconds == 600)
  2134. engine.getRollingLog().setLengthSeconds (seconds);
  2135. }
  2136. else if (key == "audioLogPreEffects")
  2137. engine.getRollingLog().setPosition (on ? RollingAudioLog::Position::preEffects : RollingAudioLog::Position::postEffects);
  2138. else if (key == "chordDelayMs")
  2139. chordReadout.setDelayMs ((std::uint32_t) line.fromFirstOccurrenceOf ("=", false, false).trim().getLargeIntValue());
  2140. else if (key == "chordRoman")
  2141. {
  2142. auto o = chordReadout.getOptions();
  2143. o.roman = on;
  2144. chordReadout.setOptions (o);
  2145. }
  2146. else if (key == "chordNearHint")
  2147. chordShowNearHint = on;
  2148. else if (key == "keyPanelFollowsStyle")
  2149. keyPanelFollowsStyle = on;
  2150. else if (key == "stretchedClipsLoop")
  2151. setStretchedClipsLoop (on);
  2152. else if (key == "autoClipsAtPlayback")
  2153. autoclipplace::setAtPlayback (on);
  2154. else if (key == "disableTypingPriority")
  2155. pluginkeys::newPluginsHostFirst() = on;
  2156. else if (key == "clipLaunchWorkflow") // (round 181a; applied when the window is ready; "layoutStyle" wins)
  2157. startStyle.legacyFlag (on);
  2158. else if (key == "layoutStyle") // (round 184a)
  2159. startStyle.styleId (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2160. else if (key == "lanesBeforeClipLaunch")
  2161. lanesBeforeClipLaunch = on;
  2162. else if (key == "detailHeight") // round 183a: the Clip-launch workflow's detail view
  2163. DetailView::preferredHeight = juce::jlimit (DetailView::minHeight, 2000, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2164. else if (key == "detailShown")
  2165. DetailView::shownSetting = on;
  2166. else if (key == "detailDevices")
  2167. DetailView::devicesPage = on;
  2168. else if (key == "detailExtraWindowKey")
  2169. DetailView::extraWindowKey = on;
  2170. else if (key == "detailExtraSelectInMixer")
  2171. DetailView::extraSelectInMixer = on;
  2172. else if (key == "alsSessionOnPlaylist")
  2173. AudioEngine::alsSessionOnPlaylist = on;
  2174. else if (key == "followPlaylist" || key == "followPianoRoll")
  2175. EditorGlobals::get().setFollowing (key == "followPianoRoll", on, false);
  2176. else if (key == "followChannelRack" || key == "followAudioEditor")
  2177. EditorGlobals::get().setFollowingView (key == "followChannelRack" ? EditorGlobals::FollowView::channelRack
  2178. : EditorGlobals::FollowView::audioEditor, on, false);
  2179. else if (key == "scopeMode")
  2180. toolbar::OutputMonitor::mode = juce::jlimit (0, toolbar::OutputMonitor::modeCount - 1,
  2181. line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2182. else if (key == "toolbarGroups")
  2183. toolbarLayout.orderFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2184. else if (key == "toolbarIcons")
  2185. toolbarLayout.iconSize = toolbarlayout::Layout::iconSizeFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2186. else if (key == "toolbarSeparators")
  2187. toolbarLayout.separators = on;
  2188. else if (key == "toolbarVisible")
  2189. toolbarLayout.visible = on;
  2190. else if (key == "menuDensity")
  2191. theme::menus::setCompact (line.fromFirstOccurrenceOf ("=", false, false).trim() != "comfortable");
  2192. else if (key == "uiScale")
  2193. toolbarLayout.uiScale = toolbarlayout::clampScale (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2194. else if (key == "editPatternsIn")
  2195. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2196. else if (key == "autosaveMinutes")
  2197. autosaveMinutes = prefs::clampAutosaveMinutes (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2198. else if (key == "askUnusedRecordings")
  2199. askUnusedRecordings = on;
  2200. else if (key == "messagesHidden") // FL's "Manage messages" (round 186c)
  2201. messages::setHiddenList (line.fromFirstOccurrenceOf ("=", false, false).trim());
  2202. else if (key == "backupWaitsForQuiet")
  2203. backupWaitsForQuiet = on;
  2204. else if (key == "backupLongestWait")
  2205. backupLongestWaitMinutes = prefs::clampBackupLongestWait (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2206. else if (key == "hoverValues")
  2207. hoverValues = on;
  2208. else if (key == "autosaveKeep")
  2209. autosaveKeep = prefs::clampAutosaveKeep (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2210. else if (key == "metronomeSound" && ! flMetronomeSound) // (before 0.1.20: 0 LYNX click, 1..5 hi-hat..pulse)
  2211. engine.getTransport().metronomeSound.store (metronome::soundFromLegacy (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2212. else if (key == "metronomeSoundFl") // FL's order: 0 Hi-hat, 1 Tick, 2 Beep, 3 Cowbell, 4 Pulse
  2213. engine.getTransport().metronomeSound.store (metronome::clampSound (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2214. else if (key == "metronomeTrack")
  2215. engine.getTransport().metronomeTrack.store (juce::jlimit (0, maxMixerTracks - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2216. else if (key == "playTruncatedOnTransport")
  2217. engine.getTransport().playTruncatedOnTransport.store (on);
  2218. else if (key == "resetPluginsOnTransport")
  2219. engine.getTransport().resetPluginsOnTransport.store (on);
  2220. else if (key == "metronomeVolume")
  2221. engine.getTransport().metronomeVolume.store ((float) controls::clampUtilityVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue()));
  2222. else if (key == "previewVolume")
  2223. engine.setPreviewVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  2224. else if (key == "editorVolume")
  2225. engine.setEditorVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  2226. else if (key == "rackPianoRollView")
  2227. rack.setPianoRollView (on);
  2228. else if (key == "undoLevels")
  2229. engine.setUndoLevels (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2230. else if (key == "askWhatToRecord" || key == "recordNotes" || key == "recordAudio" || key == "recordStartsPlayback" || key == "disarmOnStop"
  2231. || key == "recordOffOnStop" || key == "unarmAfterRender" || key == "renderAutoClip")
  2232. {
  2233. auto o = engine.getRecordOptions();
  2234. (key == "askWhatToRecord" ? o.askWhatToRecord : key == "recordNotes" ? o.recordNotes : key == "recordAudio" ? o.recordAudio
  2235. : key == "disarmOnStop" ? o.disarmOnStop : key == "recordOffOnStop" ? o.recordOffOnStop : key == "unarmAfterRender" ? o.unarmAfterRender
  2236. : key == "renderAutoClip" ? o.autoCreateClip
  2237. : o.startsPlayback) = on;
  2238. engine.setRecordOptions (o);
  2239. }
  2240. else if (key == "recordAutomation" || key == "recordQuantiseAutomation" || key == "recordClips")
  2241. {
  2242. auto o = engine.getRecordOptions();
  2243. (key == "recordAutomation" ? o.recordAutomation : key == "recordClips" ? o.recordClips : o.quantiseAutomation) = on;
  2244. engine.setRecordOptions (o);
  2245. }
  2246. else if (key == "recordToStepSequencer" || key == "recordingMarkers" || key == "recordNoteEnd")
  2247. {
  2248. auto o = engine.getRecordOptions();
  2249. if (key == "recordNoteEnd")
  2250. o.noteEnd = (NoteEnd) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2251. else
  2252. (key == "recordToStepSequencer" ? o.toStepSequencer : o.recordingMarkers) = on;
  2253. engine.setRecordOptions (o);
  2254. }
  2255. else if (key == "recordCatchWindow" || key == "recordCompensateOutput") // (round 170d)
  2256. {
  2257. auto o = engine.getRecordOptions();
  2258. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getLargeIntValue();
  2259. if (key == "recordCatchWindow")
  2260. o.catchWindow = juce::jlimit<std::int64_t> (0, ppq, v);
  2261. else
  2262. o.compensateOutput = v != 0;
  2263. engine.setRecordOptions (o);
  2264. }
  2265. else if (key == "recordPunchLoop" || key == "recordPreRoll" || key == "recordPostRoll" || key == "recordLoop" || key == "recordLastPassPlays")
  2266. {
  2267. auto o = engine.getRecordOptions();
  2268. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2269. if (key == "recordPunchLoop")
  2270. o.punchLoopRegion = v != 0;
  2271. else if (key == "recordLoop")
  2272. o.loopRecord = v != 0;
  2273. else if (key == "recordLastPassPlays")
  2274. o.lastLoopPassPlays = v != 0;
  2275. else
  2276. (key == "recordPreRoll" ? o.preRollBars : o.postRollBars) = juce::jlimit (0, 8, v);
  2277. engine.setRecordOptions (o);
  2278. }
  2279. else if (key == "recordQuantiseStarts")
  2280. {
  2281. recordQuantiseOn = on;
  2282. updateRecordQuantise();
  2283. }
  2284. else if (key == "newInserts" || key == "newMasterChain" || key == "newCleanMixer" || key == "playlistTracks" || key == "newAutoCrossfades")
  2285. newProjectDefaults().readKey (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2286. else if (key == "mixerUsedOnly")
  2287. MixerStrips::showUsedOnly = on;
  2288. else if (key == "mixerLoudness") // round 190am (also starts the measurement)
  2289. mixer.getStripsForSnapshot().setShowLoudness (on);
  2290. else if (key == "mixerKeepLostLinks")
  2291. MixerStrips::keepLostLinks = on;
  2292. else if (key == "mixerFollowPlaylist")
  2293. MixerStrips::followPlaylist = on;
  2294. else if (key == "mixerLayout") // FL's FXViewMode numbering (issue #52)
  2295. {
  2296. MixerStrips::layout = mixerlayout::parse (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2297. mixer.getStripsForSnapshot().updateSize();
  2298. }
  2299. else if (key == "quantizeSongJumps")
  2300. engine.quantizeSongJumps.store (juce::jlimit (0, 5, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2301. }
  2302. startup = StartupOptions::load();
  2303. browser.refreshPreviewVolume();
  2304. }
  2305. void MainComponent::saveUiSettings()
  2306. {
  2307. if (! persistent)
  2308. return;
  2309. uiSettingsFile().replaceWithText ("typingPiano=" + juce::String (typingPiano ? 1 : 0) + "\ntypingOctave=" + juce::String (typingOctave)
  2310. + "\ntypingRoot=" + juce::String (typingRoot)
  2311. + "\ntypingLayout=" + juce::String (keys::typingpiano::layoutName (typingLayout)) + "\nkeepEditorsOpen="
  2312. + juce::String (ChannelRackComponent::keepEditorsOpen ? 1 : 0)
  2313. + "\nselFirstChanPatChanges=" + juce::String (ChannelRackComponent::selectFirstChannelWithNotes ? 1 : 0)
  2314. + "\nprPaintMode=" + juce::String (PianoRollComponent::monophonicPainting ? 1 : 0)
  2315. + "\nlimitEditors=" + juce::String (editorlimit::enabled() ? 1 : 0)
  2316. + "\ndetachNewPlugins=" + juce::String (engine.detachesNewPlugins() ? 1 : 0)
  2317. + "\nautoSelectLinked=" + juce::String (ChannelRackComponent::autoSelectLinked ? 1 : 0)
  2318. + "\nmuteRemovedSteps=" + juce::String (ChannelRackComponent::muteRemovedSteps ? 1 : 0)
  2319. + "\naudioTrackControls=" + juce::String (PlaylistComponent::showAudioTrackControls ? 1 : 0)
  2320. + "\naudioTrackLevels=" + juce::String (PlaylistComponent::showAudioTrackLevels ? 1 : 0)
  2321. + "\ninstrumentTrackLevels=" + juce::String (PlaylistComponent::showInstrumentTrackLevels ? 1 : 0)
  2322. + "\nautomationLanes=" + juce::String (autolanes::shown() ? 1 : 0)
  2323. + "\nalternateUndo=" + juce::String (alternateUndo ? 1 : 0)
  2324. + "\neditPatternsIn="
  2325. + juce::String (PlaylistComponent::editPatternsIn) + "\nsplash=" + juce::String (startup.splash ? 1 : 0)
  2326. + "\nstartupSound=" + juce::String (startup.sound ? 1 : 0)
  2327. + "\nwaveSpectral=" + juce::String (ui::WaveformCache::spectral ? 1 : 0)
  2328. + "\nwaveStereo=" + juce::String (ui::WaveformCache::stereo ? 1 : 0)
  2329. + "\nnoteNames=" + juce::String (notenames::currentStyle.load())
  2330. + "\nnoteFlats=" + juce::String (notenames::currentFlats.load() ? 1 : 0)
  2331. + "\nnoteNamesEveryKey=" + juce::String (notenames::everyKey.load() ? 1 : 0)
  2332. + "\nrackPlayheadColumn=" + juce::String (ChannelRackComponent::playheadColumn.load() ? 1 : 0)
  2333. + "\nrackStepsChannelColour=" + juce::String (ChannelRackComponent::stepsChannelColour.load() ? 1 : 0)
  2334. + "\nreducedEffects=" + juce::String (skin::reducedEffects() ? 1 : 0)
  2335. + "\nanimationRate=" + juce::String (ui::FrameTicker::rateLimit())
  2336. + "\nuiAnimations=" + juce::String (ui::motion::enabled() ? 1 : 0)
  2337. + "\nartMotion=" + juce::String (skin::artMotion() ? 1 : 0)
  2338. + "\npluginStyle=" + juce::String (skin::forcedStyle() < 0 ? "Automatic" : skin::styleName ((skin::Style) skin::forcedStyle()))
  2339. + "\npluginStyleOverrides=" + skin::overridesToString()
  2340. + "\nrememberSeek=" + juce::String (EditorGlobals::get().rememberSeek ? 1 : 0)
  2341. + "\ncreateVariants=" + juce::String (EditorGlobals::get().createVariants ? 1 : 0)
  2342. + "\nplLeftResizing=" + juce::String (EditorGlobals::get().leftResizing ? 1 : 0)
  2343. + "\nplWheelNudging=" + juce::String (EditorGlobals::get().wheelNudging ? 1 : 0)
  2344. + "\nplManualFades=" + juce::String (EditorGlobals::get().manualFades ? 1 : 0)
  2345. + "\nplSnapFadeHandles=" + juce::String (EditorGlobals::get().snapFadeHandles ? 1 : 0)
  2346. + "\nplMagicLasso=" + juce::String (EditorGlobals::get().magicLasso ? 1 : 0)
  2347. + "\ndropAudioOnHeaders=" + juce::String ((int) trackmodes::headerDropOptions().mode)
  2348. + "\ndropLocksToContent=" + juce::String (trackmodes::headerDropOptions().lockToContent ? 1 : 0)
  2349. + "\nselectTracksOnDrop=" + juce::String (trackmodes::headerDropOptions().selectTracks ? 1 : 0)
  2350. + "\nprGridHighlights=" + juce::String (PianoRollComponent::gridHighlights ? 1 : 0)
  2351. + "\nprShowChordName=" + juce::String (PianoRollComponent::showChordName ? 1 : 0)
  2352. + "\nprSongBars=" + juce::String (PianoRollComponent::songBarsRuler ? 1 : 0)
  2353. + "\nprKeyStyle=" + juce::String ((int) PianoRollComponent::keyStyle)
  2354. + "\naudioLogEnabled=" + juce::String (engine.getRollingLog().isEnabled() ? 1 : 0)
  2355. + "\naudioLogSeconds=" + juce::String (engine.getRollingLog().lengthSeconds())
  2356. + "\naudioLogPreEffects=" + juce::String (engine.getRollingLog().getPosition() == RollingAudioLog::Position::preEffects ? 1 : 0)
  2357. + "\nchordDelayMs=" + juce::String ((std::int64_t) chordReadout.getDelayMs())
  2358. + "\nchordRoman=" + juce::String (chordReadout.getOptions().roman ? 1 : 0)
  2359. + "\nchordNearHint=" + juce::String (chordShowNearHint ? 1 : 0)
  2360. + "\nkeyPanelFollowsStyle=" + juce::String (keyPanelFollowsStyle ? 1 : 0)
  2361. + "\nstretchedClipsLoop=" + juce::String (stretchedClipsLoop() ? 1 : 0)
  2362. + "\nautoClipsAtPlayback=" + juce::String (autoclipplace::atPlayback() ? 1 : 0)
  2363. + "\ndisableTypingPriority=" + juce::String (pluginkeys::newPluginsHostFirst().load() ? 1 : 0)
  2364. + "\nclipLaunchWorkflow=" + juce::String (layoutstyle::legacyClipLaunchFlag (layoutStyle) ? 1 : 0)
  2365. + "\nlayoutStyle=" + layoutstyle::id (layoutStyle)
  2366. + "\nlanesBeforeClipLaunch=" + juce::String (lanesBeforeClipLaunch ? 1 : 0)
  2367. + "\ndetailHeight=" + juce::String (DetailView::preferredHeight)
  2368. + "\ndetailShown=" + juce::String (DetailView::shownSetting ? 1 : 0)
  2369. + "\ndetailDevices=" + juce::String (DetailView::devicesPage ? 1 : 0)
  2370. + "\ndetailExtraWindowKey=" + juce::String (DetailView::extraWindowKey ? 1 : 0)
  2371. + "\ndetailExtraSelectInMixer=" + juce::String (DetailView::extraSelectInMixer ? 1 : 0)
  2372. + "\nalsSessionOnPlaylist=" + juce::String (AudioEngine::alsSessionOnPlaylist.load() ? 1 : 0)
  2373. + "\nfollowPlaylist=" + juce::String (EditorGlobals::get().isFollowing (false) ? 1 : 0)
  2374. + "\nfollowPianoRoll=" + juce::String (EditorGlobals::get().isFollowing (true) ? 1 : 0)
  2375. + "\nfollowChannelRack=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack) ? 1 : 0)
  2376. + "\nfollowAudioEditor=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor) ? 1 : 0)
  2377. + "\nscopeMode=" + juce::String (toolbar::OutputMonitor::mode)
  2378. + "\ntoolbarGroups=" + juce::String (toolbarLayout.orderToString())
  2379. + "\ntoolbarIcons=" + toolbarlayout::Layout::iconSizeId (toolbarLayout.iconSize)
  2380. + "\nuiScale=" + juce::String (toolbarLayout.uiScale)
  2381. + "\nmenuDensity=" + juce::String (theme::menus::compact() ? "compact" : "comfortable")
  2382. + "\ntoolbarSeparators=" + juce::String (toolbarLayout.separators ? 1 : 0)
  2383. + "\ntoolbarVisible=" + juce::String (toolbarLayout.visible ? 1 : 0)
  2384. + "\nautosaveMinutes=" + juce::String (autosaveMinutes) + "\nautosaveKeep=" + juce::String (autosaveKeep)
  2385. + "\naskUnusedRecordings=" + juce::String (askUnusedRecordings ? 1 : 0)
  2386. + "\nmessagesHidden=" + messages::hiddenList()
  2387. + "\nbackupWaitsForQuiet=" + juce::String (backupWaitsForQuiet ? 1 : 0)
  2388. + "\nbackupLongestWait=" + juce::String (backupLongestWaitMinutes)
  2389. + "\nhoverValues=" + juce::String (hoverValues ? 1 : 0)
  2390. + "\nundoLevels=" + juce::String (engine.getUndoLevels())
  2391. + "\nmetronomeVolume=" + juce::String (engine.getTransport().metronomeVolume.load(), 2)
  2392. + "\nmetronomeSoundFl=" + juce::String (metronome::clampSound (engine.getTransport().metronomeSound.load()))
  2393. + "\nmetronomeTrack=" + juce::String (engine.getTransport().metronomeTrack.load())
  2394. + "\nplayTruncatedOnTransport=" + juce::String (engine.getTransport().playTruncatedOnTransport.load() ? 1 : 0)
  2395. + "\nresetPluginsOnTransport=" + juce::String (engine.getTransport().resetPluginsOnTransport.load() ? 1 : 0)
  2396. + "\npreviewVolume=" + juce::String (engine.getPreviewVolume(), 2)
  2397. + "\neditorVolume=" + juce::String (engine.getEditorVolume(), 2)
  2398. + "\nrackPianoRollView=" + juce::String (rack.isPianoRollView() ? 1 : 0)
  2399. + "\naskWhatToRecord=" + juce::String (engine.getRecordOptions().askWhatToRecord ? 1 : 0)
  2400. + "\nrecordNotes=" + juce::String (engine.getRecordOptions().recordNotes ? 1 : 0)
  2401. + "\nrecordAudio=" + juce::String (engine.getRecordOptions().recordAudio ? 1 : 0)
  2402. + "\nrecordStartsPlayback=" + juce::String (engine.getRecordOptions().startsPlayback ? 1 : 0)
  2403. + "\ndisarmOnStop=" + juce::String (engine.getRecordOptions().disarmOnStop ? 1 : 0)
  2404. + "\nrecordOffOnStop=" + juce::String (engine.getRecordOptions().recordOffOnStop ? 1 : 0)
  2405. + "\nunarmAfterRender=" + juce::String (engine.getRecordOptions().unarmAfterRender ? 1 : 0)
  2406. + "\nrenderAutoClip=" + juce::String (engine.getRecordOptions().autoCreateClip ? 1 : 0)
  2407. + "\nrecordQuantiseStarts=" + juce::String (recordQuantiseOn ? 1 : 0)
  2408. + "\nrecordNoteEnd=" + juce::String ((int) engine.getRecordOptions().noteEnd)
  2409. + "\nrecordToStepSequencer=" + juce::String (engine.getRecordOptions().toStepSequencer ? 1 : 0)
  2410. + "\nrecordingMarkers=" + juce::String (engine.getRecordOptions().recordingMarkers ? 1 : 0)
  2411. + "\nrecordAutomation=" + juce::String (engine.getRecordOptions().recordAutomation ? 1 : 0)
  2412. + "\nrecordClips=" + juce::String (engine.getRecordOptions().recordClips ? 1 : 0)
  2413. + "\nrecordQuantiseAutomation=" + juce::String (engine.getRecordOptions().quantiseAutomation ? 1 : 0)
  2414. + "\nrecordPunchLoop=" + juce::String (engine.getRecordOptions().punchLoopRegion ? 1 : 0)
  2415. + "\nrecordLoop=" + juce::String (engine.getRecordOptions().loopRecord ? 1 : 0)
  2416. + "\nrecordLastPassPlays=" + juce::String (engine.getRecordOptions().lastLoopPassPlays ? 1 : 0)
  2417. + "\nrecordBlend=" + juce::String (engine.getRecordOptions().mode == RecordMode::overdub ? 1 : 0)
  2418. + "\nrecordPreRoll=" + juce::String (engine.getRecordOptions().preRollBars)
  2419. + "\nrecordCatchWindow=" + juce::String (engine.getRecordOptions().catchWindow)
  2420. + "\nrecordCompensateOutput=" + juce::String (engine.getRecordOptions().compensateOutput ? 1 : 0)
  2421. + "\nrecordPostRoll=" + juce::String (engine.getRecordOptions().postRollBars) + "\nmixerUsedOnly=" + juce::String (MixerStrips::showUsedOnly ? 1 : 0) + "\nmixerLoudness=" + juce::String (MixerStrips::showLoudness ? 1 : 0) + "\nmixerKeepLostLinks=" + juce::String (MixerStrips::keepLostLinks ? 1 : 0) + "\nmixerFollowPlaylist=" + juce::String (MixerStrips::followPlaylist ? 1 : 0) + "\nmixerLayout=" + juce::String ((int) MixerStrips::layout)
  2422. + "\nquantizeSongJumps=" + juce::String (engine.quantizeSongJumps.load()) + "\n"
  2423. + juce::String (newProjectDefaults().toText()));
  2424. }
  2425. // --- transport -----------------------------------------------------------------------------------
  2426. void MainComponent::playStop()
  2427. {
  2428. auto& transport = engine.getTransport();
  2429. if (engine.isWaitingForInput() || engine.isCountingIn()) // pressed again: cancel
  2430. {
  2431. engine.stop();
  2432. return;
  2433. }
  2434. if (transport.playing.load())
  2435. {
  2436. engine.stop();
  2437. engine.seek (playStartTicks); // back to where playback started
  2438. }
  2439. else
  2440. {
  2441. playStartTicks = transport.positionTicks.load();
  2442. engine.startPlayback();
  2443. }
  2444. }
  2445. void MainComponent::playPause()
  2446. {
  2447. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn())
  2448. engine.stop();
  2449. else
  2450. {
  2451. playStartTicks = engine.getTransport().positionTicks.load();
  2452. engine.startPlayback();
  2453. }
  2454. }
  2455. void MainComponent::playFromStart()
  2456. {
  2457. // FL 2026's Shift+Space (measured in FL, issue #11): playing, recording, waiting or counting in -> stop at the start
  2458. // of the time selection (Song mode) or else of the song / pattern; stopped -> play from the current position, as
  2459. // Space does (a later Space goes back there).
  2460. const auto wasPlaying = engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn();
  2461. if (! wasPlaying)
  2462. {
  2463. playStop();
  2464. return;
  2465. }
  2466. engine.stop();
  2467. const auto& song = engine.getSong();
  2468. const auto target = transportedit::shiftSpaceStopTarget (song.mode == PlayMode::song, song.hasLoop(), song.loopStart);
  2469. if (target > 0)
  2470. engine.seek ((double) target);
  2471. else
  2472. engine.rewind();
  2473. playStartTicks = (double) target;
  2474. }
  2475. void MainComponent::stopAndRewind (bool toStart)
  2476. {
  2477. // Stop while nothing plays (the second press, or a double click) goes back to the very start even when
  2478. // "Remember seek time" sends the first Stop to the ruler mark (round 162, issue #9)
  2479. const auto alreadyStopped = toStart || ! (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn());
  2480. engine.stop();
  2481. // FL: the transport's Stop also ends a Browser sample preview (issue #11)
  2482. browser.stopPreview(); // (the engine's one preview voice: the Sample browser window's preview stops too)
  2483. const auto& globals = EditorGlobals::get();
  2484. const auto back = transportedit::stopTarget (alreadyStopped, globals.rememberSeek && engine.getSong().mode == PlayMode::song, globals.seekMark);
  2485. if (back > 0) // "Remember seek time": back to the position clicked on the Playlist ruler
  2486. engine.seek ((double) back);
  2487. else
  2488. engine.rewind();
  2489. playStartTicks = (double) back;
  2490. }
  2491. void MainComponent::showStopMenu()
  2492. {
  2493. auto& globals = EditorGlobals::get();
  2494. juce::PopupMenu menu;
  2495. menu.addSectionHeader (tr ("Stop"));
  2496. menu.addItem (tr ("Remember seek time: Stop goes back to the position clicked on the Playlist ruler"), true, globals.rememberSeek, [this] {
  2497. EditorGlobals::get().rememberSeek = ! EditorGlobals::get().rememberSeek;
  2498. saveUiSettings();
  2499. });
  2500. menu.addSeparator();
  2501. menu.addItem (tr ("All notes off (panic)") + "\t" + tr ("double-click"), [this] { engine.panic(); });
  2502. menu.addItem (tr ("Back to the start"), [this] { stopAndRewind (true); });
  2503. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&stopButton));
  2504. }
  2505. void MainComponent::toggleMode()
  2506. {
  2507. engine.editSong ([] (Song& s) { s.mode = s.mode == PlayMode::song ? PlayMode::pattern : PlayMode::song; }, false);
  2508. }
  2509. // --- panels --------------------------------------------------------------------------------------
  2510. void MainComponent::togglePanel (Panel panel)
  2511. {
  2512. workspace.toggle (panel);
  2513. refreshPanelButtons();
  2514. }
  2515. void MainComponent::fitChannelRack (bool width)
  2516. {
  2517. rack.updateSize();
  2518. const auto scrollbar = rackViewport.getScrollBarThickness();
  2519. // compact like FL's rack: at most two bars of steps are shown, longer patterns scroll sideways, so the
  2520. // rack does not cover the Playlist after a project with long patterns is opened
  2521. // and never past the desktop's right edge from where the rack is (the default layout keeps the Playlist's track
  2522. // names uncovered on a small desktop, round 167v)
  2523. const auto maxWidth = juce::jmin (juce::jmax (300, workspace.getWidth() - 16 - workspace.getPanelBounds (Panel::channelRack).getX() - scrollbar - 8), rack.widthForSteps (32));
  2524. const auto contentWidth = juce::jmin (rack.naturalWidth(), maxWidth); // the ghost steps only fill a wider rack
  2525. const auto needsHorizontal = rack.naturalWidth() > contentWidth;
  2526. workspace.fitPanelContent (Panel::channelRack, width ? contentWidth + scrollbar : 0, rack.getHeight() + (needsHorizontal ? scrollbar : 0));
  2527. fittedChannelCount = (int) engine.getSong().channels.size();
  2528. }
  2529. void MainComponent::showPanel (Panel panel)
  2530. {
  2531. workspace.show (panel);
  2532. refreshPanelButtons();
  2533. }
  2534. void MainComponent::showWindowsTip()
  2535. {
  2536. const auto counter = PluginHost::settingsFolder().getChildFile ("windows-tip.txt");
  2537. const auto shown = counter.existsAsFile() ? counter.loadFileAsString().trim().getIntValue() : 0;
  2538. if (shown >= 3)
  2539. return;
  2540. counter.replaceWithText (juce::String (shown + 1));
  2541. auto key = [this] (Panel p) {
  2542. const auto chords = keyMap.chordsFor (panelAction (p));
  2543. return chords.empty() ? juce::String() : "[" + juce::String (keys::toString (chords.front())) + "] ";
  2544. };
  2545. ui::Hint hint;
  2546. 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)",
  2547. { key (Panel::playlist), key (Panel::channelRack), key (Panel::pianoRoll), key (Panel::mixer), key (Panel::browser) });
  2548. ui::postHint (hint, 15000);
  2549. }
  2550. void MainComponent::refreshPanelButtons()
  2551. {
  2552. for (int i = 0; i < workspace::panelCount; ++i)
  2553. panelButtons[(std::size_t) i].setToggleState (workspace.isPanelVisible ((Panel) i), juce::dontSendNotification);
  2554. }
  2555. void MainComponent::openPianoRoll()
  2556. {
  2557. showPanel (Panel::pianoRoll);
  2558. pianoRoll.scrollToNotes();
  2559. }
  2560. void MainComponent::saveLayoutAs()
  2561. {
  2562. auto* window = new juce::AlertWindow (tr ("Save layout as"), tr ("Name of the layout:"), juce::MessageBoxIconType::NoIcon);
  2563. window->addTextEditor ("name", tr ("My layout"));
  2564. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  2565. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  2566. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  2567. const auto name = window->getTextEditorContents ("name").trim();
  2568. if (result == 1 && name.isNotEmpty())
  2569. workspace.saveLayoutAs (name);
  2570. }),
  2571. true);
  2572. keepAboveMainWindow (*window);
  2573. }
  2574. juce::PopupMenu MainComponent::layoutsMenu()
  2575. {
  2576. juce::PopupMenu menu;
  2577. auto files = Workspace::layoutsFolder().findChildFiles (juce::File::findFiles, false, "*.txt");
  2578. files.sort();
  2579. for (const auto& file : files)
  2580. menu.addItem (file.getFileNameWithoutExtension(), [this, file] {
  2581. workspace.loadLayout (file);
  2582. refreshPanelButtons();
  2583. });
  2584. if (files.isEmpty())
  2585. menu.addItem (tr ("(none saved yet)"), false, false, [] {});
  2586. menu.addSeparator();
  2587. menu.addItem (tr ("Open layouts folder"), [] {
  2588. Workspace::layoutsFolder().createDirectory();
  2589. Workspace::layoutsFolder().startAsProcess();
  2590. });
  2591. return menu;
  2592. }
  2593. namespace
  2594. {
  2595. // Both | Grid | Song, in the Playlist's title bar while Clip-launch workflow is on (round 181a)
  2596. class ClipGridSwitch final : public juce::Component
  2597. {
  2598. public:
  2599. static constexpr int width = 132;
  2600. explicit ClipGridSwitch (std::function<void (PlaylistArea::GridView)> pick)
  2601. {
  2602. const std::pair<juce::TextButton*, PlaylistArea::GridView> buttons[] { { &both, PlaylistArea::GridView::beside },
  2603. { &grid, PlaylistArea::GridView::grid },
  2604. { &song, PlaylistArea::GridView::song } };
  2605. both.setButtonText (tr ("Both"));
  2606. grid.setButtonText (tr ("Grid"));
  2607. song.setButtonText (tr ("Song"));
  2608. both.setToggleState (true, juce::dontSendNotification);
  2609. for (const auto& [button, view] : buttons)
  2610. {
  2611. addAndMakeVisible (*button);
  2612. button->setRadioGroupId (1181);
  2613. button->setClickingTogglesState (true);
  2614. // (the radio group also "clicks" the button it turns off)
  2615. button->onClick = [pick, view = view, button = button] {
  2616. if (button->getToggleState())
  2617. pick (view);
  2618. };
  2619. }
  2620. }
  2621. void show (PlaylistArea::GridView view)
  2622. {
  2623. (view == PlaylistArea::GridView::beside ? both : view == PlaylistArea::GridView::grid ? grid : song).setToggleState (true, juce::dontSendNotification);
  2624. }
  2625. void resized() override
  2626. {
  2627. auto r = getLocalBounds().reduced (0, 4);
  2628. const auto w = r.getWidth() / 3;
  2629. both.setBounds (r.removeFromLeft (w));
  2630. grid.setBounds (r.removeFromLeft (w));
  2631. song.setBounds (r);
  2632. }
  2633. private:
  2634. juce::TextButton both, grid, song;
  2635. };
  2636. } // namespace
  2637. void MainComponent::setLayoutStyle (layoutstyle::Style style, bool swapLayout)
  2638. {
  2639. using layoutstyle::Style;
  2640. const auto from = layoutStyle;
  2641. const auto partsReady = [this] (Style s) {
  2642. return s == Style::pattern || (s == Style::clipLaunch && clipGridView != nullptr) || (s == Style::simple && simpleWorkflow != nullptr);
  2643. };
  2644. if (style == from && partsReady (style))
  2645. return;
  2646. // each style's own parts are made the first time it is chosen (nothing of them exists in Pattern workflow)
  2647. if (style == Style::clipLaunch && clipGridView == nullptr)
  2648. {
  2649. clipGridView = makeClipGrid (engine);
  2650. clipGridSwitch = std::make_unique<ClipGridSwitch> ([this] (PlaylistArea::GridView view) { setClipGridView (view); });
  2651. makeDetailView();
  2652. }
  2653. if (style == Style::simple && simpleWorkflow == nullptr)
  2654. {
  2655. SimpleWorkflow::Host host;
  2656. host.setOverlay = [this] (juce::Component* c) { playlistArea.setOverlay (c); };
  2657. host.showKeys = [this] {
  2658. if (! isTouchKeyboardOpen()) // (round 190p: a new instrument can be played at once, with the mouse too)
  2659. toggleTouchKeyboard (engine);
  2660. };
  2661. host.setTitleAccessory = [this] (juce::Component* c, int width) { workspace.setTitleAccessory (Panel::playlist, c, width); };
  2662. host.showLoops = [this] {
  2663. if (findToolWindow ("sampleBrowser") == nullptr)
  2664. toggleSampleBrowser();
  2665. };
  2666. host.trackAdded = [this] (int track) { playlist.selectTrack (track); };
  2667. host.setSideDock = [this] (juce::Component* c, int width) { playlistArea.setSideDock (c, width); };
  2668. // round 190t: the Sampler tile's start folder, the Finish dock's "Save the song as a file", the backup status
  2669. host.sampleFolder = [this] { return browser.firstSampleFolder(); };
  2670. host.exportAudio = [this] (int format) { exportAudio (format); };
  2671. host.exportOtherApps = [this] { exportForOtherApps(); };
  2672. host.saveStatus = [this] { return simpleSaveStatus(); };
  2673. simpleWorkflow = std::make_unique<SimpleWorkflow> (engine, std::move (host));
  2674. // the Simple headers' "+FX" (until the dock's Effects tab, slice S5): the Mixer on that insert
  2675. playlist.onTrackEffects = [this] (int insert) {
  2676. workspace.show (Panel::mixer);
  2677. mixer.selectTrack (insert);
  2678. refreshPanelButtons();
  2679. };
  2680. playlist.onSimpleFilesDropped = [this] (const juce::StringArray& files, std::int64_t tick) {
  2681. if (simpleWorkflow != nullptr)
  2682. simpleWorkflow->dropFiles (files, tick);
  2683. };
  2684. }
  2685. if (from == Style::simple && style != Style::simple && simpleWorkflow != nullptr)
  2686. simpleWorkflow->left();
  2687. // the workspace layout is kept per style, so going back restores the Pattern layout exactly
  2688. const auto layoutFile = [] (Style s) { return platform::settingsFile (layoutstyle::workspaceFile (s)); };
  2689. if (persistent && swapLayout && style != from)
  2690. {
  2691. layoutFile (from).replaceWithText (workspace.getLayoutText());
  2692. if (const auto saved = layoutFile (style); saved.existsAsFile())
  2693. workspace.applyLayoutText (saved.loadFileAsString());
  2694. else if (style == Style::clipLaunch)
  2695. {
  2696. workspace.hide (Panel::channelRack); // one click away, on the toolbar
  2697. workspace.show (Panel::playlist);
  2698. }
  2699. else if (style == Style::simple)
  2700. {
  2701. // one window: the tracks and the timeline fill it; the other panels stay one click away (View, F5…F9)
  2702. for (auto panel : { Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser })
  2703. workspace.hide (panel);
  2704. workspace.show (Panel::playlist);
  2705. if (! workspace.isMaximised (Panel::playlist))
  2706. workspace.toggleMaximised (Panel::playlist);
  2707. }
  2708. refreshPanelButtons();
  2709. if (isShowing())
  2710. grabKeyboardFocus(); // (the new layout must not leave the keys in the Browser's search box)
  2711. }
  2712. // Clip-launch workflow shows the automation lanes; going back restores the user's setting
  2713. const auto clipLaunch = style == Style::clipLaunch;
  2714. if (clipLaunch != (from == Style::clipLaunch))
  2715. {
  2716. if (clipLaunch && swapLayout) // (at startup, the saved value holds)
  2717. lanesBeforeClipLaunch = autolanes::shown();
  2718. autolanes::setShown (clipLaunch || lanesBeforeClipLaunch);
  2719. playlist.repaint();
  2720. }
  2721. if (! clipLaunch && detailView != nullptr) // (round 183a: a docked Piano roll goes back to its panel)
  2722. detailView->releaseEditor();
  2723. layoutStyle = style;
  2724. if (clipGridView != nullptr || clipLaunch)
  2725. {
  2726. playlistArea.setClipGrid (clipLaunch ? clipGridView.get() : nullptr, PlaylistArea::GridView::beside);
  2727. // the detail view docks under the grid and the Playlist (round 183a); other workflows: nothing docked
  2728. if (detailView != nullptr)
  2729. detailView->setVisible (clipLaunch && DetailView::shownSetting);
  2730. playlistArea.setDetailView (clipLaunch ? detailView.get() : nullptr,
  2731. [this] (int available) { return detailView != nullptr ? detailView->heightFor (available) : 0; });
  2732. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  2733. flip->show (PlaylistArea::GridView::beside);
  2734. workspace.setTitleAccessory (Panel::playlist, clipLaunch ? clipGridSwitch.get() : nullptr, clipLaunch ? ClipGridSwitch::width : 0);
  2735. }
  2736. // the Simple workflow's track headers and no pattern picker (no-ops for the other two styles: nothing changes there)
  2737. playlist.setSimpleHeaders (style == Style::simple);
  2738. playlistArea.setPickerHidden (style == Style::simple);
  2739. if (style == Style::simple && simpleWorkflow != nullptr)
  2740. simpleWorkflow->entered(); // (after the grid's title accessory is gone: the Add track button takes its place)
  2741. // round 184a S11 (D15): the Key panel shows in the Simple and Clip-launch workflows, not in FL's Pattern workflow,
  2742. // until the user shows or hides it by hand
  2743. if (keyPanelFollowsStyle && toolbarLayout.isShown (toolbarlayout::Group::key) != (style != Style::pattern))
  2744. {
  2745. toolbarLayout.setShown (toolbarlayout::Group::key, style != Style::pattern);
  2746. resized();
  2747. repaint();
  2748. }
  2749. }
  2750. void MainComponent::addLayoutStyleItems (juce::PopupMenu& menu)
  2751. {
  2752. using layoutstyle::Style;
  2753. juce::PopupMenu styles;
  2754. const auto item = [this, &styles] (const juce::String& text, Style style) {
  2755. styles.addItem (text, true, layoutStyle == style, [this, style] {
  2756. setLayoutStyle (style);
  2757. saveUiSettings();
  2758. });
  2759. };
  2760. item (tr ("Pattern workflow (default)"), Style::pattern);
  2761. item (tr ("Clip-launch workflow"), Style::clipLaunch);
  2762. item (tr ("Simple workflow"), Style::simple);
  2763. menu.addSubMenu (tr ("Layout style"), styles);
  2764. // round 183a: the detail view's items, only in Clip-launch workflow (the reference DAW's View menu [SHOT] d05)
  2765. if (isClipLaunchWorkflow() && detailView != nullptr)
  2766. {
  2767. menu.addItem (tr ("Detail view") + shortcutText ("view.detailToggle"), true, DetailView::shownSetting, [this] { runAction ("view.detailToggle"); });
  2768. menu.addItem (tr ("Clip view") + shortcutText ("view.detailClip"), true, DetailView::shownSetting && ! DetailView::devicesPage,
  2769. [this] { runAction ("view.detailClip"); });
  2770. menu.addItem (tr ("Device view") + shortcutText ("view.detailDevices"), true, DetailView::shownSetting && DetailView::devicesPage,
  2771. [this] { runAction ("view.detailDevices"); });
  2772. menu.addItem (tr ("Switch between clip view and device view") + shortcutText ("view.detailSwitch"), [this] { runAction ("view.detailSwitch"); });
  2773. }
  2774. }
  2775. void MainComponent::makeDetailView()
  2776. {
  2777. DetailView::Hooks h;
  2778. // the out meter: the Mixer's own level while its strips are on screen (they take the peaks), else the peaks
  2779. h.levelOf = [this] (int insert, int side) {
  2780. return mixer.metersShowing() ? mixer.shownLevel (insert, side) : engine.getMeters().takePeak (insert, side);
  2781. };
  2782. h.toggleChannelWindow = [this] (int channel) { rack.toggleEditor (channel, true); };
  2783. h.selectInMixer = [this] (int insert) { mixer.selectTrack (insert); };
  2784. h.instrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); }; // (as on the Mixer)
  2785. h.openClip = [this] (int track, int scene) { openGridClip (track, scene); };
  2786. h.dockPianoRoll = [this] (int pattern) { return dockPianoRoll (pattern); };
  2787. h.undockPianoRoll = [this] { undockPianoRoll(); };
  2788. h.selectPattern = [this] (int pattern) { selectPattern (pattern); };
  2789. // any way the Piano roll panel comes up (F7, its button, a layout) takes the docked editor back first
  2790. workspace.onWillShow = [this] (Panel panel) {
  2791. if (panel == Panel::pianoRoll && pianoRollDocked)
  2792. {
  2793. undockPianoRoll();
  2794. if (detailView != nullptr)
  2795. detailView->editorTakenBack();
  2796. }
  2797. };
  2798. h.layoutChanged = [this] {
  2799. if (detailView != nullptr)
  2800. detailView->setVisible (isClipLaunchWorkflow() && DetailView::shownSetting);
  2801. playlistArea.resized();
  2802. saveUiSettings();
  2803. };
  2804. detailView = std::make_unique<DetailView> (engine, std::move (h));
  2805. setClipGridPickListener (*clipGridView, [this] (int track, int scene, GridPick pick) {
  2806. if (detailView == nullptr)
  2807. return;
  2808. detailView->showSelection (track, scene);
  2809. if (pick == GridPick::openClip)
  2810. detailView->setPage (DetailView::Page::clip);
  2811. else if (pick == GridPick::openTrack)
  2812. detailView->setPage (DetailView::Page::devices);
  2813. });
  2814. const auto selected = clipGridSelection (*clipGridView);
  2815. detailView->showSelection (selected.first, selected.second);
  2816. }
  2817. juce::Component* MainComponent::dockPianoRoll (int pattern)
  2818. {
  2819. if (pattern >= 0 && pattern < (int) engine.getSong().patterns.size() && pattern != engine.getSong().currentPattern)
  2820. selectPattern (pattern);
  2821. if (! pianoRollDocked)
  2822. {
  2823. if (workspace.isPanelVisible (Panel::pianoRoll))
  2824. {
  2825. workspace.hide (Panel::pianoRoll);
  2826. refreshPanelButtons();
  2827. }
  2828. workspace.releaseContent (Panel::pianoRoll);
  2829. pianoRollDocked = true;
  2830. pianoRollDockActive = false;
  2831. pianoRoll.setDocked (true); // (a short velocity lane and the keys fitted to the notes in the short dock)
  2832. dockClickWatcher.down = [this] (const juce::MouseEvent& e) {
  2833. pianoRollDockActive = e.eventComponent != nullptr && (e.eventComponent == &pianoRoll || pianoRoll.isParentOf (e.eventComponent));
  2834. };
  2835. juce::Desktop::getInstance().addGlobalMouseListener (&dockClickWatcher);
  2836. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<PianoRollComponent> (&pianoRoll)] {
  2837. if (safe != nullptr)
  2838. safe->scrollToNotes();
  2839. });
  2840. }
  2841. return &pianoRoll;
  2842. }
  2843. void MainComponent::undockPianoRoll()
  2844. {
  2845. if (! pianoRollDocked)
  2846. return;
  2847. pianoRollDocked = false;
  2848. pianoRollDockActive = false;
  2849. pianoRoll.setDocked (false);
  2850. juce::Desktop::getInstance().removeGlobalMouseListener (&dockClickWatcher);
  2851. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll); // (its panel has it again)
  2852. }
  2853. bool MainComponent::pianoRollKeysHere() const
  2854. {
  2855. return pianoRollDocked && pianoRollDockActive && pianoRoll.isShowing();
  2856. }
  2857. bool MainComponent::runDetailAction (const std::string& id)
  2858. {
  2859. if (! isClipLaunchWorkflow() || detailView == nullptr) // (Pattern workflow: the keys keep their old meaning)
  2860. return false;
  2861. if (id == "view.detailToggle")
  2862. {
  2863. DetailView::shownSetting = ! DetailView::shownSetting;
  2864. detailView->setVisible (DetailView::shownSetting);
  2865. playlistArea.resized();
  2866. saveUiSettings();
  2867. }
  2868. else if (id == "view.detailClip")
  2869. detailView->setPage (DetailView::Page::clip);
  2870. else if (id == "view.detailDevices")
  2871. detailView->setPage (DetailView::Page::devices);
  2872. else if (id == "view.detailSwitch")
  2873. detailView->togglePage();
  2874. else
  2875. return false;
  2876. return true;
  2877. }
  2878. void MainComponent::openGridClip (int track, int scene)
  2879. {
  2880. const auto& song = engine.getSong();
  2881. if (! song.clipGrid)
  2882. return;
  2883. const auto* clip = launcher::clipAt (*song.clipGrid, track, scene);
  2884. if (clip == nullptr)
  2885. return;
  2886. if (clip->kind == ClipKind::audio)
  2887. {
  2888. if (clip->channel >= 0 && clip->channel < (int) song.channels.size())
  2889. openAudioEditorForChannel (engine, clip->channel);
  2890. }
  2891. else if (clip->kind == ClipKind::pattern && clip->pattern >= 0 && clip->pattern < (int) song.patterns.size())
  2892. {
  2893. selectPattern (clip->pattern);
  2894. openPianoRoll();
  2895. }
  2896. }
  2897. void MainComponent::setClipGridView (PlaylistArea::GridView view)
  2898. {
  2899. if (clipGridView != nullptr)
  2900. playlistArea.setClipGrid (clipGridView.get(), view);
  2901. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  2902. flip->show (view);
  2903. }
  2904. void MainComponent::selectTabForSnapshot (int tab)
  2905. {
  2906. const Panel panels[] = { Panel::channelRack, Panel::pianoRoll, Panel::playlist, Panel::mixer };
  2907. const auto panel = panels[juce::jlimit (0, 3, tab)];
  2908. if (panel == Panel::pianoRoll)
  2909. {
  2910. const auto& song = engine.getSong();
  2911. std::vector<int> counts (song.channels.size(), 0);
  2912. for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
  2913. if (n.channel >= 0 && n.channel < (int) counts.size())
  2914. ++counts[(std::size_t) n.channel];
  2915. if (! counts.empty())
  2916. engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
  2917. }
  2918. // each view on its own: the panel maximized over the workspace
  2919. workspace.resetLayout();
  2920. workspace.show (panel);
  2921. workspace.toggleMaximised (panel);
  2922. refreshPanelButtons();
  2923. if (panel == Panel::pianoRoll)
  2924. pianoRoll.scrollToNotes();
  2925. if (panel == Panel::playlist)
  2926. playlist.resized(); // update the scrollbars for the loaded song
  2927. if (panel == Panel::mixer)
  2928. mixer.selectFirstTrackWithEffects();
  2929. }
  2930. void MainComponent::showDesktopForSnapshot (bool extraPanels)
  2931. {
  2932. workspace.resetLayout();
  2933. if (auto* stage = dynamic_cast<DanceStage*> (danceStage.get()))
  2934. stage->update(); // (the project's dancers now: no timer runs before the picture)
  2935. if (extraPanels)
  2936. {
  2937. workspace.show (Panel::mixer);
  2938. workspace.show (Panel::pianoRoll);
  2939. pianoRoll.scrollToNotes();
  2940. workspace.show (Panel::channelRack);
  2941. }
  2942. refreshPanelButtons();
  2943. }
  2944. void MainComponent::showPanelsForSnapshot (std::initializer_list<Panel> panels)
  2945. {
  2946. workspace.resetLayout();
  2947. for (const auto panel : panels)
  2948. workspace.show (panel);
  2949. refreshPanelButtons();
  2950. }
  2951. // --- patterns ------------------------------------------------------------------------------------
  2952. void MainComponent::selectPattern (int index)
  2953. {
  2954. if (index >= 0 && index < (int) engine.getSong().patterns.size() && index != engine.getSong().currentPattern)
  2955. engine.editSong ([index] (Song& s) { s.currentPattern = index; }, false);
  2956. }
  2957. void MainComponent::stepPatternFromSelector (int delta)
  2958. {
  2959. // FL's selector goes on past the last pattern (rack ops stepPatternCreating: one new empty pattern at most)
  2960. const auto& song = engine.getSong();
  2961. const auto last = (int) song.patterns.size() - 1;
  2962. if (delta > 0 && last >= 0 && song.currentPattern + delta > last && ! isPatternEmpty (song.patterns[(std::size_t) last]))
  2963. engine.editSong ([delta] (Song& s) { s.currentPattern = stepPatternCreating (s, delta); });
  2964. else
  2965. selectPattern (stepPattern (song, delta));
  2966. }
  2967. void MainComponent::nextEmptyPattern()
  2968. {
  2969. engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  2970. showRenamePattern (engine.getSong().currentPattern);
  2971. }
  2972. void MainComponent::deleteCurrentPattern()
  2973. {
  2974. // FL's Patterns › Delete (Ctrl+Shift+Del); the last pattern stays
  2975. if (engine.getSong().patterns.size() > 1)
  2976. engine.editSong ([] (Song& s) { s.removePattern (s.currentPattern); });
  2977. }
  2978. void MainComponent::insertPatternHere()
  2979. {
  2980. engine.editSong ([] (Song& s) { insertPattern (s, s.currentPattern, newPatternName (s)); });
  2981. }
  2982. // --- window menus ------------------------------------------------------------------------------
  2983. // Each window's own items, at the top of the menu in its title bar (FL keeps an editor's options in the
  2984. // small menu at the left of its title bar). Items run the key map's actions, so they show their keys.
  2985. void MainComponent::addPanelMenuItems (Panel panel, juce::PopupMenu& menu)
  2986. {
  2987. auto action = [this] (juce::PopupMenu& m, const char* id, const juce::String& text, bool enabled = true, bool ticked = false) {
  2988. m.addItem (text + shortcutText (id), enabled, ticked, [this, id] { runAction (id); });
  2989. };
  2990. auto zoomMenu = [&action] (const juce::String& prefix) {
  2991. juce::PopupMenu zoom;
  2992. const std::pair<const char*, const char*> items[] = {
  2993. { "zoomIn", TR_NOOP ("Zoom in") }, { "zoomOut", TR_NOOP ("Zoom out") }, { "zoom1", TR_NOOP ("Zoom: one bar") },
  2994. { "zoom2", TR_NOOP ("Zoom: four bars") }, { "zoom3", TR_NOOP ("Zoom: sixteen bars") },
  2995. { "zoomAll", TR_NOOP ("Zoom to show everything") }, { "zoomSelection", TR_NOOP ("Zoom to the selection") },
  2996. { "centrePlayhead", TR_NOOP ("Centre the view on the playhead") }
  2997. };
  2998. for (const auto& [id, text] : items)
  2999. if (const auto* a = keys::findAction ((prefix + id).toStdString())) // the key map holds the id strings
  3000. action (zoom, a->id, tr (text));
  3001. return zoom;
  3002. };
  3003. switch (panel)
  3004. {
  3005. case Panel::channelRack:
  3006. {
  3007. menu.addSubMenu (tr ("Pattern"), makePatternMenu());
  3008. menu.addSeparator();
  3009. action (menu, "rack.graphEditor", tr ("Graph lanes (velocity, pan, pitch...)"), true, rack.areGraphLanesShown());
  3010. action (menu, "rack.pianoRollView", tr ("Piano-roll view of all channels"), true, rack.isPianoRollView());
  3011. action (menu, "rack.rotateLeft", tr ("Rotate the selected channels' steps left"));
  3012. action (menu, "rack.rotateRight", tr ("Rotate the selected channels' steps right"));
  3013. juce::PopupMenu sort;
  3014. sort.addItem (tr ("By name"), [this] { rack.sortChannels (ChannelSort::name); });
  3015. sort.addItem (tr ("By color"), [this] { rack.sortChannels (ChannelSort::colour); });
  3016. sort.addItem (tr ("By mixer insert"), [this] { rack.sortChannels (ChannelSort::insert); });
  3017. sort.addItem (tr ("By type"), [this] { rack.sortChannels (ChannelSort::type); });
  3018. menu.addSubMenu (tr ("Sort channels"), sort);
  3019. menu.addItem (tr ("Select unused channels"), [this] { rack.selectUnused(); });
  3020. action (menu, "rack.groupSelected", tr ("Group selected..."));
  3021. menu.addSectionHeader (tr ("Options")); // (FL's SSMenu: "Mute removed steps" is in its Options part)
  3022. menu.addItem (tr ("Mute removed steps"), true, ChannelRackComponent::muteRemovedSteps, [this] {
  3023. ChannelRackComponent::muteRemovedSteps = ! ChannelRackComponent::muteRemovedSteps;
  3024. saveUiSettings();
  3025. });
  3026. break;
  3027. }
  3028. case Panel::playlist:
  3029. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  3030. workspace.toggleMaximised (Panel::playlist);
  3031. refreshPanelButtons();
  3032. });
  3033. menu.addSeparator();
  3034. // FL's Playlist menu › Edit and › Select (round 189e: FL's items and order; the clip items below moved there)
  3035. menu.addSubMenu (tr ("Edit"), playlist.editMenu());
  3036. menu.addSubMenu (tr ("Select"), playlist.selectMenu());
  3037. menu.addSeparator();
  3038. action (menu, "playlist.ripple", tr ("Ripple editing (resizing and deleting move the later clips)"), true, playlist.isRippleOn());
  3039. action (menu, "playlist.rippleDelete", tr ("Delete the selected clips and close the gaps"));
  3040. // FL's legacy Pattern Blocks (round 170f, issue #60): FL 10's "Enable legacy pattern blocks", per project here
  3041. action (menu, "playlist.patternBlocks", tr ("Pattern blocks (current project)"), true, engine.getSong().patternBlocksOn);
  3042. action (menu, "playlist.blocksToClips", tr ("Turn pattern blocks into clips"), ! engine.getSong().blocks.empty());
  3043. action (menu, "playlist.automationLanes", tr ("Automation lanes"), true, autolanes::shown()); // round 177b
  3044. action (menu, "playlist.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (false));
  3045. action (menu, "playlist.quantizeStarts", tr ("Quantize the clips' starts"));
  3046. action (menu, "playlist.quantizeHalf", tr ("Quantize the clips' starts 50% (halfway to the grid)"));
  3047. menu.addSubMenu (tr ("Picker panel"), picker.pickerMenu()); // (round 177d: FL's Playlist menu › Picker panel)
  3048. action (menu, "playlist.stretchMode", tr ("Stretch audio when resizing audio clips"), true, EditorGlobals::get().stretchOnResize);
  3049. {
  3050. // FL 2026's Playlist menu › View › Track headers (round 190w; [DFM] EEViewMenu, FL's defaults)
  3051. juce::PopupMenu view;
  3052. view.addSectionHeader (tr ("Track headers"));
  3053. auto option = [this, &view] (const juce::String& text, bool& setting) {
  3054. view.addItem (text, true, setting, [this, &setting] {
  3055. setting = ! setting;
  3056. playlist.headerOptionsChanged();
  3057. });
  3058. };
  3059. option (tr ("Show controls on audio tracks"), PlaylistComponent::showAudioTrackControls);
  3060. option (tr ("Show levels on audio tracks"), PlaylistComponent::showAudioTrackLevels);
  3061. option (tr ("Show levels on instrument tracks"), PlaylistComponent::showInstrumentTrackLevels);
  3062. menu.addSubMenu (tr ("View"), view);
  3063. }
  3064. {
  3065. juce::PopupMenu trackTools;
  3066. action (trackTools, "playlist.cloneTracks", tr ("Clone selected playlist track(s)"));
  3067. action (trackTools, "playlist.lockAllToContent", tr ("Lock all playlist tracks to content"));
  3068. action (trackTools, "playlist.unlockAllFromContent", tr ("Unlock all playlist tracks from content"));
  3069. action (trackTools, "playlist.resetEmptyTracks", tr ("Reset empty playlist tracks"));
  3070. action (trackTools, "playlist.collapseAllGroups", tr ("Collapse all grouped tracks"));
  3071. action (trackTools, "playlist.expandAllGroups", tr ("Expand all grouped tracks"));
  3072. menu.addSubMenu (tr ("Tools"), trackTools);
  3073. }
  3074. {
  3075. // FL's Playlist Tools › EERenderPLSelectionMenu, EEPLRenderAllTracksMenu, EEPLRenderAllTrackGroupsMenu (round 168e)
  3076. juce::PopupMenu consolidate;
  3077. action (consolidate, "tools.consolidateSelection", tr ("From selection start"));
  3078. action (consolidate, "tools.consolidateSelectionSongStart", tr ("From song start"));
  3079. menu.addSubMenu (tr ("Consolidate playlist selection"), consolidate);
  3080. menu.addSubMenu (tr ("Export all playlist tracks"), playlistTrackExportMenu (false));
  3081. menu.addSubMenu (tr ("Export all playlist track groups"), playlistTrackExportMenu (true));
  3082. }
  3083. menu.addSubMenu (tr ("Zoom"), zoomMenu ("playlist."));
  3084. menu.addSeparator();
  3085. // FL's Performance mode (round 165m)
  3086. action (menu, "playlist.performanceMode", tr ("Performance mode"), true, engine.getSong().performanceMode);
  3087. action (menu, "playlist.zoomPerformance", tr ("Zoom on performance clips"), engine.getSong().performanceZoneEnd() > 0);
  3088. action (menu, "playlist.perfClipProgress", tr ("Performance clip progress"), true, playlist.clipProgressShown());
  3089. action (menu, "playlist.perfTrackProgress", tr ("Performance track progress"), true, playlist.trackProgressShown());
  3090. break;
  3091. case Panel::pianoRoll:
  3092. {
  3093. juce::PopupMenu tools;
  3094. for (const auto* id : { "pianoRoll.riffMachine", "pianoRoll.chordProgression", "pianoRoll.articulate", "pianoRoll.quantize",
  3095. "pianoRoll.chop", "pianoRoll.arpeggiate", "pianoRoll.strum", "pianoRoll.flam", "pianoRoll.claw",
  3096. "pianoRoll.limit", "pianoRoll.flip", "pianoRoll.randomise", "pianoRoll.scaleLevels", "pianoRoll.lfo",
  3097. "pianoRoll.runLastScript" })
  3098. if (const auto* a = keys::findAction (id))
  3099. action (tools, a->id, tr (a->description));
  3100. menu.addSubMenu (tr ("Tools"), tools);
  3101. action (menu, "pianoRoll.quickQuantize", tr ("Quick quantize (starts and lengths)"));
  3102. action (menu, "pianoRoll.quantizeStarts", tr ("Quantize starts"));
  3103. action (menu, "pianoRoll.quantizeHalf", tr ("Quantize starts 50% (halfway to the grid)"));
  3104. action (menu, "pianoRoll.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (true));
  3105. menu.addSubMenu (tr ("Zoom"), zoomMenu ("pianoRoll."));
  3106. menu.addItem (tr ("Snap notes to the scale") + shortcutText ("pianoRoll.scaleSnap"), pianoRoll.hasScale(), pianoRoll.isScaleSnapOn(),
  3107. [this] { pianoRoll.setScaleSnap (! pianoRoll.isScaleSnapOn()); });
  3108. break;
  3109. }
  3110. case Panel::mixer:
  3111. action (menu, "mixer.moveLeft", tr ("Move the selected inserts left"));
  3112. action (menu, "mixer.moveRight", tr ("Move the selected inserts right"));
  3113. menu.addSeparator();
  3114. action (menu, "mixer.linkChannels", tr ("Link the selected channels to the selected insert"));
  3115. action (menu, "mixer.linkChannelsFrom", tr ("Link the selected channels to inserts starting from the selected one"));
  3116. action (menu, "mixer.selectLinkedChannels", tr ("Select the channels linked to the selected insert"));
  3117. break;
  3118. case Panel::browser:
  3119. action (menu, "browser.search", tr ("Search the Browser"));
  3120. browser.addViewItems (menu); // what it lists, which folders it shows (round 163)
  3121. menu.addItem (tr ("Add folder..."), [this] { browser.addUserFolder(); });
  3122. action (menu, "view.sampleBrowser", tr ("Sample browser (separate window)"));
  3123. menu.addSeparator();
  3124. // the search index (round 162, issue #9): searches read it; it follows changed folders by itself
  3125. menu.addSectionHeader (browser.searchIndexStatus());
  3126. menu.addItem (tr ("Refresh search index"), [this] { browser.refreshSearchIndex (false); });
  3127. menu.addItem (tr ("Rebuild search index"), [this] { browser.refreshSearchIndex (true); });
  3128. break;
  3129. default:
  3130. break;
  3131. }
  3132. }
  3133. // --- quick-add palette and history -------------------------------------------------------------
  3134. void MainComponent::togglePluginPicker()
  3135. {
  3136. // FL's ShowPluginPickerAction (F8): opens the picker over the main window, or closes it (REA_rodada169k §2.5)
  3137. if (pluginPickerView != nullptr)
  3138. {
  3139. auto old = std::move (pluginPickerView);
  3140. juce::MessageManager::callAsync ([keep = std::shared_ptr<juce::Component> (std::move (old))] {}); // (it may be on the stack)
  3141. return;
  3142. }
  3143. PluginPickerTargets targets;
  3144. auto safe = juce::Component::SafePointer<MainComponent> (this);
  3145. targets.addInstrument = [safe] (ChannelDef c) {
  3146. if (safe == nullptr)
  3147. return;
  3148. safe->rack.addChannel (std::move (c), true);
  3149. safe->showPanel (Panel::channelRack);
  3150. };
  3151. targets.addEffect = [safe] (EffectSlot slot) {
  3152. if (safe == nullptr)
  3153. return;
  3154. if (! safe->mixer.addEffectToSelected (std::move (slot)))
  3155. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin picker"), tr ("The selected insert has no free effect slot."));
  3156. else
  3157. {
  3158. safe->showPanel (Panel::mixer);
  3159. // FL opens the new effect's window (round 171c, its "insert effect plugin")
  3160. const auto track = safe->mixer.getSelectedTrack();
  3161. if (track >= 0 && track < (int) safe->engine.getSong().mixer.size())
  3162. safe->mixer.openSlotEditor (track, (int) safe->engine.getSong().mixer[(std::size_t) track].effects.size() - 1);
  3163. }
  3164. };
  3165. targets.close = [safe] {
  3166. if (safe != nullptr && safe->pluginPickerView != nullptr)
  3167. safe->togglePluginPicker();
  3168. };
  3169. targets.showMixer = [safe] { // (an effect dragged out of the picker: FL brings up the Mixer)
  3170. if (safe != nullptr)
  3171. safe->showPanel (Panel::mixer);
  3172. };
  3173. targets.openBrowser = [safe] (const std::string& category, bool generators) {
  3174. if (safe == nullptr)
  3175. return;
  3176. safe->showPanel (Panel::browser);
  3177. safe->browser.showPluginDatabase (category.empty() ? juce::String() : tr (category.c_str()), category.empty() ? -1 : (generators ? 1 : 0));
  3178. };
  3179. targets.dragOwner = [safe]() -> juce::Component* { return safe.getComponent(); };
  3180. pluginPickerView = makePluginPickerView (engine, std::move (targets));
  3181. // FL's picker form covers the work area of the main window's monitor, whatever the main window's size (round 175b:
  3182. // FL at 1280 × 720 in a 1920 screen still opens it over the whole screen), and lets the screen show through
  3183. const auto* top = getTopLevelComponent();
  3184. const auto& displays = juce::Desktop::getInstance().getDisplays();
  3185. const auto* display = displays.getDisplayForRect (top != nullptr ? top->getScreenBounds() : getScreenBounds());
  3186. const auto area = display != nullptr ? display->userArea : getScreenBounds();
  3187. takePluginPickerBackdrop (*pluginPickerView, area);
  3188. pluginPickerView->setBounds (area);
  3189. pluginPickerView->addToDesktop (0); // (no frame, not on the taskbar)
  3190. pluginPickerView->setVisible (true);
  3191. pluginPickerView->toFront (true);
  3192. pluginPickerView->grabKeyboardFocus();
  3193. }
  3194. void MainComponent::showQuickAdd()
  3195. {
  3196. QuickAddTargets targets;
  3197. targets.effectsFirst = workspace.getFocused() == Panel::mixer;
  3198. targets.addInstrument = [this] (ChannelDef c) {
  3199. rack.addChannel (std::move (c), true);
  3200. showPanel (Panel::channelRack);
  3201. };
  3202. targets.addEffect = [this] (EffectSlot slot) {
  3203. if (! mixer.addEffectToSelected (std::move (slot)))
  3204. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Quick-add palette"),
  3205. tr ("The selected insert has no free effect slot."));
  3206. else
  3207. showPanel (Panel::mixer);
  3208. };
  3209. openToolWindow (makeQuickAddPalette (engine, std::move (targets)), tr ("Quick-add palette"), "quickadd");
  3210. }
  3211. std::unique_ptr<juce::Component> MainComponent::makeQuickAddForSnapshot()
  3212. {
  3213. QuickAddTargets targets;
  3214. targets.addInstrument = [] (ChannelDef) {};
  3215. targets.addEffect = [] (EffectSlot) {};
  3216. return makeQuickAddPalette (engine, std::move (targets));
  3217. }
  3218. void MainComponent::showHistory()
  3219. {
  3220. if (auto* open = findToolWindow ("history"))
  3221. {
  3222. open->toFront (true);
  3223. return;
  3224. }
  3225. openToolWindow (makeHistoryPanel (engine), tr ("Undo history"), "history");
  3226. }
  3227. // --- recording options ---------------------------------------------------------------------------
  3228. void MainComponent::updateRecordQuantise()
  3229. {
  3230. // the global grid sets the record quantise; "none" and the zoom-dependent grids record as played
  3231. std::int64_t ticks = 0;
  3232. // (the grid is kept even with "Note start time" off: "Note end time" uses it too)
  3233. {
  3234. const auto& option = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  3235. if (option.kind == grid::Kind::ticks)
  3236. ticks = option.ticks;
  3237. else if (option.kind == grid::Kind::bar)
  3238. ticks = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  3239. }
  3240. if (engine.getRecordOptions().quantise != ticks || engine.getRecordOptions().quantiseStarts != recordQuantiseOn)
  3241. {
  3242. auto o = engine.getRecordOptions();
  3243. o.quantise = ticks;
  3244. o.quantiseStarts = recordQuantiseOn;
  3245. engine.setRecordOptions (o);
  3246. }
  3247. }
  3248. void MainComponent::addRecordQuantizeItems (juce::PopupMenu& menu)
  3249. {
  3250. const auto o = engine.getRecordOptions();
  3251. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  3252. auto options = engine.getRecordOptions();
  3253. change (options);
  3254. engine.setRecordOptions (options);
  3255. saveUiSettings();
  3256. };
  3257. // FL's record menu "Quantize" items (REA round 139), to the global snap
  3258. menu.addItem (tr ("Note start time"), ! o.toStepSequencer, recordQuantiseOn && ! o.toStepSequencer, [this] {
  3259. recordQuantiseOn = ! recordQuantiseOn;
  3260. updateRecordQuantise();
  3261. saveUiSettings();
  3262. });
  3263. menu.addItem (tr ("Note end time"), ! o.toStepSequencer, o.noteEnd == NoteEnd::quantize && ! o.toStepSequencer, [set] {
  3264. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::quantize ? NoteEnd::keepEnd : NoteEnd::quantize; });
  3265. });
  3266. menu.addItem (tr ("Leave note duration"), ! o.toStepSequencer, o.noteEnd == NoteEnd::keepLength && ! o.toStepSequencer, [set] {
  3267. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::keepLength ? NoteEnd::keepEnd : NoteEnd::keepLength; });
  3268. });
  3269. menu.addItem (tr ("Record to step sequencer"), true, o.toStepSequencer,
  3270. [set] { set ([] (AudioEngine::RecordOptions& r) { r.toStepSequencer = ! r.toStepSequencer; }); });
  3271. // FL's "Automations" (RecQuantizeAutomationsMenu, setting QuantizeAutomations; REA round 143): recorded automation
  3272. // points go to the snap
  3273. menu.addItem (tr ("Automations"), true, o.quantiseAutomation,
  3274. [set] { set ([] (AudioEngine::RecordOptions& r) { r.quantiseAutomation = ! r.quantiseAutomation; }); });
  3275. }
  3276. void MainComponent::addRecordOptions (juce::PopupMenu& menu)
  3277. {
  3278. const auto o = engine.getRecordOptions();
  3279. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  3280. auto options = engine.getRecordOptions();
  3281. change (options);
  3282. engine.setRecordOptions (options);
  3283. refreshRecordOptionButtons();
  3284. saveUiSettings();
  3285. };
  3286. juce::PopupMenu countIn;
  3287. countIn.addItem (tr ("Off"), true, o.countInBars == 0, [set] { set ([] (AudioEngine::RecordOptions& r) { r.countInBars = 0; }); });
  3288. for (int bars : { 1, 2, 4 })
  3289. countIn.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, o.countInBars == bars,
  3290. [set, bars] { set ([bars] (AudioEngine::RecordOptions& r) { r.countInBars = bars; }); });
  3291. menu.addSubMenu (tr ("Count-in") + shortcutText ("record.countIn"), countIn);
  3292. menu.addItem (tr ("Wait for the first note to start") + shortcutText ("record.waitForInput"), true, o.waitForInput,
  3293. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitForInput = ! r.waitForInput; }); });
  3294. menu.addItem (tr ("Loop record") + shortcutText ("record.loop"), true, o.loopRecord,
  3295. [set] { set ([] (AudioEngine::RecordOptions& r) { r.loopRecord = ! r.loopRecord; }); });
  3296. menu.addItem (tr ("After loop recording, only the last pass plays"), true, o.lastLoopPassPlays,
  3297. [set] { set ([] (AudioEngine::RecordOptions& r) { r.lastLoopPassPlays = ! r.lastLoopPassPlays; }); });
  3298. menu.addItem (tr ("Step edit") + shortcutText ("record.stepEdit"), true, engine.isStepEdit(), [this] { runAction ("record.stepEdit"); });
  3299. // round 170d: notes played during the count-in are kept; the ones just before the start go onto it
  3300. {
  3301. juce::PopupMenu catchMenu;
  3302. catchMenu.addItem (tr ("Off (keep their real time)"), true, o.catchWindow == 0,
  3303. [set] { set ([] (AudioEngine::RecordOptions& r) { r.catchWindow = 0; }); });
  3304. const std::pair<std::int64_t, const char*> windows[] = { { ppq / 8, TR_NOOP ("1/32 note") },
  3305. { ppq / 4, TR_NOOP ("1/16 note") },
  3306. { ppq / 2, TR_NOOP ("1/8 note") },
  3307. { ppq, TR_NOOP ("1/4 note") } };
  3308. for (const auto& [ticks, name] : windows)
  3309. catchMenu.addItem (tr (name), true, o.catchWindow == ticks,
  3310. [set, ticks = ticks] { set ([ticks] (AudioEngine::RecordOptions& r) { r.catchWindow = ticks; }); });
  3311. menu.addSubMenu (tr ("Notes played just before the start go onto it"), catchMenu);
  3312. }
  3313. menu.addItem (tr ("Played notes: compensate the output latency"), true, o.compensateOutput,
  3314. [set] { set ([] (AudioEngine::RecordOptions& r) { r.compensateOutput = ! r.compensateOutput; }); });
  3315. menu.addItem (tr ("Capture MIDI: the notes just played without recording into the pattern") + shortcutText ("record.captureMidi"),
  3316. [this] { runAction ("record.captureMidi"); });
  3317. // round 163: punch in/out on the loop region, pre-roll and post-roll (bars)
  3318. {
  3319. auto bars = [&set] (juce::PopupMenu& m, int now, std::function<void (AudioEngine::RecordOptions&, int)> apply) {
  3320. m.addItem (tr ("Off"), true, now == 0, [set, apply] { set ([apply] (AudioEngine::RecordOptions& r) { apply (r, 0); }); });
  3321. for (int n : { 1, 2, 4 })
  3322. m.addItem (n == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (n) }), true, now == n,
  3323. [set, apply, n] { set ([apply, n] (AudioEngine::RecordOptions& r) { apply (r, n); }); });
  3324. };
  3325. juce::PopupMenu pre, post;
  3326. bars (pre, o.preRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.preRollBars = n; });
  3327. bars (post, o.postRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.postRollBars = n; });
  3328. menu.addItem (tr ("Audio: punch in/out on the loop region (plays through it, keeps only the region)"), true, o.punchLoopRegion,
  3329. [set] { set ([] (AudioEngine::RecordOptions& r) { r.punchLoopRegion = ! r.punchLoopRegion; }); });
  3330. menu.addSubMenu (tr ("Audio: pre-roll (plays before the punch-in or the start position)"), pre);
  3331. menu.addSubMenu (tr ("Audio: post-roll (plays after the punch-out, then stops)"), post);
  3332. }
  3333. menu.addSeparator();
  3334. menu.addItem (tr ("Overdub: add to the pattern"), true, o.mode == RecordMode::overdub,
  3335. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::overdub; }); });
  3336. menu.addItem (tr ("Replace: a recorded channel's old notes are cleared"), true, o.mode == RecordMode::replace,
  3337. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::replace; }); });
  3338. menu.addSeparator();
  3339. {
  3340. juce::PopupMenu quantize;
  3341. addRecordQuantizeItems (quantize);
  3342. menu.addSubMenu (tr ("Quantize recorded notes to the global snap"), quantize);
  3343. }
  3344. menu.addItem (tr ("Song mode: place a pattern clip where recording starts"), true, o.placeSongClip,
  3345. [set] { set ([] (AudioEngine::RecordOptions& r) { r.placeSongClip = ! r.placeSongClip; }); });
  3346. }
  3347. void MainComponent::toggleRecording()
  3348. {
  3349. if (engine.isRecording())
  3350. {
  3351. engine.setRecording (false);
  3352. return;
  3353. }
  3354. if (! engine.getRecordOptions().askWhatToRecord || ! persistent)
  3355. {
  3356. engine.setRecording (true);
  3357. if (engine.getRecordOptions().startsPlayback && ! engine.getTransport().playing.load()) // FL's "Recording starts playback"
  3358. engine.startPlayback();
  3359. return;
  3360. }
  3361. juce::Component::SafePointer<MainComponent> safe (this);
  3362. showRecordChoiceDialog ([safe] (int choice, bool dontAsk) {
  3363. if (safe == nullptr)
  3364. return;
  3365. if (choice == recordChoiceAudioEditor)
  3366. {
  3367. openAudioEditorRecording (safe->engine);
  3368. if (! safe->engine.getTransport().playing.load())
  3369. safe->engine.play();
  3370. return;
  3371. }
  3372. auto o = safe->engine.getRecordOptions();
  3373. o.recordNotes = choice != recordChoiceAudio;
  3374. o.recordAudio = choice != recordChoiceNotes;
  3375. o.recordAutomation = choice != recordChoiceAudio;
  3376. if (dontAsk)
  3377. o.askWhatToRecord = false;
  3378. safe->engine.setRecordOptions (o);
  3379. if (dontAsk)
  3380. safe->saveUiSettings();
  3381. if (choice == recordChoiceAudio && safe->engine.getArmedInserts().empty())
  3382. safe->armSelectedInsertForAudio();
  3383. safe->engine.setRecording (true);
  3384. if (o.startsPlayback && ! safe->engine.getTransport().playing.load()) // FL's "Recording starts playback"
  3385. safe->engine.startPlayback();
  3386. });
  3387. }
  3388. // Round 163: the fastest way from "press record" to a clip on the Playlist — one key arms the selected insert (or the
  3389. // one with an input), records audio only (no question) and starts playback (count-in / pre-roll as set); pressed
  3390. // again it stops, and the take is on the Playlist.
  3391. void MainComponent::quickRecordAudio()
  3392. {
  3393. auto& transport = engine.getTransport();
  3394. if (engine.isRecording() && (transport.playing.load() || engine.isCountingIn() || engine.isWaitingForInput()))
  3395. {
  3396. engine.stop();
  3397. engine.setRecording (false);
  3398. return;
  3399. }
  3400. if (engine.getArmedInserts().empty())
  3401. armSelectedInsertForAudio();
  3402. if (engine.getArmedInserts().empty()) // no input yet: its menu is open, nothing to record
  3403. return;
  3404. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  3405. {
  3406. o.recordAudio = true;
  3407. engine.setRecordOptions (o);
  3408. }
  3409. engine.setRecording (true);
  3410. if (! transport.playing.load())
  3411. engine.startPlayback();
  3412. }
  3413. void MainComponent::armSelectedInsertForAudio()
  3414. {
  3415. const auto& mixer = engine.getSong().mixer;
  3416. // the selected insert, else the first one with an input, else a free one
  3417. auto target = this->mixer.getStripsForSnapshot().getSelectedTrack();
  3418. for (int t = 1; target <= 0 && t < (int) mixer.size(); ++t)
  3419. if (mixer[(std::size_t) t].inputChannel >= 0)
  3420. target = t;
  3421. if (target <= 0)
  3422. target = engine.getSong().nextFreeInsert();
  3423. if (target <= 0 || target >= (int) mixer.size())
  3424. return;
  3425. showPanel (Panel::mixer);
  3426. this->mixer.selectTrack (target);
  3427. if (engine.isInsertArmed (target))
  3428. return;
  3429. // this menu item says "(choose its input)": without one, the input menu comes first and arms after the choice
  3430. if (mixer[(std::size_t) target].inputChannel < 0)
  3431. mixerinput::showMenu (engine, target, &this->mixer, [this, target] { engine.setInsertArmed (target, true); });
  3432. else
  3433. mixerinput::toggleArm (engine, target, &this->mixer);
  3434. }
  3435. void MainComponent::showMetronomeMenu()
  3436. {
  3437. // FL 2026's right-click on the metronome button, as it is (REA round 165z-a2): the "Metronome sound" choice only,
  3438. // in FL's order. The volume trim is in Options, the count-in has its own button and the track the click plays
  3439. // through is in Settings › Audio › Mixer.
  3440. auto& transport = engine.getTransport();
  3441. juce::PopupMenu menu;
  3442. menu.addSectionHeader (tr ("Metronome sound"));
  3443. for (int i = 0; i < metronome::soundCount; ++i)
  3444. menu.addItem (tr (metronome::soundName (i)), true, metronome::clampSound (transport.metronomeSound.load()) == i, [this, i] {
  3445. engine.getTransport().metronomeSound.store (i);
  3446. saveUiSettings();
  3447. });
  3448. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&metronomeButton));
  3449. }
  3450. void MainComponent::showTypingPianoMenu()
  3451. {
  3452. // FL 2026's right-click on the typing keyboard button (KbToMIDIPopup, measured round 168t2): Root note C..B,
  3453. // Octave 2..6 (where the Z row starts), Options › Reset, Layout (FL's .scr names and order, core/KeyMap.h).
  3454. // FL's Reset (KbToMIDIResetClick 0x121ac70) releases the held notes and puts Root note C, Octave 4 and Layout Piano back.
  3455. static const char* const names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  3456. juce::PopupMenu menu;
  3457. menu.addSectionHeader (tr ("Root note"));
  3458. for (int r = 0; r < 12; ++r)
  3459. menu.addItem (names[r], true, typingRoot == r, [this, r] { typingRoot = r; saveUiSettings(); });
  3460. menu.addSectionHeader (tr ("Octave"));
  3461. for (int o = keys::typingpiano::minOctave; o <= keys::typingpiano::maxOctave; ++o)
  3462. menu.addItem (juce::String (o), true, typingOctave == o, [this, o] { typingOctave = o; saveUiSettings(); });
  3463. menu.addSectionHeader (tr ("Options"));
  3464. menu.addItem (tr ("Reset"), [this] {
  3465. heldKeys.releaseAll();
  3466. releaseTypingLaunches (true);
  3467. typingOctave = keys::typingpiano::defaultOctave;
  3468. typingRoot = 0;
  3469. typingLayout = keys::typingpiano::pianoLayout();
  3470. saveUiSettings();
  3471. });
  3472. menu.addSectionHeader (tr ("Layout"));
  3473. for (int l = 0; l < keys::typingpiano::layoutCount(); ++l) // (FL's file names, untranslated as in FL)
  3474. menu.addItem (keys::typingpiano::layoutName (l), true, typingLayout == l, [this, l] {
  3475. heldKeys.releaseAll(); // a held key's notes belong to the old layout
  3476. releaseTypingLaunches (true);
  3477. typingLayout = l;
  3478. saveUiSettings();
  3479. });
  3480. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&typingPianoButton));
  3481. }
  3482. void MainComponent::dumpScoreLog (int minutes)
  3483. {
  3484. const auto& song = engine.getSong();
  3485. scorelog::DumpOptions options;
  3486. options.minutes = minutes;
  3487. options.bpm = song.bpm;
  3488. options.beatsPerBar = song.beatsPerBar;
  3489. auto notes = scorelog::dump (engine.scoreLogSnapshot(), options);
  3490. // (channels deleted since the notes were played are left out)
  3491. notes.erase (std::remove_if (notes.begin(), notes.end(), [&song] (const Note& n) { return n.channel < 0 || n.channel >= (int) song.channels.size(); }),
  3492. notes.end());
  3493. if (notes.empty())
  3494. {
  3495. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Score logger"),
  3496. tr ("The score log is empty: no notes were played on a MIDI keyboard or the typing keyboard in that time."));
  3497. return;
  3498. }
  3499. auto apply = [this] (std::vector<Note> logged, bool replace) {
  3500. const auto count = logged.size();
  3501. engine.editSong ([&logged, replace] (Song& s) {
  3502. if (s.patterns.empty())
  3503. s.patterns.emplace_back();
  3504. s.currentPattern = juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern);
  3505. auto& pattern = s.patterns[(std::size_t) s.currentPattern];
  3506. if (replace)
  3507. pattern.notes.clear();
  3508. pattern.notes.insert (pattern.notes.end(), logged.begin(), logged.end());
  3509. pattern.sortNotes();
  3510. });
  3511. ui::postHint ({ tr ("Score log: {0} notes put in the pattern", { juce::String ((int) count) }), {}, false, false }, 4000);
  3512. };
  3513. const auto& patterns = song.patterns;
  3514. const auto current = song.currentPattern;
  3515. if (current < 0 || current >= (int) patterns.size() || patterns[(std::size_t) current].notes.empty())
  3516. {
  3517. apply (std::move (notes), false);
  3518. return;
  3519. }
  3520. auto box = juce::MessageBoxOptions()
  3521. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  3522. .withTitle (tr ("Score logger"))
  3523. .withMessage (tr ("The current pattern isn't empty. Do you want the score log to be merged, or to replace the current content?"))
  3524. .withButton (tr ("Merge"))
  3525. .withButton (tr ("Replace"))
  3526. .withButton (tr ("Cancel"));
  3527. juce::AlertWindow::showAsync (box, [apply, notes] (int result) mutable {
  3528. if (result == 1 || result == 2)
  3529. apply (std::move (notes), result == 2);
  3530. });
  3531. }
  3532. void MainComponent::showMetronomeVolume()
  3533. {
  3534. // a callout with the volume knob; the click plays at the new level at once (Transport::metronomeVolume)
  3535. struct VolumePanel final : public juce::Component
  3536. {
  3537. VolumePanel (MainComponent& m) : owner (m)
  3538. {
  3539. title.setText (tr ("Metronome volume"), juce::dontSendNotification);
  3540. title.setJustificationType (juce::Justification::centred);
  3541. addAndMakeVisible (title);
  3542. knob.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  3543. knob.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 120, 18);
  3544. knob.setRange (0.0, controls::maxUtilityVolume, 0.01);
  3545. knob.setDoubleClickReturnValue (true, 1.0);
  3546. knob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  3547. knob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  3548. knob.setValue (owner.engine.getTransport().metronomeVolume.load(), juce::dontSendNotification);
  3549. knob.onValueChange = [this] { owner.engine.getTransport().metronomeVolume.store ((float) knob.getValue()); };
  3550. knob.onDragEnd = [this] { owner.saveUiSettings(); };
  3551. ui::setHint (knob, tr ("Metronome volume: 100% is the default click level, up to 125% [2xLMB] 100%"));
  3552. addAndMakeVisible (knob);
  3553. setSize (170, 150);
  3554. }
  3555. ~VolumePanel() override { owner.saveUiSettings(); }
  3556. void resized() override
  3557. {
  3558. auto r = getLocalBounds().reduced (8);
  3559. title.setBounds (r.removeFromTop (20));
  3560. knob.setBounds (r);
  3561. }
  3562. MainComponent& owner;
  3563. juce::Label title;
  3564. juce::Slider knob;
  3565. };
  3566. juce::CallOutBox::launchAsynchronously (std::make_unique<VolumePanel> (*this), metronomeButton.getScreenBounds(), nullptr);
  3567. }
  3568. void MainComponent::openAudioEditorForSelection()
  3569. {
  3570. const auto& song = engine.getSong();
  3571. const auto channel = engine.getSelectedChannel();
  3572. if (juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  3573. {
  3574. const auto& c = song.channels[(std::size_t) channel];
  3575. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && ! c.samplePath.empty())
  3576. {
  3577. openAudioEditorForChannel (engine, channel);
  3578. return;
  3579. }
  3580. }
  3581. openAudioEditor (engine);
  3582. }
  3583. void MainComponent::showRecordMenu()
  3584. {
  3585. const auto o = engine.getRecordOptions();
  3586. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  3587. auto options = engine.getRecordOptions();
  3588. change (options);
  3589. engine.setRecordOptions (options);
  3590. saveUiSettings();
  3591. };
  3592. juce::PopupMenu menu;
  3593. menu.addSectionHeader (tr ("Recording filter"));
  3594. // FL's filter order (RecMenu, REA round 143): Automation, Notes, Audio
  3595. menu.addItem (tr ("Automation (the controls you move: automation clips in song mode, pattern events in pattern mode)"), true,
  3596. o.recordAutomation, [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAutomation = ! r.recordAutomation; }); });
  3597. menu.addItem (tr ("Notes (MIDI and PC keyboard) into the current pattern"), true, o.recordNotes,
  3598. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordNotes = ! r.recordNotes; }); });
  3599. menu.addItem (tr ("Audio of the armed mixer inserts (becomes Playlist clips)"), true, o.recordAudio,
  3600. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAudio = ! r.recordAudio; }); });
  3601. menu.addItem (tr ("Clips (Performance mode: the launched clips are written into the arrangement)"), true, o.recordClips,
  3602. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordClips = ! r.recordClips; }); });
  3603. menu.addItem (tr ("Ask what to record when recording starts"), true, o.askWhatToRecord,
  3604. [set] { set ([] (AudioEngine::RecordOptions& r) { r.askWhatToRecord = ! r.askWhatToRecord; }); });
  3605. // FL's "Options" section (REA round 134)
  3606. menu.addSectionHeader (tr ("Options"));
  3607. menu.addItem (tr ("Recording starts playback"), true, o.startsPlayback,
  3608. [set] { set ([] (AudioEngine::RecordOptions& r) { r.startsPlayback = ! r.startsPlayback; }); });
  3609. menu.addItem (tr ("Disarm on stop (recording switches off when playback stops)"), true, o.recordOffOnStop,
  3610. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordOffOnStop = ! r.recordOffOnStop; }); });
  3611. // LYNX's own (issue #16; FL has no such option): also in Mixer › Disk recording
  3612. menu.addItem (tr ("Disarm the inserts when recording stops"), true, o.disarmOnStop,
  3613. [set] { set ([] (AudioEngine::RecordOptions& r) { r.disarmOnStop = ! r.disarmOnStop; }); });
  3614. menu.addItem (tr ("Enable recording markers (Start / Stop recording markers in the Playlist)"), true, o.recordingMarkers,
  3615. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordingMarkers = ! r.recordingMarkers; }); });
  3616. // FL's "Quantize" section (REA round 139): to the global snap
  3617. menu.addSectionHeader (tr ("Quantize"));
  3618. addRecordQuantizeItems (menu);
  3619. menu.addItem (tr ("Record into the audio editor..."), [this] { openAudioEditor (engine); });
  3620. menu.addSeparator();
  3621. menu.addItem (tr ("Arm the selected mixer insert for audio (choose its input)..."), [this] { armSelectedInsertForAudio(); });
  3622. menu.addItem (tr ("Audio settings (input device)..."), [this] { openSettings ((int) SettingsPage::audio); });
  3623. menu.addItem (tr ("Open recordings folder"), [this] {
  3624. const auto folder = engine.getRecordingFolder();
  3625. folder.createDirectory();
  3626. folder.startAsProcess();
  3627. });
  3628. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  3629. menu.addSeparator();
  3630. addRecordOptions (menu);
  3631. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (recordMenuButton.isVisible() ? (juce::Component*) &recordMenuButton
  3632. : (juce::Component*) &recordButton));
  3633. }
  3634. void MainComponent::refreshRecordOptionButtons()
  3635. {
  3636. auto withKey = [this] (const juce::String& text, const char* id) {
  3637. const auto key = shortcutText (id).trim();
  3638. return key.isEmpty() ? text : text + " (" + key + ")";
  3639. };
  3640. const auto o = engine.getRecordOptions();
  3641. countInButton.setToggleState (o.countInBars > 0, juce::dontSendNotification);
  3642. countInButton.setTooltip (withKey (o.countInBars > 0 ? tr ("Count-in before recording: {0} bar(s)", { juce::String (o.countInBars) })
  3643. : tr ("Count-in before recording: off"),
  3644. "record.countIn"));
  3645. blendButton.setToggleState (o.mode == RecordMode::overdub, juce::dontSendNotification);
  3646. {
  3647. const auto blend = o.mode == RecordMode::overdub;
  3648. auto tip = blend ? tr ("Blend recorded notes: on (new notes join the pattern's notes)")
  3649. : tr ("Blend recorded notes: off (a recorded channel's old notes are replaced)");
  3650. if (! o.lastLoopPassPlays)
  3651. tip << "\n" << (blend ? tr ("Loop-recorded audio: every pass plays") : tr ("Loop-recorded audio: every pass is muted"));
  3652. blendButton.setTooltip (tip);
  3653. }
  3654. waitInputButton.setToggleState (o.waitForInput, juce::dontSendNotification);
  3655. waitInputButton.setTooltip (withKey (o.waitForInput ? tr ("Recording waits for the first note: on") : tr ("Recording waits for the first note: off"),
  3656. "record.waitForInput"));
  3657. blendButton.setTooltip (withKey (blendButton.getTooltip(), "record.blend"));
  3658. loopRecordButton.setToggleState (o.loopRecord, juce::dontSendNotification);
  3659. 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)")
  3660. : tr ("Loop record: off (recording plays straight on: through the loop region, or past the pattern's end, which grows)"),
  3661. "record.loop"));
  3662. stepEditButton.setToggleState (engine.isStepEdit(), juce::dontSendNotification);
  3663. stepEditButton.setTooltip (withKey (engine.isStepEdit() ? tr ("Step edit: on (stopped, played notes go into the pattern one snap step after another)")
  3664. : tr ("Step edit: off"),
  3665. "record.stepEdit"));
  3666. punchButton.setToggleState (o.punchLoopRegion, juce::dontSendNotification);
  3667. punchButton.setTooltip (withKey (o.punchLoopRegion ? tr ("Punch in/out: on (audio is kept only inside the loop region)") : tr ("Punch in/out: off"),
  3668. "record.punch"));
  3669. }
  3670. void MainComponent::clonePatternNow()
  3671. {
  3672. engine.editSong ([] (Song& s) { clonePattern (s, s.currentPattern); });
  3673. }
  3674. void MainComponent::movePatternNow (int delta)
  3675. {
  3676. engine.editSongPatternOrder ([delta] (Song& s) { movePattern (s, s.currentPattern, delta); });
  3677. }
  3678. void MainComponent::splitPatternByChannelNow()
  3679. {
  3680. int created = 0;
  3681. engine.editSong ([&created] (Song& s) { created = splitPatternByChannel (s, s.currentPattern); });
  3682. if (created == 0)
  3683. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Split by channel"), tr ("This pattern has no notes."));
  3684. }
  3685. void MainComponent::showRenamePattern (int index)
  3686. {
  3687. if (index < 0 || index >= (int) engine.getSong().patterns.size())
  3688. return;
  3689. const auto& p = engine.getSong().patterns[(std::size_t) index];
  3690. showNameAndColourDialog (tr ("Rename pattern"), juce::String::fromUTF8 (p.name.c_str()), p.colour,
  3691. [this, index] (const juce::String& name, std::uint32_t colour) {
  3692. if (index < (int) engine.getSong().patterns.size())
  3693. engine.editSong ([index, n = name.toStdString(), colour] (Song& s) {
  3694. s.patterns[(std::size_t) index].name = n;
  3695. s.patterns[(std::size_t) index].colour = colour;
  3696. });
  3697. });
  3698. }
  3699. void MainComponent::refreshToolbar()
  3700. {
  3701. const auto& song = engine.getSong();
  3702. patternBox.clear (juce::dontSendNotification);
  3703. for (std::size_t i = 0; i < song.patterns.size(); ++i)
  3704. patternBox.addItem (juce::String::fromUTF8 (song.patterns[i].name.c_str()), (int) i + 1);
  3705. patternBox.setSelectedItemIndex (song.currentPattern, juce::dontSendNotification);
  3706. swingSlider.setValue (song.swing, juce::dontSendNotification);
  3707. tempoDisplay.repaint();
  3708. refreshModeButton();
  3709. refreshRackPatternSelector();
  3710. refreshRackLengthBox();
  3711. }
  3712. void MainComponent::refreshRackPatternSelector()
  3713. {
  3714. const auto& song = engine.getSong();
  3715. const auto valid = song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size();
  3716. const auto text = valid ? juce::String::fromUTF8 (song.patterns[(std::size_t) song.currentPattern].name.c_str()) : juce::String();
  3717. const auto colour = valid ? PlaylistComponent::patternColour (song, song.currentPattern) : juce::Colour();
  3718. if (text != rackPatternSelector.text || colour != rackPatternSelector.colour)
  3719. {
  3720. rackPatternSelector.text = text;
  3721. rackPatternSelector.colour = colour;
  3722. rackPatternSelector.repaint();
  3723. }
  3724. }
  3725. void MainComponent::showRackPatternList()
  3726. {
  3727. const auto& song = engine.getSong();
  3728. juce::PopupMenu menu;
  3729. for (int i = 0; i < (int) song.patterns.size(); ++i)
  3730. menu.addItem (juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()), true, i == song.currentPattern, [this, i] { selectPattern (i); });
  3731. menu.addSeparator();
  3732. menu.addItem (tr ("New pattern"), [this] { newPatternButton.onClick(); });
  3733. menu.addItem (tr ("Rename and color the pattern") + shortcutText ("pattern.rename"), [this] { runAction ("pattern.rename"); });
  3734. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackPatternSelector));
  3735. }
  3736. // --- the Channel Rack's pattern length box (issue #12) ---------------------------------------------------------
  3737. int MainComponent::PatternLengthBox::stepBars (int value, int delta)
  3738. {
  3739. static const int steps[] = { 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 };
  3740. constexpr int count = (int) (sizeof (steps) / sizeof (steps[0]));
  3741. int i = 0;
  3742. while (i + 1 < count && steps[i + 1] <= value)
  3743. ++i;
  3744. if (delta < 0 && steps[i] < value) // between two steps: going down lands on the lower one
  3745. ++delta;
  3746. return steps[juce::jlimit (0, count - 1, i + delta)];
  3747. }
  3748. void MainComponent::PatternLengthBox::paint (juce::Graphics& g)
  3749. {
  3750. using namespace theme;
  3751. const auto area = getLocalBounds().toFloat();
  3752. g.setColour (hovered ? colour::bg3 : colour::bg1);
  3753. g.fillRoundedRectangle (area, radius::sm);
  3754. g.setColour (hovered ? colour::borderStrong : colour::border);
  3755. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  3756. auto r = getLocalBounds().reduced (3, 0);
  3757. // round 170e: a length icon instead of the letters "A" / "L" (unreadable); dim = automatic (from the notes)
  3758. icons::draw (g, Icon::span, r.removeFromLeft (13).toFloat().withSizeKeepingCentre (13.0f, 13.0f),
  3759. automatic ? colour::textDisabled : colour::textSecondary);
  3760. g.setFont (font (type::small, true));
  3761. g.setColour (automatic ? colour::textSecondary : colour::textPrimary);
  3762. g.drawText (juce::String (bars), r, juce::Justification::centred, false);
  3763. }
  3764. void MainComponent::PatternLengthBox::mouseDown (const juce::MouseEvent& e)
  3765. {
  3766. dragStartBars = bars;
  3767. if (e.mods.isPopupMenu() && onMenu)
  3768. onMenu();
  3769. }
  3770. void MainComponent::PatternLengthBox::mouseDrag (const juce::MouseEvent& e)
  3771. {
  3772. if (e.mods.isPopupMenu() || onSet == nullptr)
  3773. return;
  3774. // one step of the list per 14 px up (as the rack's insert number box: drag up = more)
  3775. const auto delta = -e.getDistanceFromDragStartY() / 14;
  3776. const auto value = delta == 0 ? dragStartBars : stepBars (dragStartBars, delta);
  3777. if (value != bars || automatic)
  3778. if (delta != 0)
  3779. onSet (value);
  3780. }
  3781. void MainComponent::PatternLengthBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  3782. {
  3783. if (onSet != nullptr && wheel.deltaY != 0.0f)
  3784. onSet (stepBars (bars, wheel.deltaY > 0.0f ? 1 : -1));
  3785. }
  3786. void MainComponent::refreshRackLengthBox()
  3787. {
  3788. const auto& song = engine.getSong();
  3789. if (song.currentPattern < 0 || song.currentPattern >= (int) song.patterns.size())
  3790. return;
  3791. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  3792. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  3793. const auto bars = (int) juce::jmax<std::int64_t> (1, (pattern.effectiveLength (song.beatsPerBar) + bar - 1) / bar);
  3794. const auto automatic = pattern.lengthTicks == 0;
  3795. if (bars != rackLengthBox.bars || automatic != rackLengthBox.automatic)
  3796. {
  3797. rackLengthBox.bars = bars;
  3798. rackLengthBox.automatic = automatic;
  3799. rackLengthBox.setTooltip (automatic ? tr ("Pattern length: {0} (automatic, from the notes)", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) })
  3800. : tr ("Pattern length: {0}", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) }));
  3801. rackLengthBox.repaint();
  3802. }
  3803. }
  3804. void MainComponent::showPatternLengthMenu()
  3805. {
  3806. const auto& song = engine.getSong();
  3807. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  3808. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  3809. juce::PopupMenu menu;
  3810. menu.addSectionHeader (tr ("Pattern length"));
  3811. menu.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0, [this] { rackLengthBox.onSet (0); });
  3812. for (int bars : { 1, 2, 4, 8, 16, 32 })
  3813. menu.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == bars * bar,
  3814. [this, bars] { rackLengthBox.onSet (bars); });
  3815. menu.addSeparator();
  3816. menu.addItem (tr ("Type value..."), [this] {
  3817. ui::ValueSpec spec;
  3818. spec.name = tr ("Pattern length (bars, 0 = automatic)");
  3819. spec.minimum = 0.0;
  3820. spec.maximum = 999.0;
  3821. spec.interval = 1.0;
  3822. ui::typeValue (rackLengthBox, spec, rackLengthBox.automatic ? 0.0 : (double) rackLengthBox.bars,
  3823. [this] (double v) { rackLengthBox.onSet (juce::roundToInt (v)); });
  3824. });
  3825. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackLengthBox));
  3826. }
  3827. void MainComponent::PatternSelector::paint (juce::Graphics& g)
  3828. {
  3829. using namespace theme;
  3830. auto area = getLocalBounds().toFloat();
  3831. g.setColour (hoveredPart >= 0 ? colour::bg3 : colour::bg1);
  3832. g.fillRoundedRectangle (area, radius::sm);
  3833. g.setColour (hoveredPart >= 0 ? colour::borderStrong : colour::border);
  3834. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  3835. // the pattern's colour as a thin stripe at the left of the name
  3836. if (! colour.isTransparent())
  3837. {
  3838. g.setColour (colour);
  3839. g.fillRect (juce::Rectangle<float> ((float) arrowWidth + 1.0f, 4.0f, 3.0f, (float) getHeight() - 8.0f));
  3840. }
  3841. auto arrow = [&g, this] (int part, bool left) {
  3842. const auto box = juce::Rectangle<float> (left ? 0.0f : (float) (getWidth() - arrowWidth), 0.0f, (float) arrowWidth, (float) getHeight());
  3843. const auto c = box.getCentre();
  3844. juce::Path p;
  3845. if (left)
  3846. p.addTriangle (c.x + 2.5f, c.y - 4.0f, c.x + 2.5f, c.y + 4.0f, c.x - 2.5f, c.y);
  3847. else
  3848. p.addTriangle (c.x - 2.5f, c.y - 4.0f, c.x - 2.5f, c.y + 4.0f, c.x + 2.5f, c.y);
  3849. g.setColour (hoveredPart == part ? colour::textPrimary : colour::textSecondary);
  3850. g.fillPath (p);
  3851. };
  3852. arrow (0, true);
  3853. arrow (2, false);
  3854. g.setColour (colour::textPrimary);
  3855. g.setFont (font (type::small, true));
  3856. const auto name = getLocalBounds().withTrimmedLeft (arrowWidth + 7).withTrimmedRight (arrowWidth + 14);
  3857. g.drawText (text, name, juce::Justification::centredLeft, true);
  3858. icons::draw (g, Icon::chevronDown, juce::Rectangle<float> ((float) (getWidth() - arrowWidth - 14), 0.0f, 12.0f, (float) getHeight()).reduced (1.0f, 4.0f),
  3859. hoveredPart == 1 ? colour::textPrimary : colour::textSecondary);
  3860. g.setColour (colour::border);
  3861. g.fillRect (arrowWidth, 3, 1, getHeight() - 6);
  3862. g.fillRect (getWidth() - arrowWidth - 1, 3, 1, getHeight() - 6);
  3863. }
  3864. void MainComponent::PatternSelector::mouseDown (const juce::MouseEvent& e)
  3865. {
  3866. const auto part = partAt (e.x);
  3867. namePressed = dragging = false;
  3868. appliedSteps = 0;
  3869. if (e.mods.isPopupMenu())
  3870. {
  3871. if (onMenu)
  3872. onMenu();
  3873. }
  3874. else if (part == 1)
  3875. namePressed = true; // the list opens on release unless the mouse dragged (FL's pattern selector)
  3876. else if (onStep)
  3877. onStep (part == 0 ? -1 : 1);
  3878. }
  3879. void MainComponent::PatternSelector::mouseDrag (const juce::MouseEvent& e)
  3880. {
  3881. if (! namePressed)
  3882. return;
  3883. dragging = dragging || std::abs (e.getDistanceFromDragStartY()) >= patterndrag::threshold;
  3884. if (! dragging)
  3885. return;
  3886. const auto steps = patterndrag::steps ((float) e.getDistanceFromDragStartY());
  3887. if (steps != appliedSteps && onStep)
  3888. onStep (steps - appliedSteps);
  3889. appliedSteps = steps;
  3890. }
  3891. void MainComponent::PatternSelector::mouseUp (const juce::MouseEvent&)
  3892. {
  3893. if (namePressed && ! dragging && onMenu)
  3894. onMenu();
  3895. namePressed = dragging = false;
  3896. }
  3897. void MainComponent::PatternSelector::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  3898. {
  3899. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  3900. if (const auto n = wheelSteps.take (delta); n != 0 && onStep)
  3901. onStep (n);
  3902. }
  3903. void MainComponent::PatternBox::mouseDown (const juce::MouseEvent& e)
  3904. {
  3905. pressed = dragging = false;
  3906. appliedSteps = 0;
  3907. if (! isEnabled() || e.mods.isPopupMenu())
  3908. return;
  3909. pressed = true; // the list opens on release unless the mouse dragged (FL's pattern selector)
  3910. }
  3911. void MainComponent::PatternBox::mouseDrag (const juce::MouseEvent& e)
  3912. {
  3913. if (! pressed)
  3914. return;
  3915. dragging = dragging || std::abs (e.getDistanceFromDragStartY()) >= patterndrag::threshold;
  3916. if (! dragging)
  3917. return;
  3918. const auto steps = patterndrag::steps ((float) e.getDistanceFromDragStartY());
  3919. if (steps != appliedSteps && onStep)
  3920. onStep (steps - appliedSteps);
  3921. appliedSteps = steps;
  3922. }
  3923. void MainComponent::PatternBox::mouseUp (const juce::MouseEvent&)
  3924. {
  3925. if (pressed && ! dragging)
  3926. showPopup();
  3927. pressed = dragging = false;
  3928. }
  3929. void MainComponent::PatternBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  3930. {
  3931. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  3932. if (wheel.isInertial)
  3933. return;
  3934. if (const auto n = wheelSteps.take (delta); n != 0 && onStep)
  3935. onStep (n);
  3936. }
  3937. juce::PopupMenu MainComponent::playlistTrackExportMenu (bool groups)
  3938. {
  3939. // FL: From song start... / From track start... / Time selection... (the last does nothing without a time selection)
  3940. juce::PopupMenu menu;
  3941. auto add = [&] (const juce::String& text, quickrender::Start start, bool enabled) {
  3942. menu.addItem (text, enabled, false, [this, start, groups] { exportAllPlaylistTracks (engine, projectName, start, groups); });
  3943. };
  3944. add (tr ("From song start..."), quickrender::Start::songStart, true);
  3945. add (tr ("From track start..."), quickrender::Start::clipStart, true);
  3946. add (tr ("Time selection..."), quickrender::Start::timeSelection, engine.getSong().hasLoop());
  3947. return menu;
  3948. }
  3949. juce::PopupMenu MainComponent::makePatternMenu (std::vector<int> picked)
  3950. {
  3951. const auto& song = engine.getSong();
  3952. const auto index = song.currentPattern;
  3953. const auto& pattern = song.patterns[(std::size_t) index];
  3954. auto colours = ui::colourMenu (pattern.colour, [this, index] (std::uint32_t c) {
  3955. if (index < (int) engine.getSong().patterns.size())
  3956. engine.editSong ([index, c] (Song& s) { s.patterns[(std::size_t) index].colour = c; });
  3957. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1));
  3958. juce::PopupMenu lengths;
  3959. lengths.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0,
  3960. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = 0; }); });
  3961. for (int bars : { 1, 2, 4, 8, 16, 32 })
  3962. {
  3963. const auto ticks = (std::int64_t) bars * ppq * juce::jmax (1, song.beatsPerBar);
  3964. lengths.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == ticks,
  3965. [this, index, ticks] { engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; }); });
  3966. }
  3967. juce::PopupMenu menu;
  3968. // a double-click on the title renames the pattern (issue #12)
  3969. ui::addItemHeader (menu, tr ("Pattern"), juce::String::fromUTF8 (pattern.name.c_str()), PlaylistComponent::patternColour (song, index),
  3970. [this, index] { showRenamePattern (index); });
  3971. menu.addItem (tr ("Next pattern") + shortcutText ("pattern.next"), index + 1 < (int) song.patterns.size(), false,
  3972. [this] { selectPattern (stepPattern (engine.getSong(), 1)); });
  3973. menu.addItem (tr ("Previous pattern") + shortcutText ("pattern.previous"), index > 0, false,
  3974. [this] { selectPattern (stepPattern (engine.getSong(), -1)); });
  3975. menu.addItem (tr ("First empty pattern (and name it)") + shortcutText ("pattern.firstEmpty"), [this] { runAction ("pattern.firstEmpty"); });
  3976. menu.addItem (tr ("Next empty pattern (and name it)") + shortcutText ("pattern.nextEmpty"), [this] { nextEmptyPattern(); });
  3977. menu.addItem (tr ("Next empty pattern (no naming)") + shortcutText ("pattern.nextEmptyNoName"), [this] { runAction ("pattern.nextEmptyNoName"); });
  3978. menu.addSeparator();
  3979. menu.addItem (tr ("Rename and color...") + shortcutText ("pattern.rename"), [this, index] { showRenamePattern (index); });
  3980. menu.addSubMenu (tr ("Color"), colours);
  3981. menu.addSubMenu (tr ("Length"), lengths);
  3982. menu.addItem (tr ("Insert an empty pattern before this one") + shortcutText ("pattern.insert"), [this] { insertPatternHere(); });
  3983. menu.addItem (tr ("Clone") + shortcutText ("pattern.clone"), [this] { clonePatternNow(); });
  3984. menu.addItem (tr ("Move up") + shortcutText ("pattern.moveUp"), index > 0, false, [this] { movePatternNow (-1); });
  3985. menu.addItem (tr ("Move down") + shortcutText ("pattern.moveDown"), index + 1 < (int) song.patterns.size(), false, [this] { movePatternNow (1); });
  3986. menu.addItem (tr ("Split by channel (one new pattern per channel)"), ! pattern.notes.empty(), false, [this] { splitPatternByChannelNow(); });
  3987. // FL's Patterns › PSPatQuickRenderMenu / PSPatRenderMenu / PSPatRenderReplaceMenu (PSPatQuickRenderMenuClick, tags 1 / 0 / 2;
  3988. // REA round 168e); opened from the picker, every picked pattern is rendered (round 169k)
  3989. if (picked.empty())
  3990. picked = { index };
  3991. menu.addItem (tr ("Quick render as audio clip"), [this, picked] { renderPatternsAsAudioClips (engine, picked, 1); });
  3992. menu.addItem (tr ("Render as audio clip..."), [this, picked] { renderPatternsAsAudioClips (engine, picked, 0); });
  3993. menu.addItem (tr ("Render and replace..."), [this, picked] { renderPatternsAsAudioClips (engine, picked, 2); });
  3994. juce::PopupMenu signatures;
  3995. for (int beats : { 2, 3, 4, 5, 6, 7, 8, 9, 12 })
  3996. signatures.addItem (juce::String (beats) + "/4", true, song.beatsPerBar == beats,
  3997. [this, beats] { engine.editSong ([beats] (Song& s) { s.beatsPerBar = beats; }); });
  3998. menu.addSubMenu (tr ("Song time signature"), signatures);
  3999. menu.addSeparator();
  4000. menu.addItem (tr ("Delete pattern") + shortcutText ("pattern.delete"), song.patterns.size() > 1, false,
  4001. [this, index] { engine.editSong ([index] (Song& s) { s.removePattern (index); }); });
  4002. return menu;
  4003. }
  4004. void MainComponent::showPatternMenu()
  4005. {
  4006. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patternMenuButton));
  4007. }
  4008. void MainComponent::refreshModeButton()
  4009. {
  4010. const auto recording = engine.isRecording();
  4011. recordButton.setToggleState (recording, juce::dontSendNotification);
  4012. const auto inputs = engine.getActiveMidiInputs();
  4013. recordButton.setTooltip ((engine.isAudioRecordingArmed() ? tr ("Record while playing: notes (PC keyboard and MIDI) and input audio")
  4014. : tr ("Record while playing: notes (PC keyboard and MIDI)"))
  4015. + "\n" + tr ("MIDI inputs: {0}", { inputs.isEmpty() ? tr ("none") : inputs.joinIntoString (", ") }));
  4016. recordMenuButton.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  4017. recordMenuButton.setOnColour (theme::colour::accentMuted);
  4018. const auto songMode = engine.getSong().mode == PlayMode::song;
  4019. patternModeButton.setToggleState (! songMode, juce::dontSendNotification);
  4020. songModeButton.setToggleState (songMode, juce::dontSendNotification);
  4021. metronomeButton.setToggleState (engine.getTransport().metronome.load(), juce::dontSendNotification);
  4022. multilinkButton.setToggleState (engine.isMultilinkOn(), juce::dontSendNotification);
  4023. }
  4024. void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  4025. {
  4026. // round 190ap: the title says while third-party plugins are off; the last one switched on takes the note away
  4027. if (const auto off = engine.pluginsOff(); off != shownPluginsOff)
  4028. {
  4029. shownPluginsOff = off;
  4030. updateTitle();
  4031. }
  4032. if (const auto notice = engine.takeRecordingNotice(); notice.issue != AudioEngine::InputIssue::none && persistent)
  4033. mixerinput::explain (notice);
  4034. // round 165c: hardware inserts measured for another device setup (the device or its buffer size changed, or the project
  4035. // was measured elsewhere): a prompt that pings them on request, nothing pinged by itself (pings make clicks)
  4036. if (auto stale = engine.takeHardwareInsertNotice(); ! stale.empty() && persistent)
  4037. {
  4038. const auto count = (int) stale.size();
  4039. auto options = juce::MessageBoxOptions()
  4040. .withIconType (juce::MessageBoxIconType::InfoIcon)
  4041. .withTitle (tr ("Hardware Insert"))
  4042. .withMessage ((count == 1 ? tr ("The round trip of a hardware insert was measured for another audio setup (the device or its "
  4043. "buffer size changed), so its return is no longer lined up with the rest of the mix.")
  4044. : tr ("The round trip of {0} hardware inserts was measured for another audio setup (the device or its "
  4045. "buffer size changed), so their returns are no longer lined up with the rest of the mix.",
  4046. { juce::String (count) }))
  4047. + "\n\n" + tr ("Ping now? Each one sends a few clicks out to its gear and listens for them on its return."))
  4048. .withButton (tr ("Ping now"))
  4049. .withButton (tr ("Later"));
  4050. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), stale = std::move (stale)] (int result) {
  4051. if (result == 1 && safe != nullptr)
  4052. safe->engine.pingHardwareInserts (stale);
  4053. });
  4054. }
  4055. const auto& song = engine.getSong();
  4056. // FL's Auto select linked modules [DECOMP FUN_00ffe510 -> FUN_011e84e0] (round 187a): selecting one channel selects
  4057. // its mixer track
  4058. if (const auto selected = engine.getSelectedChannel(); selected != lastLinkedChannel)
  4059. {
  4060. lastLinkedChannel = selected;
  4061. if (ChannelRackComponent::autoSelectLinked && selected >= 0 && selected < (int) song.channels.size() && engine.getSelectedChannels().size() == 1)
  4062. if (const auto insert = song.channels[(std::size_t) selected].mixerTrack; insert >= 0 && insert < (int) song.mixer.size()
  4063. && insert != mixer.getStripsForSnapshot().getSelectedTrack())
  4064. mixer.selectTrack (insert);
  4065. }
  4066. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr)
  4067. simpleWorkflow->songChanged(); // (an empty project opens on the New track chooser)
  4068. // FL's "Select first channel with notes when the pattern changes" (Settings › General, REA round 167j §5)
  4069. if (song.currentPattern != lastCurrentPattern)
  4070. {
  4071. const auto changedPattern = lastCurrentPattern >= 0;
  4072. lastCurrentPattern = song.currentPattern;
  4073. if (changedPattern && ChannelRackComponent::selectFirstChannelWithNotes)
  4074. if (const auto first = firstChannelWithNotes (song, song.currentPattern); first >= 0 && first != engine.getSelectedChannel())
  4075. engine.setSelectedChannel (first);
  4076. }
  4077. bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
  4078. for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
  4079. namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
  4080. refreshModeButton();
  4081. tempoDisplay.repaint();
  4082. // a project with other filter groups (or none): the rack's filter falls back to "All"
  4083. if (rack.getFilterGroup() >= (int) song.channelGroups.size())
  4084. rack.setFilterGroup (-1);
  4085. if (rackFilterBox.text != rack.filterName())
  4086. {
  4087. rackFilterBox.text = rack.filterName();
  4088. rackFilterBox.repaint();
  4089. }
  4090. if (rackLoopButton.getToggleState() != rack.isLoopingOn()) // (another pattern, undo)
  4091. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  4092. if ((int) song.channels.size() != fittedChannelCount && fittedChannelCount >= 0) // a row was added or removed
  4093. fitChannelRack (false);
  4094. refreshKeyPanel(); // (undo, another project; cheap: it repaints only on a change)
  4095. if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (swingSlider.getValue() - song.swing) > 1e-6)
  4096. refreshToolbar();
  4097. else
  4098. {
  4099. refreshRackPatternSelector(); // a new pattern colour
  4100. refreshRackLengthBox(); // (notes added: the automatic length grows)
  4101. }
  4102. }
  4103. // --- tempo display -------------------------------------------------------------------------------
  4104. ui::ValueSpec MainComponent::TempoDisplay::spec() const
  4105. {
  4106. ui::ValueSpec s;
  4107. s.name = tr ("Tempo");
  4108. s.minimum = minTempo;
  4109. s.maximum = maxTempo;
  4110. s.defaultValue = 130.0;
  4111. s.toText = [] (double v) { return juce::String (v, 3) + " BPM"; };
  4112. s.target = AutomationTarget { AutomationTargetKind::tempo, 0 };
  4113. return s;
  4114. }
  4115. void MainComponent::TempoDisplay::setBpm (double bpm)
  4116. {
  4117. bpm = controls::clampTempo (bpm);
  4118. if (std::abs (bpm - engine.getSong().bpm) > 1e-9)
  4119. engine.editSong ([bpm] (Song& s) { clipops::followTempo (s, bpm); });
  4120. repaint();
  4121. }
  4122. bool MainComponent::TempoDisplay::isOnDecimals (int x) const
  4123. {
  4124. return decimalX > 0 && x > decimalX;
  4125. }
  4126. void MainComponent::TempoDisplay::paint (juce::Graphics& g)
  4127. {
  4128. using namespace theme;
  4129. const auto area = getLocalBounds().toFloat();
  4130. g.setColour (colour::bg1);
  4131. g.fillRoundedRectangle (area, radius::md);
  4132. if (dragging)
  4133. {
  4134. g.setColour (colour::accent.withAlpha (0.6f));
  4135. g.drawRoundedRectangle (area.reduced (0.5f), radius::md, 1.0f);
  4136. }
  4137. const auto bpm = engine.getSong().bpm;
  4138. const auto whole = juce::String ((int) std::floor (bpm + 1e-9));
  4139. const auto fraction = juce::String (bpm - std::floor (bpm + 1e-9), 3).fromFirstOccurrenceOf (".", false, false).paddedRight ('0', 3).substring (0, 3);
  4140. const juce::Font big (monoFont (18.0f)), small (monoFont (11.0f)), caption (font (type::caption - 1.0f));
  4141. const auto wholeWidth = juce::GlyphArrangement::getStringWidth (big, whole);
  4142. const auto fracWidth = juce::GlyphArrangement::getStringWidth (small, "." + fraction);
  4143. const auto unitWidth = juce::GlyphArrangement::getStringWidth (caption, "BPM");
  4144. auto x = area.getCentreX() - (wholeWidth + fracWidth + 6.0f + unitWidth) / 2.0f;
  4145. const auto baseline = area.getCentreY() + 5.0f;
  4146. g.setColour (colour::textPrimary);
  4147. g.setFont (big);
  4148. g.drawSingleLineText (whole, juce::roundToInt (x), juce::roundToInt (baseline));
  4149. x += wholeWidth;
  4150. decimalX = juce::roundToInt (x);
  4151. g.setColour (dragOnDecimals && dragging ? colour::textPrimary : colour::textSecondary);
  4152. g.setFont (small);
  4153. g.drawSingleLineText ("." + fraction, juce::roundToInt (x), juce::roundToInt (baseline));
  4154. x += fracWidth + 6.0f;
  4155. g.setColour (colour::textDisabled);
  4156. g.setFont (caption);
  4157. g.drawSingleLineText ("BPM", juce::roundToInt (x), juce::roundToInt (baseline));
  4158. }
  4159. void MainComponent::TempoDisplay::mouseDown (const juce::MouseEvent& e)
  4160. {
  4161. if (e.mods.isPopupMenu())
  4162. {
  4163. showMenu();
  4164. return;
  4165. }
  4166. if (ui::isResetClick (e))
  4167. {
  4168. setBpm (spec().defaultValue);
  4169. return;
  4170. }
  4171. startBpm = engine.getSong().bpm;
  4172. dragOnDecimals = isOnDecimals (e.x);
  4173. dragging = true;
  4174. repaint();
  4175. }
  4176. void MainComponent::TempoDisplay::mouseDrag (const juce::MouseEvent& e)
  4177. {
  4178. if (dragging)
  4179. {
  4180. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  4181. setBpm (controls::tempoDrag (startBpm, -e.getDistanceFromDragStartY(), dragOnDecimals, e.mods.isCtrlDown()));
  4182. }
  4183. }
  4184. void MainComponent::TempoDisplay::mouseUp (const juce::MouseEvent&)
  4185. {
  4186. dragging = false;
  4187. repaint();
  4188. }
  4189. void MainComponent::TempoDisplay::mouseDoubleClick (const juce::MouseEvent& e)
  4190. {
  4191. if (! e.mods.isPopupMenu())
  4192. ui::typeValue (*this, spec(), engine.getSong().bpm, [this] (double v) { setBpm (v); });
  4193. }
  4194. void MainComponent::TempoDisplay::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  4195. {
  4196. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  4197. if (delta == 0.0f)
  4198. return;
  4199. const auto step = isOnDecimals (e.x) ? 0.01 : 1.0;
  4200. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  4201. setBpm (engine.getSong().bpm + (delta > 0.0f ? 1.0 : -1.0) * step * (e.mods.isCtrlDown() ? 0.1 : 1.0));
  4202. }
  4203. ui::Hint MainComponent::TempoDisplay::hintAt (juce::Point<int> p)
  4204. {
  4205. return ui::valueHint (spec(), engine.getSong().bpm,
  4206. isOnDecimals (p.x) ? tr ("[LMB] drag the decimals for fine changes [Wheel] 0.01 [2xLMB] type [RMB] tap tempo, half, double")
  4207. : tr ("[LMB] drag the whole number [Ctrl] fine [Wheel] 1 BPM [2xLMB] type [RMB] tap tempo, half, double"));
  4208. }
  4209. void MainComponent::TempoDisplay::showMenu()
  4210. {
  4211. const auto bpm = engine.getSong().bpm;
  4212. juce::PopupMenu menu;
  4213. menu.addSectionHeader (tr ("Tempo") + ": " + juce::String (bpm, 3) + " BPM");
  4214. menu.addItem (tr ("Type value..."), [this, bpm] { ui::typeValue (*this, spec(), bpm, [this] (double v) { setBpm (v); }); });
  4215. menu.addItem (tr ("Tempo tapper..."), [this] { showTap(); });
  4216. menu.addItem (tr ("Half ({0} BPM)", { juce::String (controls::halfTempo (bpm), 2) }), [this, bpm] { setBpm (controls::halfTempo (bpm)); });
  4217. menu.addItem (tr ("Double ({0} BPM)", { juce::String (controls::doubleTempo (bpm), 2) }), [this, bpm] { setBpm (controls::doubleTempo (bpm)); });
  4218. menu.addItem (tr ("Reset ({0})", { "130 BPM" }), [this] { setBpm (130.0); });
  4219. menu.addSeparator();
  4220. addAutomationItem (menu, engine, { AutomationTargetKind::tempo, 0 });
  4221. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  4222. }
  4223. void MainComponent::TempoDisplay::showTap()
  4224. {
  4225. openTempoTapper (engine); // FL's tempo menu opens its tempo tapper too
  4226. }
  4227. // --- hint bar ------------------------------------------------------------------------------------
  4228. juce::String MainComponent::idleHint() const
  4229. {
  4230. if (engine.isWaitingForInput())
  4231. return tr ("Recording: waiting for the first note ([Space] cancels)");
  4232. if (engine.isCountingIn())
  4233. return tr ("Recording: count-in...");
  4234. // FL's text while "Multilink to controllers" is on (round 177b-4); the controls moved show their own hint
  4235. if (engine.isMultilinkOn())
  4236. return tr ("Please tweak the controls you want to link...");
  4237. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.running)
  4238. return tr ("Scanning for plugins in the background: {0}% {1}", { juce::String (juce::roundToInt (scan.progress * 100.0f)), scan.file });
  4239. // round 170e3: one line at 1920 (the typing piano's state shows on its own button)
  4240. return tr ("Point at anything for help [F1] shortcuts [F5]-[F9] windows [Space] play/stop");
  4241. }
  4242. juce::String MainComponent::keyMarkup (const char* actionId) const
  4243. {
  4244. const auto& chords = keyMap.chordsFor (actionId);
  4245. if (chords.empty())
  4246. return {};
  4247. // "Ctrl+Shift+S" -> "[Ctrl][Shift][S]"; a key name that is not markup stays as text
  4248. const auto text = juce::String (keys::displayString (chords.front()));
  4249. juce::String out;
  4250. for (const auto& part : juce::StringArray::fromTokens (text, "+", ""))
  4251. {
  4252. if (! hintmarkup::isToken (part.toStdString()))
  4253. return "(" + text + ")";
  4254. out << "[" << part << "]";
  4255. }
  4256. return out;
  4257. }
  4258. void MainComponent::setControlHints()
  4259. {
  4260. auto with = [this] (const juce::String& text, const char* actionId) {
  4261. const auto key = keyMarkup (actionId);
  4262. return key.isEmpty() ? text : text + " " + key;
  4263. };
  4264. ui::setHint (newButton, with (tr ("New project"), "file.new"));
  4265. ui::setHint (openButton, with (tr ("Open a project (.lynx, FL Studio .flp, Ableton Live .als, FL Studio Mobile .flm, MIDI)"), "file.open"));
  4266. ui::setHint (saveButton, with (tr ("Save the project"), "file.save") + " " + tr ("save as:") + " " + keyMarkup ("file.saveAs"));
  4267. ui::setHint (exportButton, with (tr ("Export audio: WAV, FLAC or OGG"), "file.export"));
  4268. ui::setHint (undoButton, with (tr ("Undo the last edit"), "edit.undo") + " " + tr ("[RMB] undo history"), true);
  4269. ui::setHint (redoButton, with (tr ("Redo"), "edit.redo") + " " + tr ("[RMB] undo history"), true);
  4270. ui::setHint (pluginPickerButton, with (tr ("Plugin picker: add an instrument or an effect by name"), "panel.quickAdd"));
  4271. ui::setHint (playButton, with (tr ("Play: [LMB] play; again: stop and go back to where it started"), "transport.playStop")
  4272. + " " + keyMarkup ("transport.pause") + " " + tr ("pause"));
  4273. ui::setHint (stopButton, tr ("Stop: [LMB] stop and go back to the start (or the remembered position; again: the start) "
  4274. "[2xLMB] back to the start and all notes off (panic) [RMB] remember seek time")
  4275. + " " + keyMarkup ("tools.stopSound") + " " + tr ("Stop sound (all notes off)"), // round 170h2
  4276. true);
  4277. ui::setHint (recordButton, with (tr ("Record: [LMB] arm, then play to record notes (and audio, when armed) [RMB] what to record"), "transport.record"),
  4278. true);
  4279. ui::setHint (recordMenuButton, tr ("What to record: notes, input audio, count-in, overdub or replace, quantise [LMB] menu"), true);
  4280. ui::setHint (patternModeButton, with (tr ("Pattern mode: plays the current pattern in a loop [RMB] show the Channel Rack"), "transport.toggleMode"));
  4281. ui::setHint (songModeButton, with (tr ("Song mode: plays the Playlist arrangement [RMB] show the Playlist"), "transport.toggleMode"));
  4282. ui::setHint (metronomeButton, with (tr ("Metronome: clicks on every beat while playing [RMB] volume and options"), "transport.metronome"), true);
  4283. ui::setHint (countInButton, with (tr ("Count-in: one bar of clicks before recording starts (the menu has more lengths)"), "record.countIn"));
  4284. ui::setHint (waitInputButton, with (tr ("Wait for input: recording starts with the first note you play"), "record.waitForInput"));
  4285. 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"));
  4286. 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 "
  4287. "plays straight on, through the loop region or past the pattern's end, and keeps everything where it "
  4288. "was played (the pattern grows)"), "record.loop"));
  4289. ui::setHint (stepEditButton, with (tr ("Step edit: with the transport stopped, notes you play go into the current pattern at the position, "
  4290. "a snap step long; release the keys and the position moves on one step (chords: hold them together)"),
  4291. "record.stepEdit"));
  4292. ui::setHint (punchButton, with (tr ("Punch in/out: audio recording keeps only the loop region (playback runs through it; pre- and "
  4293. "post-roll in the recording options)"), "record.punch"));
  4294. ui::setHint (tapTempoButton, with (tr ("Tempo tapper: tap the beat to set the tempo"), "view.tempoTapper"));
  4295. ui::setHint (typingPianoButton, with (tr ("Typing keyboard to piano: Z..M and Q..P play the selected channels; letter shortcuts pause"),
  4296. "view.typingPiano"));
  4297. ui::setHint (snapToggleButton, tr ("Snap (magnet): [LMB] turns the snap off and back on (as [Backspace]); lit while it snaps. "
  4298. "The Playlist and Piano Roll snap boxes show the same magnet"));
  4299. ui::setHint (gridBox, tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  4300. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"),
  4301. true);
  4302. ui::setHint (patternBox, tr ("Current pattern: what the Channel Rack and Piano Roll edit and Pattern mode plays [LMB] choose [Wheel] step "
  4303. "[F4] next empty [F2] rename") + " " + tr ("[LMB] drag up / down: step through the patterns"));
  4304. ui::setHint (newPatternButton, tr ("New pattern: an empty pattern after the last one"));
  4305. ui::setHint (patternMenuButton, tr ("Pattern menu: rename, color, length, clone, insert, split by channel, delete"), true);
  4306. const char* panelHelp[] = { TR_NOOP ("the arrangement: clips of patterns, audio and automation on tracks"),
  4307. TR_NOOP ("the instruments and their step sequencer"),
  4308. TR_NOOP ("the notes of the selected channel in the current pattern"),
  4309. TR_NOOP ("inserts, effects and routing"),
  4310. TR_NOOP ("samples, presets, plugins and projects to drag in") };
  4311. for (int i = 0; i < workspace::panelCount; ++i)
  4312. ui::setHint (panelButtons[(std::size_t) i],
  4313. with (panelName ((Panel) i) + ": " + tr (panelHelp[i]) + " " + tr ("[LMB] show, focus or hide [RMB] maximized"),
  4314. panelAction ((Panel) i)));
  4315. setQuickTips();
  4316. }
  4317. std::vector<std::pair<juce::Rectangle<int>, juce::String>> MainComponent::getQuickTipsForSnapshot()
  4318. {
  4319. std::vector<std::pair<juce::Rectangle<int>, juce::String>> tips;
  4320. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  4321. for (auto* child : c.getChildren())
  4322. {
  4323. if (! child->isVisible())
  4324. continue;
  4325. if (const auto tip = ui::quickTipOf (*child); tip.isNotEmpty() && ! child->getBounds().isEmpty())
  4326. tips.emplace_back (getLocalArea (child->getParentComponent(), child->getBounds()), tip);
  4327. visit (*child);
  4328. }
  4329. };
  4330. visit (*this);
  4331. return tips;
  4332. }
  4333. // the small name bubble of every toolbar control (the hint bar keeps the full description)
  4334. void MainComponent::setQuickTips()
  4335. {
  4336. auto tip = [this] (juce::Component& c, const juce::String& name, const char* actionId = nullptr) {
  4337. ui::setQuickTip (c, name, actionId != nullptr ? shortcutText (actionId).trim() : juce::String());
  4338. };
  4339. tip (newButton, tr ("New project"), "file.new");
  4340. tip (openButton, tr ("Open project"), "file.open");
  4341. tip (saveButton, tr ("Save project"), "file.save");
  4342. tip (exportButton, tr ("Export audio"), "file.export");
  4343. tip (undoButton, tr ("Undo"), "edit.undo");
  4344. tip (redoButton, tr ("Redo"), "edit.redo");
  4345. tip (pluginPickerButton, tr ("Plugin picker"), "panel.quickAdd");
  4346. tip (playButton, tr ("Play"), "transport.playStop");
  4347. tip (stopButton, tr ("Stop"));
  4348. tip (recordButton, tr ("Record"), "transport.record");
  4349. tip (recordMenuButton, tr ("Recording options"));
  4350. tip (patternModeButton, tr ("Pattern mode"), "transport.toggleMode");
  4351. tip (songModeButton, tr ("Song mode"), "transport.toggleMode");
  4352. tip (metronomeButton, tr ("Metronome"), "transport.metronome");
  4353. tip (countInButton, tr ("Count-in"), "record.countIn");
  4354. tip (waitInputButton, tr ("Wait for input"), "record.waitForInput");
  4355. tip (blendButton, tr ("Blend recorded notes"), "record.blend");
  4356. tip (loopRecordButton, tr ("Loop record"), "record.loop");
  4357. tip (stepEditButton, tr ("Step edit"), "record.stepEdit");
  4358. tip (multilinkButton, tr ("Multilink to controllers"), "options.multilink"); // (FL's hint: "Ctrl+J Multilink to controllers")
  4359. tip (punchButton, tr ("Punch in/out"), "record.punch");
  4360. tip (tapTempoButton, tr ("Tempo tapper"), "view.tempoTapper");
  4361. tip (typingPianoButton, tr ("Typing keyboard to piano"), "view.typingPiano");
  4362. tip (tempoDisplay, tr ("Tempo (BPM)"));
  4363. tip (timeDisplay, tr ("Song time"));
  4364. tip (songPosition, tr ("Song position"));
  4365. tip (masterVolume, tr ("Master volume"));
  4366. tip (masterPitch, tr ("Master pitch"));
  4367. tip (gridBox, tr ("Snap"));
  4368. tip (snapToggleButton, tr ("Snap on / off"));
  4369. tip (patternBox, tr ("Pattern"));
  4370. tip (newPatternButton, tr ("New pattern"));
  4371. tip (patternMenuButton, tr ("Pattern options"));
  4372. tip (perfMeter, tr ("CPU, memory and polyphony"));
  4373. tip (chordPanel, tr ("Detected chord"));
  4374. tip (output, tr ("Output monitor"));
  4375. tip (swingSlider, tr ("Swing"));
  4376. tip (rackFilterBox, tr ("Channel filter group"));
  4377. tip (rackGraphButton, tr ("Graph editor"));
  4378. tip (rackPianoRollButton, tr ("Piano-roll view"), "rack.pianoRollView");
  4379. tip (rackLoopButton, tr ("Channel looping"));
  4380. tip (rackLoopStarterButton, tr ("Loop Starter"));
  4381. for (int i = 0; i < workspace::panelCount; ++i)
  4382. tip (panelButtons[(std::size_t) i], tr (panelName ((Panel) i)), panelAction ((Panel) i));
  4383. }
  4384. // FL's Step edit (round 170e3): the notes played since the last tick go into the current pattern at the position, a
  4385. // snap step of the Piano Roll long; when every key is up the position moves on a step (core/StepEdit.h). While the
  4386. // transport plays they are left to the recording, as in FL.
  4387. void MainComponent::applyStepEdit()
  4388. {
  4389. auto played = engine.takeStepEditNotes();
  4390. if (played.empty() || engine.getTransport().playing.load())
  4391. return;
  4392. const auto now = engine.getTransport().positionTicks.load();
  4393. // the position moved by anything else (a click on a ruler, Stop): start from there
  4394. if (now != stepSeekTick && now != stepPrevTick)
  4395. {
  4396. const auto& song = engine.getSong();
  4397. const auto at = transportedit::patternPlayhead (song, song.currentPattern, now);
  4398. stepWriter.reset (at >= 0.0 ? (std::int64_t) std::llround (at) : 0);
  4399. stepSeekTick = stepPrevTick = now;
  4400. }
  4401. // the toolbar (main) snap is FL's step-edit step (round 170e5)
  4402. const auto& mainSnap = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  4403. const auto mainTicks = mainSnap.kind == grid::Kind::ticks ? (std::int64_t) mainSnap.ticks
  4404. : mainSnap.kind == grid::Kind::bar ? (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar)
  4405. : 0;
  4406. const auto step = stepedit::stepLength (mainTicks, pianoRoll.gridForSnapshot());
  4407. for (const auto& p : played)
  4408. {
  4409. auto moved = false;
  4410. engine.editSong ([&] (Song& s) {
  4411. if (! s.patterns.empty())
  4412. moved = stepWriter.play (p, s.patterns[(std::size_t) juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern)], step);
  4413. }, p.on);
  4414. if (! moved)
  4415. continue;
  4416. const auto& song = engine.getSong();
  4417. const auto target = transportedit::patternSeekTarget (song, song.currentPattern, (double) stepWriter.getPosition(), now);
  4418. if (target >= 0.0)
  4419. {
  4420. stepPrevTick = engine.getTransport().positionTicks.load();
  4421. stepSeekTick = target;
  4422. engine.seek (target);
  4423. }
  4424. }
  4425. }
  4426. bool MainComponent::toolbarFrame (double nowMs)
  4427. {
  4428. const auto moved = output.update (nowMs);
  4429. timeDisplay.update();
  4430. songPosition.update();
  4431. return moved || engine.getTransport().playing.load (std::memory_order_relaxed);
  4432. }
  4433. void MainComponent::refreshChordOptions()
  4434. {
  4435. auto options = chordReadout.getOptions();
  4436. options.sharps = ! notenames::flats();
  4437. for (int pc = 0; pc < 12; ++pc)
  4438. {
  4439. // the chosen note names, with FL's accidentals ("C♯", "B♭", "Sol♯")
  4440. auto name = juce::String (notenames::pitchName (pc));
  4441. if (name.endsWithChar ('#'))
  4442. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266F);
  4443. else if (name.length() > 1 && name.endsWithChar ('b'))
  4444. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266D);
  4445. chordNotes[(std::size_t) pc] = name.toStdString();
  4446. }
  4447. options.notes = &chordNotes;
  4448. // Roman (a LYNX choice, FL's item changes nothing): against the Piano Roll's scale, when one is set
  4449. const auto& highlight = engine.getSong().scaleHighlight;
  4450. options.tonic = pianoRoll.scaleTonic() >= 0 ? pianoRoll.scaleTonic() : highlight.scale >= 0 ? highlight.root : -1;
  4451. chordReadout.setOptions (options);
  4452. }
  4453. void MainComponent::showChordText()
  4454. {
  4455. auto text = juce::String::fromUTF8 (chordReadout.text().c_str());
  4456. if (chordReadout.lastWasNovelty())
  4457. text = tr (text);
  4458. chordPanel.setText (text);
  4459. if (chordShowNearHint)
  4460. {
  4461. // as FL: it follows the panel, leaves with "---", and with a display delay stays that long at most (15 s at most)
  4462. const auto chord = chordReadout.text() != chordread::noChord && text.isNotEmpty();
  4463. chordNearHint.setText (text);
  4464. const auto width = juce::roundToInt (juce::GlyphArrangement::getStringWidth (theme::font (theme::type::body, true).withHeight (17.0f), text)) + 8;
  4465. chordNearHint.setBounds (hintBar.getX() + 8, hintBar.getBottom() + 2, width, 24);
  4466. chordNearHint.setVisible (chord);
  4467. if (chord)
  4468. {
  4469. chordNearHint.toFront (false);
  4470. chordNearHintUntil = juce::Time::getMillisecondCounter() + juce::jmin<std::uint32_t> (15000, chordReadout.getDelayMs());
  4471. }
  4472. }
  4473. }
  4474. void MainComponent::updateChordPanel()
  4475. {
  4476. if (! chordPanel.isVisible() && ! chordShowNearHint)
  4477. return;
  4478. const auto now = juce::Time::getMillisecondCounter();
  4479. auto changed = false;
  4480. for (int channel = 0; channel < chordread::channels; ++channel)
  4481. {
  4482. const auto bits = engine.heldInputKeyBits (channel);
  4483. auto& before = chordHeld[(std::size_t) channel];
  4484. if (bits == before)
  4485. continue;
  4486. if (! changed)
  4487. refreshChordOptions();
  4488. changed = true;
  4489. // what ended first: a chord changed between two ticks reads as the new chord, not as both
  4490. for (const auto on : { false, true })
  4491. for (int word = 0; word < 2; ++word)
  4492. {
  4493. auto diff = (on ? bits[(std::size_t) word] & ~before[(std::size_t) word] : before[(std::size_t) word] & ~bits[(std::size_t) word]);
  4494. for (int b = 0; diff != 0; ++b, diff >>= 1)
  4495. if ((diff & 1u) != 0)
  4496. chordReadout.note (channel, word * 64 + b, on, now);
  4497. }
  4498. before = bits;
  4499. }
  4500. if (chordReadout.tick (now))
  4501. changed = true;
  4502. if (changed)
  4503. showChordText();
  4504. if (chordNearHint.isVisible() && chordReadout.getDelayMs() > 0 && (int) (now - chordNearHintUntil) > 0)
  4505. chordNearHint.setVisible (false);
  4506. }
  4507. void MainComponent::showChordPanelMenu()
  4508. {
  4509. juce::PopupMenu menu;
  4510. menu.addSectionHeader (tr ("Chord style"));
  4511. const auto roman = chordReadout.getOptions().roman;
  4512. auto setRoman = [this] (bool on) {
  4513. auto o = chordReadout.getOptions();
  4514. o.roman = on;
  4515. chordReadout.setOptions (o);
  4516. saveUiSettings();
  4517. };
  4518. menu.addItem (tr ("Standard"), true, ! roman, [setRoman] { setRoman (false); });
  4519. menu.addItem (tr ("Roman"), true, roman, [setRoman] { setRoman (true); });
  4520. menu.addSectionHeader (tr ("Display delay for played chords"));
  4521. const auto delay = chordReadout.getDelayMs();
  4522. auto delayItem = [&] (const juce::String& name, std::uint32_t seconds) {
  4523. menu.addItem (name, true, delay == seconds * 1000u, [this, seconds] {
  4524. chordReadout.setDelayMs (seconds * 1000u);
  4525. saveUiSettings();
  4526. });
  4527. };
  4528. delayItem (tr ("None"), 0);
  4529. delayItem (tr ("1 second"), 1);
  4530. delayItem (tr ("3 seconds"), 3);
  4531. delayItem (tr ("5 seconds"), 5);
  4532. delayItem (tr ("Show forever"), chordread::foreverSeconds);
  4533. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&chordPanel));
  4534. }
  4535. namespace
  4536. {
  4537. // "A minor", "C# Dorian": the root and the short scale name (round 184a S11)
  4538. juce::String keyLabel (const projectkey::Key& key)
  4539. {
  4540. return juce::String (projectkey::rootName (key.root)) + " " + tr (juce::String (projectkey::shortScaleName (key.flScale)));
  4541. }
  4542. } // namespace
  4543. void MainComponent::refreshKeyPanel()
  4544. {
  4545. const auto key = projectkey::get (engine.getSong());
  4546. keyPanel.setText (key ? keyLabel (*key) : juce::String());
  4547. }
  4548. void MainComponent::setProjectKey (std::optional<projectkey::Key> key)
  4549. {
  4550. if (projectkey::get (engine.getSong()) == key)
  4551. return;
  4552. engine.editSong ([key] (Song& s) { projectkey::set (s, key); }); // one undo step; no note moves
  4553. refreshKeyPanel();
  4554. pianoRoll.repaint(); // (its scale highlight is this key)
  4555. }
  4556. // The Key menu (round 184a S11, design §3.1): the best guesses from the song's notes, the root, the scale (the common ones,
  4557. // then "More scales"), and None. Every choice writes the one stored key, FL's project scale (.flp 0xF3).
  4558. void MainComponent::showKeyMenu()
  4559. {
  4560. makeKeyMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&keyPanel));
  4561. }
  4562. juce::PopupMenu MainComponent::makeKeyMenu()
  4563. {
  4564. const auto current = projectkey::get (engine.getSong());
  4565. juce::PopupMenu menu;
  4566. menu.addSectionHeader (tr ("Guess from notes"));
  4567. const auto guesses = keyguess::guess (engine.getSong(), 3);
  4568. if (guesses.empty())
  4569. menu.addItem (tr ("No notes to guess from yet"), false, false, [] {});
  4570. for (const auto& g : guesses)
  4571. menu.addItem (keyLabel (g.key) + " (" + tr ("{0} of {1} notes in scale", { juce::String (g.notesInScale), juce::String (g.notes) }) + ")",
  4572. true, current == g.key, [this, key = g.key] { setProjectKey (key); });
  4573. const auto root = current ? current->root : 0;
  4574. const auto scale = current ? current->flScale : projectkey::commonFirst().front(); // (no key yet: Major)
  4575. menu.addSectionHeader (tr ("Root"));
  4576. juce::PopupMenu roots;
  4577. for (int r = 0; r < 12; ++r)
  4578. roots.addItem (juce::String (projectkey::rootName (r)), true, current && current->root == r,
  4579. [this, r, scale] { setProjectKey (projectkey::Key { r, scale }); });
  4580. menu.addSubMenu (current ? juce::String (projectkey::rootName (root)) : tr ("Choose the root"), roots);
  4581. menu.addSectionHeader (tr ("Scale"));
  4582. const auto order = projectkey::commonFirst();
  4583. juce::PopupMenu more;
  4584. for (std::size_t i = 0; i < order.size(); ++i)
  4585. {
  4586. const auto flScale = order[i];
  4587. const auto ticked = current && current->flScale == flScale;
  4588. auto choose = [this, root, flScale] { setProjectKey (projectkey::Key { root, flScale }); };
  4589. if ((int) i < keyguess::commonScales)
  4590. {
  4591. const auto name = tr (juce::String (projectkey::shortScaleName (flScale))); // ("minor" in "A minor"; "Minor" in the list)
  4592. menu.addItem (name.substring (0, 1).toUpperCase() + name.substring (1), true, ticked, choose);
  4593. }
  4594. else // FL's own scale names (its Reference scales folder), as its Piano roll lists them
  4595. more.addItem (juce::String (notetools::flReferenceScales()[(std::size_t) flScale].name), true, ticked, choose);
  4596. }
  4597. menu.addSubMenu (tr ("More scales"), more);
  4598. menu.addSeparator();
  4599. menu.addItem (tr ("None"), true, ! current, [this] { setProjectKey (std::nullopt); });
  4600. return menu;
  4601. }
  4602. void MainComponent::addAudioLoggerMenu (juce::PopupMenu& menu)
  4603. {
  4604. // FL 2026's Tools › Audio logger, item for item (REA_rodada181b.md)
  4605. auto& log = engine.getRollingLog();
  4606. const auto on = log.isEnabled();
  4607. auto title = tr ("Audio logger");
  4608. if (on)
  4609. title << " (" << tr ("memory used: {0}MB", { juce::String (juce::roundToInt ((double) log.bytesInUse() / 1048576.0)) }) << ")";
  4610. menu.addSectionHeader (title);
  4611. menu.addItem (tr ("Enabled"), true, on, [this, on] {
  4612. engine.getRollingLog().setEnabled (! on);
  4613. saveUiSettings();
  4614. });
  4615. juce::PopupMenu settings;
  4616. settings.addSectionHeader (tr ("Maximum length"));
  4617. const auto seconds = log.lengthSeconds();
  4618. auto lengthItem = [&] (const juce::String& name, int minutes) {
  4619. settings.addItem (name, true, seconds == minutes * 60, [this, minutes] {
  4620. engine.getRollingLog().setLengthSeconds (minutes * 60);
  4621. saveUiSettings();
  4622. });
  4623. };
  4624. lengthItem (tr ("1 minute"), 1);
  4625. lengthItem (tr ("2 minutes"), 2);
  4626. lengthItem (tr ("5 minutes"), 5);
  4627. lengthItem (tr ("10 minutes"), 10);
  4628. settings.addSectionHeader (tr ("Recording position"));
  4629. const auto pre = log.getPosition() == RollingAudioLog::Position::preEffects;
  4630. auto positionItem = [&] (const juce::String& name, RollingAudioLog::Position p, bool ticked) {
  4631. settings.addItem (name, true, ticked, [this, p] {
  4632. engine.getRollingLog().setPosition (p);
  4633. saveUiSettings();
  4634. });
  4635. };
  4636. positionItem (tr ("Pre effects"), RollingAudioLog::Position::preEffects, pre);
  4637. positionItem (tr ("Post effects, pre fader"), RollingAudioLog::Position::postEffects, ! pre);
  4638. menu.addSubMenu (tr ("Settings"), settings);
  4639. menu.addItem (tr ("Dump to audio editor"), on, false, [this] { dumpAudioLog(); });
  4640. }
  4641. void MainComponent::dumpAudioLog()
  4642. {
  4643. auto dump = std::make_shared<RollingAudioLog::Dump>();
  4644. if (! engine.getRollingLog().dump (*dump))
  4645. {
  4646. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Audio logger is empty"),
  4647. tr ("The audio logger doesn't contain any audio at the moment"));
  4648. return;
  4649. }
  4650. const auto folder = AudioLogger::defaultFolder();
  4651. folder.createDirectory();
  4652. const auto target = folder.getNonexistentChildFile ("Audiolog-" + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S"), ".wav", false);
  4653. juce::Component::SafePointer<MainComponent> self (this);
  4654. // (a long log takes a moment to write: not on the UI thread)
  4655. juce::Thread::launch ([self, dump, target] {
  4656. auto saved = false;
  4657. {
  4658. juce::WavAudioFormat wav;
  4659. std::unique_ptr<juce::OutputStream> stream (target.createOutputStream().release());
  4660. if (stream != nullptr)
  4661. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (stream.get(), dump->rate, 2, 32, {}, 0) }; writer != nullptr)
  4662. {
  4663. stream.release(); // owned by the writer now
  4664. const float* channels[] = { dump->left.data(), dump->right.data() };
  4665. saved = writer->writeFromFloatArrays (channels, 2, (int) dump->left.size());
  4666. }
  4667. }
  4668. juce::MessageManager::callAsync ([self, target, saved] {
  4669. if (self == nullptr)
  4670. return;
  4671. if (saved)
  4672. openAudioEditor (self->engine, target);
  4673. else
  4674. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Audio logger"),
  4675. tr ("Could not create a file in {0}", { target.getParentDirectory().getFullPathName() }));
  4676. });
  4677. });
  4678. }
  4679. void MainComponent::timerCallback()
  4680. {
  4681. const uitrace::Scope trace ("MainComponent timer", false);
  4682. {
  4683. const uitrace::Scope part ("timer: toolbar displays", false);
  4684. masterVolume.update();
  4685. masterPitch.update();
  4686. updateRecordQuantise();
  4687. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  4688. }
  4689. if (engine.isStepEdit())
  4690. applyStepEdit();
  4691. if (engine.isModified() != lastModified)
  4692. {
  4693. const uitrace::Scope part ("timer: title", false);
  4694. lastModified = engine.isModified();
  4695. updateTitle();
  4696. }
  4697. // the Browser's "Project folder" follows the project's file (.lynx, or the .flp it was imported from)
  4698. const uitrace::Scope partFolders ("timer: project folder / recording target", false);
  4699. browser.setProjectFile (currentFile != juce::File() ? currentFile : importedFlpFile);
  4700. // and so does where audio is recorded ("<project folder>/Audio/Recorded", FL-like take names)
  4701. engine.setRecordingTarget (recordingFolderFor (currentFile != juce::File() ? currentFile : importedFlpFile),
  4702. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String());
  4703. // a backup copy every few minutes (Settings › General) when there are changes
  4704. // (not in the middle of a recording: FL also postpones the timed backup until the transport is free; round 177d:
  4705. // with "Wait with backups..." on, also while playing and for a few seconds after MIDI input, so writing the plugin
  4706. // states never stutters the sound, up to the longest wait set there)
  4707. if (const auto midi = engine.getMidiPlayed(); midi != backupMidiSeen)
  4708. {
  4709. backupMidiSeen = midi;
  4710. backupMidiMs = juce::Time::getMillisecondCounterHiRes();
  4711. }
  4712. const auto backupDueTicks = 30 * 60 * autosaveMinutes;
  4713. if (autosaveMinutes > 0 && ++autosaveTicks >= backupDueTicks
  4714. && prefs::backupMayRun (engine.isRecording(), engine.getTransport().playing.load(),
  4715. juce::Time::getMillisecondCounterHiRes() - backupMidiMs, backupWaitsForQuiet,
  4716. autosaveTicks * 1000.0 / 30.0, backupLongestWaitMinutes * 60000.0))
  4717. {
  4718. autosaveTicks = 0;
  4719. if (engine.isModified())
  4720. autosave();
  4721. }
  4722. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.finished != scansSeen)
  4723. {
  4724. scansSeen = scan.finished;
  4725. ui::postHint ({ scan.found == 1 ? tr ("Plugin scan finished: 1 new plugin.")
  4726. : tr ("Plugin scan finished: {0} new plugins.", { juce::String (scan.found) }), {}, false, false },
  4727. 6000);
  4728. }
  4729. // a hosted plugin crashed inside a call: it was switched off (bypassed / silent) and LYNX kept running
  4730. if (const auto crashes = pluginCrashCount(); crashes != pluginCrashesSeen)
  4731. {
  4732. pluginCrashesSeen = crashes;
  4733. juce::StringArray names, lines;
  4734. for (const auto& c : pluginCrashes())
  4735. {
  4736. const auto name = juce::String::fromUTF8 (c.plugin.c_str());
  4737. names.addIfNotAlreadyThere (name);
  4738. lines.add (juce::Time::getCurrentTime().toISO8601 (true) + " " + name + " " + crashguard::describe (c.code) + " 0x"
  4739. + juce::String::toHexString ((juce::int64) c.code));
  4740. }
  4741. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (lines[lines.size() - 1] + "\n");
  4742. // round 190ao: "Reload" starts it again without reopening the project (only on request: a plugin that crashes
  4743. // again shows this again)
  4744. const auto crashedName = names[names.size() - 1];
  4745. juce::AlertWindow::showAsync (juce::MessageBoxOptions()
  4746. .withIconType (juce::MessageBoxIconType::WarningIcon)
  4747. .withTitle (tr ("Plugin crashed"))
  4748. .withMessage (tr ("{0} crashed and was switched off.", { crashedName }) + "\n\n"
  4749. + tr ("LYNX SHARE and your project kept running (an effect is bypassed, an instrument "
  4750. "stays silent). Save your project.")
  4751. + " " + tr ("Reload starts it again with the settings from the last save or backup."))
  4752. .withButton (tr ("Reload"))
  4753. .withButton (tr ("Close")),
  4754. [safe = juce::Component::SafePointer<MainComponent> (this), crashedName] (int result) {
  4755. if (safe != nullptr && result == 1)
  4756. safe->reloadCrashedPlugins (crashedName);
  4757. });
  4758. }
  4759. // round 176a: a plugin in a separate process (Make bridged, or a 32-bit plugin in the 32-bit bridge) crashed or hung:
  4760. // only that process went; the plugin is muted. Round 174a's prompt, logged like the other plugin crashes.
  4761. if (const auto deaths = pluginSandboxDeathCount(); deaths != sandboxDeathsSeen)
  4762. {
  4763. sandboxDeathsSeen = deaths;
  4764. const auto all = pluginSandboxDeaths();
  4765. if (! all.empty())
  4766. {
  4767. const auto& d = all.back();
  4768. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (
  4769. juce::Time::getCurrentTime().toISO8601 (true) + " " + d.plugin + " " + (d.crashed ? "crashed" : "stopped responding")
  4770. + (d.bits32 ? " (32-bit bridge)" : " (separate process)") + "\n");
  4771. announceSeparateProcessCrash (d.plugin, d.crashed, d.bits32);
  4772. }
  4773. }
  4774. // issue #32 (round 174a): a plugin's own editor window faulted; LYNX closed that editor and kept running
  4775. if (const auto crashes = PluginWindows::editorCrashCount(); crashes != editorCrashesSeen)
  4776. {
  4777. editorCrashesSeen = crashes;
  4778. const auto all = PluginWindows::editorCrashes();
  4779. if (! all.empty())
  4780. announceEditorCrash (all.back().plugin);
  4781. }
  4782. auto& transport = engine.getTransport();
  4783. if (! heldKeys.empty())
  4784. {
  4785. if (! juce::Process::isForegroundProcess()) // switched to another app with keys down: no key-up will come
  4786. heldKeys.releaseAll();
  4787. else // keys released while another window (a detached panel, a dialog) had the focus
  4788. keyStateChanged (false);
  4789. }
  4790. // hint bar: a gesture's own posted hint, else the control under the mouse (while it is dragged, the
  4791. // control that was pressed, at the point it was pressed, so its value updates live); MIDI learn and
  4792. // recording states first
  4793. if (! hintsFrozen)
  4794. {
  4795. const uitrace::Scope part ("timer: hint", false);
  4796. ui::Hint hint;
  4797. bool live = false;
  4798. juce::Component* hovered = nullptr;
  4799. if (engine.isLearningMidi())
  4800. hint.text = tr ("Move a knob/fader on the MIDI controller to link it to the parameter...");
  4801. else if (engine.isWaitingForInput() || engine.isCountingIn())
  4802. hint.text = idleHint();
  4803. else if (auto posted = ui::postedHint())
  4804. {
  4805. hint = *posted;
  4806. live = true;
  4807. }
  4808. else if (isShowing())
  4809. {
  4810. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  4811. if (auto* under = source.getComponentUnderMouse())
  4812. {
  4813. live = source.isDragging();
  4814. const auto at = live ? source.getLastMouseDownPosition() : source.getScreenPosition();
  4815. hint = ui::hintFor (under, under->getLocalPoint (nullptr, at).roundToInt());
  4816. hovered = under;
  4817. }
  4818. }
  4819. if (hint.isEmpty())
  4820. {
  4821. hint.text = idleHint();
  4822. live = false;
  4823. }
  4824. hintBar.setHint (hint, live && hint.value.isNotEmpty());
  4825. if (hoverValues)
  4826. updateHoverValue (hovered, hint, live);
  4827. if (++tweakTicks >= 3) // 10 times a second
  4828. {
  4829. tweakTicks = 0;
  4830. refreshTweakReadout();
  4831. }
  4832. }
  4833. const auto playing = transport.playing.load();
  4834. playButton.setToggleState (playing, juce::dontSendNotification);
  4835. updateChordPanel();
  4836. // CPU / memory / polyphony, a few times a second
  4837. if (++meterTicks >= 8 && perfMeter.isVisible() && ! hintsFrozen)
  4838. {
  4839. const uitrace::Scope part ("timer: performance meter", false);
  4840. meterTicks = 0;
  4841. const auto held = (int) heldKeys.size();
  4842. const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
  4843. perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
  4844. const auto rt = engine.getRtStats().snapshot();
  4845. juce::StringArray heaviest;
  4846. for (const auto& u : engine.getHeaviestUnits())
  4847. if (heaviest.size() < 3 && u.load >= 0.01)
  4848. heaviest.add (u.name + " " + juce::String (juce::roundToInt (u.load * 100.0)) + "%");
  4849. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  4850. perfMeter.setRealtime (rt.overBudget, rt.lateCalls, engine.getRtStats().takeWindowMaxLoad(), heaviest,
  4851. device != nullptr ? device->getXRunCount() : -1);
  4852. // dropouts on Windows shared mode: suggest the interface's ASIO driver (round 160), worked out once per device type
  4853. if (device != nullptr && (rt.overBudget > 0 || rt.lateCalls > 0) && device->getTypeName() != driverTipType)
  4854. {
  4855. driverTipType = device->getTypeName();
  4856. std::vector<std::string> asio;
  4857. for (auto* type : engine.getDeviceManager().getAvailableDeviceTypes())
  4858. if (type->getTypeName() == "ASIO")
  4859. for (const auto& name : type->getDeviceNames())
  4860. asio.push_back (name.toStdString());
  4861. perfMeter.setDriverTip (juce::String::fromUTF8 (prefs::suggestedAsioDriver (driverTipType.toStdString(), asio).c_str()));
  4862. }
  4863. // Linux: the first dropouts without real-time priority explain how to get it, once per installation (round 161)
  4864. if (device != nullptr && ! realtimeHintChecked && (rt.overBudget > 0 || device->getXRunCount() > 0)
  4865. && lynx::rt::status() == lynx::rt::Status::denied)
  4866. {
  4867. realtimeHintChecked = true;
  4868. if (lynx::rt::shouldShowHint (PluginHost::settingsFolder().getChildFile ("realtime-hint-shown")))
  4869. juce::AlertWindow::showMessageBoxAsync (
  4870. juce::MessageBoxIconType::InfoIcon, tr ("Real-time priority"),
  4871. 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"
  4872. "- install rtkit (package \"rtkit\"; most desktops already have it), or\n"
  4873. "- add yourself to the \"audio\" group with an rtprio limit in /etc/security/limits.d (as for JACK),\n\n"
  4874. "then log out and in again. LYNX SHARE never needs root. Options > Audio settings shows the current state."));
  4875. }
  4876. }
  4877. if (++midiInputTicks % 30 == 1) // the open MIDI inputs, once a second
  4878. midiLightInputs = engine.getActiveMidiInputs();
  4879. midiLight.update (engine.getMidiActivity(), midiLightInputs);
  4880. // If a closed dialog left the main window without a focused component, take it back so the PC keyboard
  4881. // keeps playing. Only while the main window itself is the active one: another LYNX window (Audio editor,
  4882. // Quick-add palette, a plugin's editor, a detached panel) keeps its focus (issue #4: grabbing it here, 30
  4883. // times a second, pulled the main window to the front and closed the plugins' drop-down menus).
  4884. if (shouldReclaimKeyboardFocus())
  4885. grabKeyboardFocus();
  4886. }
  4887. bool MainComponent::shouldReclaimKeyboardFocus()
  4888. {
  4889. auto* peer = getPeer();
  4890. return ! hasKeyboardFocus (true) && isShowing() && peer != nullptr && peer->isFocused() && juce::Process::isForegroundProcess()
  4891. && juce::Component::getCurrentlyModalComponent() == nullptr && ! workspace.isDetachedWindowActive();
  4892. }
  4893. void MainComponent::updateTitle()
  4894. {
  4895. repaint (titleArea); // the project name in the toolbar
  4896. if (! engine.isModified()) // what is on disk now: the reference for "unused recordings" after a Discard
  4897. savedSamples = safety::referencedSamples (engine.getSong());
  4898. if (auto* window = getTopLevelComponent())
  4899. {
  4900. // a live session's state (round 169j): LIVE, or what it is waiting for
  4901. juce::String liveState;
  4902. if (live != nullptr && live->isActive())
  4903. {
  4904. using S = LiveSessionManager::State;
  4905. const auto st = live->getState();
  4906. liveState = " [" + (st == S::live ? tr ("LIVE") : st == S::reconnecting ? tr ("Reconnecting...") : st == S::waitingHost ? tr ("Waiting for the host...") : tr ("Connecting...")) + "]";
  4907. }
  4908. // round 190ap: opened without third-party plugins, while some are still off
  4909. const auto pluginsOff = engine.pluginsOff() ? " " + tr ("(third-party plugins off)") : juce::String();
  4910. window->setName ((engine.isModified() ? "* " : "")
  4911. + (projectName.isNotEmpty() ? "LYNX SHARE - " + projectName : juce::String ("LYNX SHARE")) + importedSuffix + pluginsOff + liveState);
  4912. }
  4913. }
  4914. std::unique_ptr<juce::AlertWindow> MainComponent::makeConfirmDiscardWindow()
  4915. {
  4916. auto window = std::make_unique<juce::AlertWindow> (tr ("Save changes?"), tr ("The project has unsaved changes."),
  4917. juce::MessageBoxIconType::QuestionIcon);
  4918. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4919. window->addButton (tr ("Discard"), 2);
  4920. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4921. return window;
  4922. }
  4923. void MainComponent::confirmDiscard (std::function<void()> then)
  4924. {
  4925. if (! engine.isModified())
  4926. {
  4927. offerToDeleteUnusedRecordings (true, std::move (then));
  4928. return;
  4929. }
  4930. auto* window = makeConfirmDiscardWindow().release();
  4931. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
  4932. if (result == 1)
  4933. save (false, [this, then] { offerToDeleteUnusedRecordings (true, then); }); // (not after a cancelled "save as")
  4934. else if (result == 2)
  4935. offerToDeleteUnusedRecordings (false, then);
  4936. }),
  4937. true);
  4938. }
  4939. juce::File MainComponent::recordingFolderFor (const juce::File& projectFile) const
  4940. {
  4941. // FL records into the project data folder's "Audio\Recorded" (REA round 134); LYNX's data folder is the folder of
  4942. // the project file. Unsaved projects record into the global recordings folder.
  4943. return projectFile == juce::File() ? AudioEngine::defaultRecordingFolder()
  4944. : projectFile.getParentDirectory().getChildFile (safety::recordedSubfolder);
  4945. }
  4946. namespace
  4947. {
  4948. // FL's Keep / Delete question about recorded files nothing uses (FLEngine FUN_00ed1380, REA round 134)
  4949. void askKeepOrDelete (const juce::String& message, const std::vector<juce::File>& files, std::function<void (bool)> done)
  4950. {
  4951. juce::String list;
  4952. for (std::size_t i = 0; i < files.size() && i < 8; ++i)
  4953. list << "\n " << files[i].getFileName();
  4954. if (files.size() > 8)
  4955. list << "\n " << tr ("...and {0} more", { juce::String ((int) files.size() - 8) });
  4956. auto* w = new juce::AlertWindow (tr ("Unused recordings"), message + list, juce::MessageBoxIconType::QuestionIcon);
  4957. w->addButton (tr ("Keep"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4958. w->addButton (tr ("Delete"), 1);
  4959. w->enterModalState (true, juce::ModalCallbackFunction::create ([done] (int result) { done (result == 1); }), true);
  4960. }
  4961. // to the recycle bin when the system has one (FL's "Delete recorded files to recycle bin")
  4962. int removeFiles (const std::vector<juce::File>& files)
  4963. {
  4964. int removed = 0;
  4965. for (const auto& f : files)
  4966. removed += f.existsAsFile() && (f.moveToTrash() || f.deleteFile());
  4967. return removed;
  4968. }
  4969. } // namespace
  4970. void MainComponent::offerToDeleteUnusedRecordings (bool keepsCurrentState, std::function<void()> then)
  4971. {
  4972. // the takes of this session the project on disk will not use: deleted takes, undone recordings, a project closed
  4973. // without saving (FL: "You created ... sample file(s) that are no longer used if the project isn't saved")
  4974. std::vector<std::string> recorded;
  4975. for (const auto& f : engine.getSessionRecordings())
  4976. if (f.existsAsFile())
  4977. recorded.push_back (f.getFullPathName().toStdString());
  4978. const auto referenced = keepsCurrentState ? safety::referencedSamples (engine.getSong()) : savedSamples;
  4979. std::vector<juce::File> unused;
  4980. for (const auto& path : safety::unusedRecordings (recorded, referenced))
  4981. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  4982. if (unused.empty() || ! askUnusedRecordings || ! persistent)
  4983. {
  4984. then();
  4985. return;
  4986. }
  4987. askKeepOrDelete (unused.size() == 1 ? tr ("You recorded 1 audio file that this project will not use.")
  4988. : tr ("You recorded {0} audio files that this project will not use.", { juce::String ((int) unused.size()) }),
  4989. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused, then] (bool remove) {
  4990. if (safe == nullptr)
  4991. return;
  4992. if (remove)
  4993. removeFiles (unused);
  4994. safe->engine.forgetRecordings (unused); // asked once per file
  4995. then();
  4996. });
  4997. }
  4998. void MainComponent::deleteUnusedRecordingsAndSave()
  4999. {
  5000. // FL's Tools › Macros "Delete unused files and save project", for the files this project recorded: every take in
  5001. // its recording folder (and this session's takes elsewhere) that no channel or clip uses
  5002. if (currentFile == juce::File())
  5003. {
  5004. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Delete unused recordings"),
  5005. tr ("Save the project first: its recordings are kept next to it, in {0}.", { juce::String (safety::recordedSubfolder) }));
  5006. return;
  5007. }
  5008. std::vector<std::string> recorded;
  5009. const auto stem = currentFile.getFileNameWithoutExtension() + "_";
  5010. for (const auto& f : recordingFolderFor (currentFile).findChildFiles (juce::File::findFiles, false, "*.wav"))
  5011. if (f.getFileName().startsWithIgnoreCase (stem)) // other projects in the same folder record there too
  5012. recorded.push_back (f.getFullPathName().toStdString());
  5013. for (const auto& f : engine.getSessionRecordings())
  5014. if (f.existsAsFile())
  5015. recorded.push_back (f.getFullPathName().toStdString());
  5016. std::vector<juce::File> unused;
  5017. for (const auto& path : safety::unusedRecordings (recorded, safety::referencedSamples (engine.getSong())))
  5018. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  5019. if (unused.empty())
  5020. {
  5021. save (false);
  5022. ui::postHint ({ tr ("No unused recordings. Project saved."), {}, false, false }, 4000);
  5023. return;
  5024. }
  5025. askKeepOrDelete (tr ("This project has {0} unused recording(s). Deleting them cannot be undone (they go to the recycle bin).",
  5026. { juce::String ((int) unused.size()) }),
  5027. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused] (bool remove) {
  5028. if (safe == nullptr)
  5029. return;
  5030. if (remove)
  5031. {
  5032. const auto n = removeFiles (unused);
  5033. safe->engine.forgetRecordings (unused);
  5034. ui::postHint ({ tr ("Deleted {0} unused recording(s).", { juce::String (n) }), {}, false, false }, 4000);
  5035. }
  5036. safe->save (false);
  5037. });
  5038. }
  5039. namespace
  5040. {
  5041. juce::String projectStem (const juce::String& projectName)
  5042. {
  5043. return projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled");
  5044. }
  5045. // the backup folder's projects with their modification times (for rotation and "revert to last backup")
  5046. std::vector<safety::BackupFile> backupFiles (const juce::File& folder)
  5047. {
  5048. std::vector<safety::BackupFile> files;
  5049. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, juce::String ("*") + ProjectFile::extension))
  5050. files.push_back ({ f.getFileNameWithoutExtension().toStdString(), f.getLastModificationTime().toMilliseconds() });
  5051. return files;
  5052. }
  5053. // "Song (autosaved on 2026-10-20 at 14h19)" in `folder`, "_2"... when that minute is taken (FL's naming, REA round 118)
  5054. juce::File newBackupFile (const juce::File& folder, const juce::String& stem, safety::BackupKind kind)
  5055. {
  5056. const auto now = juce::Time::getCurrentTime();
  5057. const auto name = safety::backupName (stem.toStdString(), kind, now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(), now.getMinutes());
  5058. const auto unique = safety::uniqueName (name, [&folder] (const std::string& n) {
  5059. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  5060. });
  5061. return folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ProjectFile::extension);
  5062. }
  5063. } // namespace
  5064. void MainComponent::autosave()
  5065. {
  5066. // backup copy of the open project, so work isn't lost if something crashes ("Song (autosaved on 2026-10-20 at
  5067. // 14h19).lynx" in the backup folder, like FL's Backup folder); only the newest few of each project are kept
  5068. // The plugins' settings are read here (they answer on the message thread); writing the file (the big part:
  5069. // every plugin's state, encoded) runs on a thread of its own, so the timed backup no longer freezes the screen
  5070. // (round 151: 180 ms every two minutes on a project with 71 plugins). One at a time.
  5071. if (autosaveRunning->load())
  5072. return;
  5073. const auto folder = autosaveFolder();
  5074. folder.createDirectory();
  5075. const auto stem = projectStem (projectName);
  5076. {
  5077. const uitrace::Scope trace ("autosave: plugin states", false);
  5078. engine.capturePluginStates();
  5079. }
  5080. auto copy = std::make_shared<Song> (engine.getSong());
  5081. const auto file = newBackupFile (folder, stem, safety::BackupKind::autosaved);
  5082. autosaveRunning->store (true);
  5083. juce::Thread::launch ([copy, file, running = autosaveRunning, safe = juce::Component::SafePointer<MainComponent> (this), stem] {
  5084. juce::String error;
  5085. const auto ok = ProjectFile::save (*copy, file, error);
  5086. running->store (false);
  5087. juce::MessageManager::callAsync ([safe, ok, error, stem] {
  5088. if (safe == nullptr)
  5089. return;
  5090. if (! ok)
  5091. ui::postHint ({ tr ("Autosave failed: {0}", { error }), {}, false, false }, 6000);
  5092. else
  5093. {
  5094. safe->rotateBackups (stem);
  5095. safe->lastBackupMs = juce::Time::currentTimeMillis(); // (the Simple workflow's "Backed up ... ago")
  5096. safe->lastBackupProject = safe->engine.getSong().projectId;
  5097. }
  5098. });
  5099. });
  5100. }
  5101. // The Simple workflow's line beside "+ Add track" (round 190t): what a beginner needs to know about their work — LYNX
  5102. // backs it up by itself. Empty when there is nothing to say (a new project with nothing in it yet).
  5103. juce::String MainComponent::simpleSaveStatus() const
  5104. {
  5105. return simpleSaveStatusText (engine.isModified(), currentFile.existsAsFile(),
  5106. lastBackupProject == engine.getSong().projectId ? lastBackupMs : 0, juce::Time::currentTimeMillis());
  5107. }
  5108. juce::String MainComponent::simpleSaveStatusText (bool modified, bool hasFile, juce::int64 backupMs, juce::int64 nowMs)
  5109. {
  5110. if (! modified)
  5111. return hasFile ? tr ("All changes saved") : juce::String();
  5112. if (backupMs <= 0)
  5113. return tr ("Not saved yet");
  5114. const auto minutes = (int) ((nowMs - backupMs) / 60000);
  5115. return minutes < 1 ? tr ("Backed up just now") : tr ("Backed up {0} min ago", { juce::String (minutes) });
  5116. }
  5117. void MainComponent::rotateBackups (const juce::String& stem)
  5118. {
  5119. const auto folder = autosaveFolder();
  5120. // (round 190ap: a backup the user labelled in the Versions panel is one to find again: it is left alone and does
  5121. // not count toward the number kept; without labels the rotation is exactly as before)
  5122. const auto files = safety::versions::withoutLabelled (backupFiles (folder), backupLabels (folder, stem));
  5123. for (const auto& old : safety::backupsToRemove (files, stem.toStdString(), autosaveKeep))
  5124. {
  5125. const auto f = folder.getChildFile (juce::String::fromUTF8 (old.c_str()) + ProjectFile::extension);
  5126. f.setReadOnly (false); // (FL clears the read-only flag before deleting an old backup too)
  5127. f.deleteFile();
  5128. }
  5129. }
  5130. void MainComponent::keepOverwrittenCopy (const juce::File& file)
  5131. {
  5132. // FL moves the file a save replaces into its Backup folder as "Song (overwritten on ... at ...)"; LYNX copies it
  5133. // (the save itself still goes through a temporary file and a rename)
  5134. const auto folder = autosaveFolder();
  5135. if (! file.existsAsFile() || file.isAChildOf (folder))
  5136. return;
  5137. folder.createDirectory();
  5138. const auto stem = projectStem (file.getFileNameWithoutExtension());
  5139. if (file.copyFileTo (newBackupFile (folder, stem, safety::BackupKind::overwritten)))
  5140. rotateBackups (stem);
  5141. }
  5142. void MainComponent::saveNewVersion()
  5143. {
  5144. // FL's "Save new version": Song.flp -> Song_2.flp -> Song_3.flp, next to the current file
  5145. if (currentFile == juce::File())
  5146. {
  5147. save (true);
  5148. return;
  5149. }
  5150. const auto folder = currentFile.getParentDirectory();
  5151. const auto name = safety::nextVersionName (currentFile.getFileNameWithoutExtension().toStdString(), [&folder] (const std::string& n) {
  5152. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  5153. });
  5154. const auto file = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  5155. juce::String error;
  5156. engine.capturePluginStates();
  5157. if (! ProjectFile::save (engine.getSong(), file, error))
  5158. {
  5159. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  5160. return;
  5161. }
  5162. engine.markSaved();
  5163. rememberRecent (file);
  5164. currentFile = file;
  5165. projectName = file.getFileNameWithoutExtension();
  5166. importedSuffix = {};
  5167. updateTitle();
  5168. ui::postHint ({ tr ("Saved as a new version: {0}", { file.getFileName() }), {}, false, false }, 5000);
  5169. }
  5170. void MainComponent::showVersions()
  5171. {
  5172. if (auto* open = findToolWindow ("versions"))
  5173. {
  5174. open->toFront (true);
  5175. return;
  5176. }
  5177. VersionsActions actions;
  5178. const juce::Component::SafePointer<MainComponent> safe (this);
  5179. actions.context = [safe] {
  5180. VersionsContext c;
  5181. if (safe == nullptr)
  5182. return c;
  5183. c.projectFile = safe->currentFile;
  5184. c.projectStem = projectStem (safe->projectName);
  5185. c.backupFolder = autosaveFolder();
  5186. c.extension = ProjectFile::extension;
  5187. return c;
  5188. };
  5189. actions.openAsCopy = [safe] (const juce::File& file, const juce::String& name) {
  5190. if (safe != nullptr)
  5191. safe->confirmDiscard ([safe, file, name] {
  5192. if (safe != nullptr)
  5193. safe->openProjectAsCopy (file, name);
  5194. });
  5195. };
  5196. actions.saveNewVersion = [safe] {
  5197. if (safe != nullptr)
  5198. safe->saveNewVersion();
  5199. };
  5200. if (auto* window = openToolWindow (makeVersionsPanel (std::move (actions)), tr ("Versions"), "versions"))
  5201. window->setResizable (true, false);
  5202. }
  5203. void MainComponent::openProjectAsCopy (const juce::File& file, const juce::String& name)
  5204. {
  5205. // A version or a backup opened to look at or to carry on from: it becomes an unsaved project under `name`, so
  5206. // neither that file nor the project that was open is written over (Save asks where to put it).
  5207. juce::String error;
  5208. auto song = ProjectFile::load (file, error);
  5209. if (! song)
  5210. {
  5211. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5212. return;
  5213. }
  5214. engine.getPluginHost().applySubstitutes (*song);
  5215. engine.stop();
  5216. engine.rewind();
  5217. engine.setSong (std::move (*song));
  5218. currentFile = juce::File();
  5219. importedFlpFile = juce::File();
  5220. projectName = name;
  5221. importedSuffix = {};
  5222. updateTitle();
  5223. playlist.showSongAfterOpen();
  5224. ui::postHint ({ tr ("Opened as a copy: {0}", { file.getFileName() }), tr ("Save asks where to keep it; the original file is untouched") }, 7000);
  5225. }
  5226. void MainComponent::revertToLastBackup()
  5227. {
  5228. const auto stem = projectStem (projectName);
  5229. const auto name = safety::newestBackup (backupFiles (autosaveFolder()), stem.toStdString());
  5230. if (name.empty())
  5231. {
  5232. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Revert to last backup"),
  5233. tr ("There is no backup of this project yet."));
  5234. return;
  5235. }
  5236. const auto backup = autosaveFolder().getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  5237. const auto when = backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M");
  5238. auto* w = new juce::AlertWindow (tr ("Revert to last backup"),
  5239. tr ("Replace the open project with its backup from {0}?\n{1}\n\nThe project file itself only changes when you save.",
  5240. { when, backup.getFileName() }),
  5241. juce::MessageBoxIconType::QuestionIcon);
  5242. w->addButton (tr ("Revert"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5243. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5244. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup] (int result) {
  5245. if (safe == nullptr || result != 1)
  5246. return;
  5247. juce::String error;
  5248. auto song = ProjectFile::load (backup, error);
  5249. if (! song)
  5250. {
  5251. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5252. return;
  5253. }
  5254. safe->engine.getPluginHost().applySubstitutes (*song);
  5255. safe->engine.stop();
  5256. safe->engine.rewind();
  5257. safe->engine.setSong (std::move (*song));
  5258. safe->engine.markModified(); // Save writes it back to the project's own file
  5259. safe->updateTitle();
  5260. safe->playlist.showSongAfterOpen();
  5261. }),
  5262. true);
  5263. }
  5264. sessionui::Context MainComponent::sessionContext()
  5265. {
  5266. return { engine, currentFile, projectName, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::File& project) {
  5267. if (safe != nullptr)
  5268. safe->openLynxProject (project);
  5269. } };
  5270. }
  5271. liveui::Context MainComponent::liveContext()
  5272. {
  5273. return { engine, *live, currentFile, [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  5274. if (safe != nullptr)
  5275. safe->confirmDiscard (std::move (then));
  5276. } };
  5277. }
  5278. void MainComponent::startLiveFromCommandLine()
  5279. {
  5280. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  5281. auto value = [&] (const char* flag) {
  5282. const auto at = cli.indexOf (flag);
  5283. return at >= 0 && at + 1 < cli.size() ? cli[at + 1].unquoted() : juce::String();
  5284. };
  5285. auto o = LiveSessionManager::Options();
  5286. o.name = value ("--live-name").isNotEmpty() ? value ("--live-name") : liveui::myName();
  5287. o.projectFile = currentFile;
  5288. if (const auto relay = value ("--live-relay"); relay.isNotEmpty())
  5289. o.relay = relay;
  5290. // round 169j: --live-chat "text" (sent once in), --live-follow (follow the host's transport), --live-resume (the
  5291. // host resumes its interrupted session without asking)
  5292. if (const auto text = value ("--live-chat"); text.isNotEmpty())
  5293. juce::Timer::callAfterDelay (9000, [safe = juce::Component::SafePointer<MainComponent> (this), text] {
  5294. if (safe != nullptr)
  5295. {
  5296. safe->live->sendChat (text);
  5297. liveui::showChat (*safe->live);
  5298. }
  5299. });
  5300. if (cli.contains ("--live-follow"))
  5301. juce::Timer::callAfterDelay (8500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  5302. if (safe != nullptr)
  5303. safe->live->setFollowTransport (true);
  5304. });
  5305. if (cli.contains ("--live-resume"))
  5306. {
  5307. o.projectFile = juce::File();
  5308. o.autoAccept = true;
  5309. if (! live->resumeHost (LiveSessionManager::defaultJournal(), o))
  5310. platform::testModeLog ("live session: nothing to resume");
  5311. return;
  5312. }
  5313. if (cli.contains ("--live-rejoin"))
  5314. {
  5315. // (round 190ah, scripted: a guest goes back into its session without the question)
  5316. if (! live->resumeGuest (LiveSessionManager::defaultGuestJournal(), o))
  5317. platform::testModeLog ("live session: nothing to go back to");
  5318. return;
  5319. }
  5320. if (! cli.contains ("--live-host") && ! cli.contains ("--live-join"))
  5321. {
  5322. if (! platform::testMode())
  5323. liveui::offerResume (liveContext());
  5324. return;
  5325. }
  5326. if (const auto codeFile = value ("--live-host"); codeFile.isNotEmpty())
  5327. {
  5328. o.autoAccept = true; // (scripted: nobody to click "Let them in")
  5329. live->start (o);
  5330. auto poll = std::make_shared<std::function<void (int)>>();
  5331. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), codeFile, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  5332. if (safe == nullptr)
  5333. return;
  5334. if (safe->live->getState() == LiveSessionManager::State::live)
  5335. return (void) juce::File (codeFile).replaceWithText (safe->live->getInviteCode());
  5336. if (safe->live->isActive() && left > 0)
  5337. juce::Timer::callAfterDelay (200, [poll = weak.lock(), left] {
  5338. if (poll != nullptr)
  5339. (*poll) (left - 1);
  5340. });
  5341. else
  5342. juce::File (codeFile).replaceWithText ("ERROR " + safe->live->getStatus());
  5343. };
  5344. (*poll) (150);
  5345. // round 190ai: --live-share file.vst3 — once live, the host shares that plugin and shows its list
  5346. if (const auto pluginFile = value ("--live-share"); pluginFile.isNotEmpty())
  5347. juce::Timer::callAfterDelay (6000, [safe = juce::Component::SafePointer<MainComponent> (this), pluginFile] {
  5348. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  5349. return;
  5350. auto& plugins = safe->engine.getPluginHost();
  5351. plugins.addPluginFile (juce::File (pluginFile));
  5352. juce::String why = "not found";
  5353. bool ok = false;
  5354. for (const auto& type : plugins.getKnownPlugins().getTypes())
  5355. if (! ok && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginFile).getFileName())
  5356. ok = safe->live->sharePlugin (type.createIdentifierString().toStdString(), true, &why);
  5357. platform::testModeLog ("live session: --live-share " + pluginFile + (ok ? " shared" : " NOT shared: " + why));
  5358. liveui::showSharePlugins (*safe->live, safe->engine);
  5359. });
  5360. }
  5361. else if (auto code = value ("--live-join"); code.isNotEmpty())
  5362. {
  5363. if (code.startsWith ("@"))
  5364. code = juce::File (code.substring (1)).loadFileAsString().trim();
  5365. live->join (code, o);
  5366. // round 190ai: --live-use — when the host shares a plugin, a channel of one's own with it, a riff, and its
  5367. // parameter editor (the GUI check of remote plugins)
  5368. if (cli.contains ("--live-use"))
  5369. {
  5370. auto poll = std::make_shared<std::function<void (int)>>();
  5371. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  5372. if (safe == nullptr)
  5373. return;
  5374. if (! safe->live->mayUseSharedPlugins())
  5375. {
  5376. if (left > 0)
  5377. juce::Timer::callAfterDelay (500, [poll = weak.lock(), left] {
  5378. if (poll != nullptr)
  5379. (*poll) (left - 1);
  5380. });
  5381. return;
  5382. }
  5383. std::uint64_t uid = 0;
  5384. const auto channelName = (name + " remote").toStdString();
  5385. safe->engine.editSong ([&] (Song& s) {
  5386. ChannelDef c;
  5387. c.name = channelName;
  5388. c.instrument = InstrumentKind::plugin;
  5389. c.plugin = safe->live->sharedPluginRef (safe->live->sharedPlugins().front());
  5390. const auto* me = s.session.find (s.session.me);
  5391. c.mixerTrack = me != nullptr ? me->insertFirst : 0;
  5392. s.channels.push_back (c);
  5393. Pattern p;
  5394. p.name = channelName + " riff";
  5395. for (int n = 0; n < 4; ++n)
  5396. p.notes.push_back ({ (std::int64_t) n * ppq, ppq / 2, (int) s.channels.size() - 1, 57 + 2 * n, 0.9f });
  5397. s.patterns.push_back (p);
  5398. });
  5399. for (const auto& c : safe->engine.getSong().channels)
  5400. if (c.name == channelName)
  5401. uid = c.uid;
  5402. platform::testModeLog ("live session: --live-use channel " + juce::String (channelName) + " uid " + juce::String ((juce::int64) uid));
  5403. liveui::showHostedEditor ({ { live::Kind::channel, uid, 0 }, -1 });
  5404. };
  5405. (*poll) (120);
  5406. }
  5407. // --live-edit: once in, add a channel of one's own (the GUI check sees it arrive on the host)
  5408. if (cli.contains ("--live-edit"))
  5409. juce::Timer::callAfterDelay (8000, [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name] {
  5410. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  5411. return;
  5412. safe->engine.editSong ([&] (Song& s) {
  5413. ChannelDef c;
  5414. c.name = (name + " synth").toStdString();
  5415. c.instrument = InstrumentKind::synth;
  5416. s.channels.push_back (c);
  5417. });
  5418. });
  5419. }
  5420. }
  5421. void MainComponent::exportPackage()
  5422. {
  5423. // FL's zipped loop package: the project and every sample it uses in one .zip
  5424. const auto stem = projectStem (projectName);
  5425. const auto start = (currentFile != juce::File() ? currentFile.getParentDirectory()
  5426. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory))
  5427. .getChildFile (stem + ".zip");
  5428. fileChooser = lynx::ui::makeFileChooser (tr ("Export project with samples"), start, "*.zip");
  5429. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  5430. [safe = juce::Component::SafePointer<MainComponent> (this), stem] (const juce::FileChooser& chooser) {
  5431. auto zip = chooser.getResult();
  5432. if (safe == nullptr || zip == juce::File())
  5433. return;
  5434. zip = zip.withFileExtension (".zip");
  5435. safe->engine.capturePluginStates();
  5436. ProjectPackage::Result result;
  5437. juce::String error;
  5438. if (! ProjectPackage::exportZip (safe->engine.getSong(), stem, zip, result, error))
  5439. {
  5440. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  5441. return;
  5442. }
  5443. auto text = tr ("{0} saved with {1} samples.", { zip.getFileName(), juce::String (result.files) });
  5444. if (! result.missing.isEmpty())
  5445. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  5446. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Export project with samples"), text);
  5447. });
  5448. }
  5449. void MainComponent::collectSamples()
  5450. {
  5451. // FL's "Export project data files": copy the samples the project uses into one folder (and use the copies)
  5452. fileChooser = lynx::ui::makeFileChooser (tr ("Copy the project's samples to..."),
  5453. currentFile != juce::File() ? currentFile.getParentDirectory()
  5454. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  5455. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  5456. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  5457. const auto folder = chooser.getResult();
  5458. if (safe == nullptr || folder == juce::File())
  5459. return;
  5460. std::map<std::string, std::string> relink;
  5461. ProjectPackage::Result result;
  5462. juce::String error;
  5463. if (! ProjectPackage::collectSamples (safe->engine.getSong(), folder, relink, result, error))
  5464. {
  5465. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not copy"), error);
  5466. return;
  5467. }
  5468. safe->engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  5469. auto text = tr ("{0} samples copied to {1}. The project now uses the copies.", { juce::String (result.files), folder.getFullPathName() });
  5470. if (! result.missing.isEmpty())
  5471. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  5472. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Collect project samples"), text);
  5473. });
  5474. }
  5475. void MainComponent::saveToNewProjectFolder()
  5476. {
  5477. // FL's "Save to new project folder...": <chosen name>/<name>.lynx, so the project gets its own data folder (its
  5478. // recordings go to <name>/Audio/Recorded). This session's takes still in the global recordings folder move along
  5479. // (copied there, the project uses the copies; the originals are then offered for deletion as unused).
  5480. const auto start = currentFile != juce::File() ? currentFile.getParentDirectory()
  5481. : lynx::platform::documentsFolder().getChildFile ("LYNX/Projects");
  5482. start.createDirectory();
  5483. fileChooser = lynx::ui::makeFileChooser (tr ("Save to new project folder"),
  5484. start.getChildFile (projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled")),
  5485. juce::String ("*") + ProjectFile::extension);
  5486. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  5487. const auto chosen = chooser.getResult();
  5488. if (safe == nullptr || chosen == juce::File())
  5489. return;
  5490. const auto name = chosen.getFileNameWithoutExtension();
  5491. auto folder = chosen.getParentDirectory().getChildFile (name);
  5492. if (folder.exists() && ! folder.findChildFiles (juce::File::findFilesAndDirectories, false).isEmpty())
  5493. folder = folder.getNonexistentSibling (false);
  5494. if (! folder.createDirectory())
  5495. {
  5496. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  5497. tr ("Could not create the folder {0}", { folder.getFullPathName() }));
  5498. return;
  5499. }
  5500. auto& self = *safe;
  5501. const auto recorded = folder.getChildFile (safety::recordedSubfolder);
  5502. std::map<std::string, std::string> relink;
  5503. const auto used = safety::referencedSamples (self.engine.getSong());
  5504. for (const auto& take : self.engine.getSessionRecordings())
  5505. if (take.existsAsFile() && take.isAChildOf (AudioEngine::defaultRecordingFolder())
  5506. && std::any_of (used.begin(), used.end(), [&take] (const std::string& p) { return safety::samePath (p, take.getFullPathName().toStdString()); }))
  5507. {
  5508. recorded.createDirectory();
  5509. const auto copy = recorded.getNonexistentChildFile (take.getFileNameWithoutExtension(), take.getFileExtension(), false);
  5510. if (take.copyFileTo (copy))
  5511. relink[take.getFullPathName().toStdString()] = copy.getFullPathName().toStdString();
  5512. }
  5513. if (! relink.empty())
  5514. self.engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  5515. const auto file = folder.getChildFile (name + ProjectFile::extension);
  5516. juce::String error;
  5517. self.engine.capturePluginStates();
  5518. if (! ProjectFile::save (self.engine.getSong(), file, error))
  5519. {
  5520. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  5521. return;
  5522. }
  5523. self.engine.markSaved();
  5524. self.rememberRecent (file);
  5525. self.currentFile = file;
  5526. self.projectName = name;
  5527. self.importedSuffix = {};
  5528. self.updateTitle();
  5529. ui::postHint ({ tr ("Saved in its own folder: {0}", { folder.getFullPathName() }), {}, false, false }, 5000);
  5530. });
  5531. }
  5532. void MainComponent::startSession()
  5533. {
  5534. // Like FL's backup on crash: a marker exists while LYNX runs; finding one at start means the last session
  5535. // ended without closing (crash, power loss), so the newest backup written during it is offered.
  5536. sessionLock = std::make_unique<juce::InterProcessLock> ("LYNX-ui-session");
  5537. if (! sessionLock->enter (0))
  5538. {
  5539. sessionLock.reset(); // another LYNX window is running: it owns the marker
  5540. return;
  5541. }
  5542. sessionMarker = lynx::platform::settingsFile ("session-running.txt");
  5543. if (sessionMarker.existsAsFile())
  5544. {
  5545. const auto previousStart = juce::Time (sessionMarker.loadFileAsString().trim().getLargeIntValue());
  5546. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this), previousStart] {
  5547. if (safe != nullptr)
  5548. safe->checkPreviousSession (previousStart);
  5549. });
  5550. }
  5551. sessionMarker.getParentDirectory().createDirectory();
  5552. sessionMarker.replaceWithText (juce::String (juce::Time::getCurrentTime().toMilliseconds()));
  5553. // takes that were recording when LYNX stopped (crash, power loss, closed while recording): after the backup offer
  5554. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  5555. if (safe != nullptr)
  5556. safe->checkInterruptedTakes();
  5557. });
  5558. }
  5559. void MainComponent::checkInterruptedTakes()
  5560. {
  5561. if (juce::Component::getCurrentlyModalComponent() != nullptr) // a dialog is open (the backup offer): ask later
  5562. {
  5563. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  5564. if (safe != nullptr)
  5565. safe->checkInterruptedTakes();
  5566. });
  5567. return;
  5568. }
  5569. std::vector<juce::File> folders { engine.getRecordingFolder() };
  5570. const auto takes = engine.recoverInterruptedTakes (folders);
  5571. if (takes.empty())
  5572. return;
  5573. juce::StringArray names;
  5574. for (const auto& j : takes)
  5575. names.add (juce::File (juce::String::fromUTF8 (j.wav.c_str())).getFileName());
  5576. const auto folder = juce::File (juce::String::fromUTF8 (takes.front().wav.c_str())).getParentDirectory();
  5577. auto* w = new juce::AlertWindow (tr ("Recordings recovered"),
  5578. tr ("LYNX SHARE was recording when it stopped. These takes were saved and repaired:\n{0}\n\nPut them on the Playlist "
  5579. "where they were recorded?", { names.joinIntoString ("\n") }),
  5580. juce::MessageBoxIconType::InfoIcon);
  5581. w->addButton (tr ("Put them on the Playlist"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5582. w->addButton (tr ("Show the folder"), 2);
  5583. w->addButton (tr ("Keep the files only"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5584. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), takes, folder] (int result) {
  5585. if (safe == nullptr)
  5586. return;
  5587. if (result == 1)
  5588. {
  5589. const auto placed = safe->engine.placeRecoveredTakes (takes);
  5590. ui::postHint ({ tr ("{0} recovered take(s) placed on the Playlist", { juce::String (placed) }), {}, false, false }, 5000);
  5591. }
  5592. else
  5593. {
  5594. if (result == 2)
  5595. folder.startAsProcess();
  5596. safe->engine.forgetInterruptedTakes (takes);
  5597. }
  5598. }),
  5599. true);
  5600. }
  5601. void MainComponent::checkPreviousSession (juce::Time sessionStart)
  5602. {
  5603. if (juce::Component::getCurrentlyModalComponent() != nullptr) // the setup wizard or another dialog: ask later
  5604. {
  5605. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this), sessionStart] {
  5606. if (safe != nullptr)
  5607. safe->checkPreviousSession (sessionStart);
  5608. });
  5609. return;
  5610. }
  5611. const auto folder = autosaveFolder();
  5612. const auto name = safety::crashRecoveryCandidate (backupFiles (folder), sessionStart.toMilliseconds());
  5613. if (name.empty())
  5614. return; // nothing was saved in that session
  5615. const auto backup = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  5616. auto* w = new juce::AlertWindow (tr ("LYNX SHARE did not close properly"),
  5617. tr ("The last session ended unexpectedly. Open the newest backup it saved?\n{0} ({1})",
  5618. { backup.getFileName(), backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M") }),
  5619. juce::MessageBoxIconType::WarningIcon);
  5620. w->addButton (tr ("Open backup"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5621. w->addButton (tr ("Open backup folder"), 2);
  5622. w->addButton (tr ("Ignore"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5623. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup, folder] (int result) {
  5624. if (safe == nullptr)
  5625. return;
  5626. if (result == 1)
  5627. safe->confirmDiscard ([safe, backup] {
  5628. if (safe != nullptr)
  5629. safe->openLynxProject (backup);
  5630. });
  5631. else if (result == 2)
  5632. folder.startAsProcess();
  5633. }),
  5634. true);
  5635. }
  5636. void MainComponent::newProject (bool askAlways)
  5637. {
  5638. confirmDiscard ([this, askAlways] {
  5639. if (! askAlways && ! newProjectDialogEnabled())
  5640. {
  5641. // FL's File › New: a new project from the default template (issue #123)
  5642. bool missing = false;
  5643. auto song = makeDefaultTemplateProject (&missing);
  5644. startNewProject (std::move (song), {});
  5645. if (missing)
  5646. ui::postHint ({ tr ("The default template was not found; LYNX SHARE's default project opened instead") }, 6000);
  5647. return;
  5648. }
  5649. showNewProjectDialog ([safe = juce::Component::SafePointer<MainComponent> (this)] (Song song, juce::File file) {
  5650. if (safe != nullptr)
  5651. safe->startNewProject (std::move (song), file);
  5652. });
  5653. });
  5654. }
  5655. void MainComponent::openStartupProject()
  5656. {
  5657. // (only over the untouched start-up song: a file, a resumed session or an edit made meanwhile stays)
  5658. if (currentFile != juce::File() || projectName.isNotEmpty() || engine.isModified())
  5659. return;
  5660. switch (startupProject())
  5661. {
  5662. case StartupProject::lastProject:
  5663. // FL's "Last used project": the project itself (saving goes to it), when it is still there
  5664. if (const auto last = recent.getFile (0); last.existsAsFile())
  5665. {
  5666. openFile (last);
  5667. return;
  5668. }
  5669. break; // (none, or gone: the default template, as FL's default)
  5670. case StartupProject::emptyProject:
  5671. if (const auto empty = builtInTemplateIndex ("Empty"); empty >= 0)
  5672. startNewProject (makeNewProject (empty), {});
  5673. return;
  5674. case StartupProject::defaultTemplate:
  5675. break;
  5676. }
  5677. if (defaultTemplate().isLynxDefault())
  5678. return; // (the start-up song is LYNX's default already)
  5679. bool missing = false;
  5680. auto song = makeDefaultTemplateProject (&missing);
  5681. if (missing)
  5682. {
  5683. ui::postHint ({ tr ("The default template was not found; LYNX SHARE's default project opened instead") }, 6000);
  5684. return;
  5685. }
  5686. startNewProject (std::move (song), {});
  5687. }
  5688. void MainComponent::startNewProject (Song song, const juce::File& file)
  5689. {
  5690. engine.stop();
  5691. engine.rewind();
  5692. engine.setSong (std::move (song));
  5693. engine.markCreatedNow(); // Project info › created (a template's own date is kept, as FL does)
  5694. currentFile = juce::File();
  5695. projectName = {};
  5696. importedSuffix = {};
  5697. if (file != juce::File())
  5698. {
  5699. juce::String error;
  5700. file.getParentDirectory().createDirectory();
  5701. if (ProjectFile::save (engine.getSong(), file, error))
  5702. {
  5703. engine.markSaved();
  5704. rememberRecent (file);
  5705. currentFile = file;
  5706. projectName = file.getFileNameWithoutExtension();
  5707. }
  5708. else
  5709. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  5710. }
  5711. updateTitle();
  5712. }
  5713. // 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
  5714. // separate process from now on (like Processing › "Always run … in a separate process": persisted, applied at once)
  5715. void MainComponent::announceEditorCrash (const juce::String& plugin)
  5716. {
  5717. const auto offerSeparate = ! pluginSandboxEnabled() && ! pluginAlwaysSeparate (plugin) && plugin != "?";
  5718. auto options = juce::MessageBoxOptions()
  5719. .withIconType (juce::MessageBoxIconType::WarningIcon)
  5720. .withTitle (tr ("Plugin crashed"))
  5721. .withMessage (tr ("{0} crashed. Save your project now (as a new file is safest).", { plugin }) + "\n\n"
  5722. + tr ("Its window was closed so that LYNX SHARE could keep running. The plugin may not work "
  5723. "properly until the project is opened again."))
  5724. .withButton (tr ("Save as..."));
  5725. if (offerSeparate)
  5726. options = options.withButton (tr ("Always run {0} in a separate process", { plugin }));
  5727. options = options.withButton (tr ("Close"));
  5728. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), plugin, offerSeparate] (int result) {
  5729. if (safe == nullptr)
  5730. return;
  5731. if (result == 1)
  5732. safe->save (true);
  5733. else if (result == 2 && offerSeparate)
  5734. {
  5735. safe->engine.capturePluginStates(); // the new instances start from the current settings
  5736. setPluginAlwaysSeparate (plugin, true);
  5737. const auto name = plugin.toStdString();
  5738. safe->engine.editSong ([name] (Song& song) {
  5739. for (auto& c : song.channels)
  5740. if (c.instrument == InstrumentKind::plugin && c.plugin.name == name)
  5741. c.plugin.separateProcess = true;
  5742. for (auto& track : song.mixer)
  5743. for (auto& fx : track.effects)
  5744. if (fx.kind == EffectKind::plugin && fx.plugin.name == name)
  5745. fx.plugin.separateProcess = true;
  5746. });
  5747. }
  5748. });
  5749. }
  5750. // Round 190ao: "Reload" of a crash prompt: the plugins of that name that are down (the prompt only knows the name the
  5751. // plugin reports; when the project knows it under another name, every plugin that is down)
  5752. void MainComponent::reloadCrashedPlugins (const juce::String& plugin)
  5753. {
  5754. auto which = engine.downHostedPlugins (plugin.toStdString());
  5755. if (which.empty())
  5756. which = engine.downHostedPlugins();
  5757. if (! which.empty())
  5758. PluginWindows::reload (engine, which);
  5759. }
  5760. // Round 176a: round 174a's "Plugin crashed" prompt for a plugin whose separate process died. LYNX itself is unharmed
  5761. // (the plugin ran in its own process), so it offers the save and says how to get the plugin back.
  5762. void MainComponent::announceSeparateProcessCrash (const juce::String& plugin, bool crashed, bool bits32)
  5763. {
  5764. const auto name = plugin.isNotEmpty() ? plugin : tr ("A plugin");
  5765. const auto where = bits32 ? tr ("{0} crashed in the 32-bit bridge.", { name }) : tr ("{0} crashed in its separate process.", { name });
  5766. auto options = juce::MessageBoxOptions()
  5767. .withIconType (juce::MessageBoxIconType::WarningIcon)
  5768. .withTitle (tr ("Plugin crashed"))
  5769. .withMessage ((crashed ? where : tr ("{0} stopped responding (separate process).", { name })) + "\n\n"
  5770. + tr ("Only its process was affected: LYNX SHARE and your project kept running, and the plugin "
  5771. "was muted. Save your project.")
  5772. + " " + tr ("Reload starts it again with the settings from the last save or backup."))
  5773. .withButton (tr ("Reload")) // (round 190ao: without reopening the project; only on request)
  5774. .withButton (tr ("Save as..."))
  5775. .withButton (tr ("Close"));
  5776. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), plugin] (int result) {
  5777. if (safe == nullptr)
  5778. return;
  5779. if (result == 1)
  5780. safe->reloadCrashedPlugins (plugin);
  5781. else if (result == 2)
  5782. safe->save (true);
  5783. });
  5784. }
  5785. void MainComponent::saveAsTemplate()
  5786. {
  5787. auto* w = new juce::AlertWindow (tr ("Save as template"), tr ("The template appears in File › New project... (saved in {0})", { userTemplatesFolder().getFullPathName() }),
  5788. juce::MessageBoxIconType::NoIcon);
  5789. w->addTextEditor ("name", projectName.isNotEmpty() ? projectName : tr ("My template"));
  5790. w->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5791. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5792. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, safe = juce::Component::SafePointer<MainComponent> (this)] (int result) {
  5793. if (result != 1 || safe == nullptr)
  5794. return;
  5795. safe->engine.capturePluginStates();
  5796. juce::String error;
  5797. if (! saveUserTemplate (safe->engine.getSong(), w->getTextEditorContents ("name"), error))
  5798. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  5799. }), true);
  5800. }
  5801. void MainComponent::chooseFileToOpen()
  5802. {
  5803. confirmDiscard ([this] { chooseFileToOpenNow(); });
  5804. }
  5805. void MainComponent::chooseFileToOpenNow()
  5806. {
  5807. fileChooser = lynx::ui::makeFileChooser (tr ("Open project"), currentFile.getParentDirectory(),
  5808. juce::String ("*") + ProjectFile::extension + ";*.dawproj;*.flp;*.als;*.flm;*.zip;*.lynxpack;*.mid;*.midi");
  5809. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  5810. [this] (const juce::FileChooser& chooser) {
  5811. if (chooser.getResult().existsAsFile())
  5812. openFile (chooser.getResult());
  5813. });
  5814. }
  5815. void MainComponent::openFileRequest (const juce::File& file)
  5816. {
  5817. const juce::Component::SafePointer<MainComponent> safe (this);
  5818. if (projectLoadRunning())
  5819. {
  5820. juce::Timer::callAfterDelay (500, [safe, file] {
  5821. if (safe != nullptr)
  5822. safe->openFileRequest (file);
  5823. });
  5824. return;
  5825. }
  5826. confirmDiscard ([safe, file] {
  5827. if (safe != nullptr)
  5828. safe->openFile (file);
  5829. });
  5830. }
  5831. void MainComponent::openFile (const juce::File& file)
  5832. {
  5833. juce::String error;
  5834. crashguard::note (("opening project " + file.getFileName()).toStdString()); // session breadcrumb (round 111)
  5835. if (file.hasFileExtension ("zip"))
  5836. {
  5837. // a project package (File › Export project with samples, or FL's zipped loop package): extracted into a
  5838. // folder of its own, then the project inside is opened (its samples are found next to it)
  5839. const auto project = ProjectPackage::extractZip (file, ProjectPackage::defaultExtractRoot(), error);
  5840. if (project == juce::File())
  5841. {
  5842. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5843. return;
  5844. }
  5845. openFile (project);
  5846. return;
  5847. }
  5848. if (file.hasFileExtension (sessionpack::extension))
  5849. {
  5850. // Online Sessions (round 168a): a project a friend sent (opened after a summary) or a part sent back (merged)
  5851. sessionui::openPackage (sessionContext(), file);
  5852. return;
  5853. }
  5854. if (file.hasFileExtension ("mid;midi"))
  5855. {
  5856. auto song = MidiFileIo::loadSong (file, error);
  5857. if (! song)
  5858. {
  5859. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5860. return;
  5861. }
  5862. engine.stop();
  5863. engine.rewind();
  5864. engine.setSong (std::move (*song));
  5865. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  5866. projectName = file.getFileNameWithoutExtension();
  5867. rememberRecent (file);
  5868. importedSuffix = " " + tr ("(imported from MIDI)");
  5869. updateTitle();
  5870. return;
  5871. }
  5872. // (a Live set takes the .flp import's path, round 175a; an FL Studio Mobile project too, round 182c)
  5873. if (file.hasFileExtension ("flp;als;flm;songtmpl"))
  5874. {
  5875. if (! persistent) // (command-line modes open synchronously, without scanning)
  5876. {
  5877. importFlp (file);
  5878. return;
  5879. }
  5880. // behind a progress panel (round 112): the project's unknown plugins get a targeted scan of just their files,
  5881. // the samples are decoded off the message thread, the hosted plugins are created one by one with their names
  5882. // shown; the panel's bar never sits still at 0 %
  5883. if (projectLoadRunning())
  5884. return;
  5885. openFlpWithProgress (*this, engine, file, [safe = juce::Component::SafePointer<MainComponent> (this), file] (bool ok, const juce::String& error) {
  5886. if (safe == nullptr)
  5887. return;
  5888. if (! ok)
  5889. {
  5890. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5891. return;
  5892. }
  5893. safe->flpImported (file);
  5894. });
  5895. return;
  5896. }
  5897. openLynxProject (file);
  5898. }
  5899. void MainComponent::importFlp (const juce::File& file)
  5900. {
  5901. juce::String error;
  5902. loadtrace::begin (file.getFullPathName().toStdString());
  5903. const auto ok = engine.importFlpFile (file, error);
  5904. loadtrace::end();
  5905. if (! ok)
  5906. {
  5907. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5908. return;
  5909. }
  5910. flpImported (file);
  5911. }
  5912. void MainComponent::flpImported (const juce::File& file)
  5913. {
  5914. {
  5915. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  5916. importedFlpFile = file;
  5917. projectName = file.getFileNameWithoutExtension();
  5918. rememberRecent (file);
  5919. importedSuffix = " " + (file.hasFileExtension ("als") ? tr ("(imported from .als)")
  5920. : file.hasFileExtension ("flm;songtmpl") ? tr ("(imported from FL Studio Mobile)")
  5921. : tr ("(imported from FL Studio)"));
  5922. updateTitle();
  5923. playlist.showSongAfterOpen();
  5924. showMissingFiles (true);
  5925. // FL opens Project info when the project's "Show on opening" box is on (event 0x0A, REA round 167g)
  5926. if (engine.getSong().info.showOnOpen && platform::testMode())
  5927. platform::testModeLog ("project info shown on open");
  5928. else if (engine.getSong().info.showOnOpen)
  5929. openSettings ((int) SettingsPage::info);
  5930. }
  5931. }
  5932. void MainComponent::chooseFileToOpenWithoutPlugins()
  5933. {
  5934. confirmDiscard ([this] {
  5935. fileChooser = lynx::ui::makeFileChooser (tr ("Open without third-party plugins"), currentFile.getParentDirectory(), juce::String ("*") + ProjectFile::extension);
  5936. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  5937. [this] (const juce::FileChooser& chooser) {
  5938. if (chooser.getResult().existsAsFile())
  5939. {
  5940. crashguard::note (("opening project without plugins " + chooser.getResult().getFileName()).toStdString());
  5941. openLynxProject (chooser.getResult(), true);
  5942. }
  5943. });
  5944. });
  5945. }
  5946. void MainComponent::showPluginsOff()
  5947. {
  5948. if (auto* open = findToolWindow ("pluginsOff"))
  5949. {
  5950. open->toFront (true);
  5951. return;
  5952. }
  5953. if (auto* window = openToolWindow (makePluginsOffPanel (engine), tr ("Third-party plugins"), "pluginsOff"))
  5954. window->setResizable (true, false);
  5955. }
  5956. void MainComponent::openLynxProject (const juce::File& file, bool withoutPlugins)
  5957. {
  5958. juce::String error, savedBy;
  5959. auto song = ProjectFile::load (file, error, &savedBy);
  5960. if (! song)
  5961. {
  5962. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  5963. return;
  5964. }
  5965. withoutPlugins = withoutPlugins || std::exchange (nextOpenWithoutPlugins, false);
  5966. engine.stop();
  5967. engine.rewind();
  5968. if (withoutPlugins)
  5969. {
  5970. // round 190ap: no hosted plugin is created and no slot is changed (no substitutes either): each keeps the
  5971. // settings the file has, which is also what a save made now writes
  5972. engine.setSongWithPluginsOff (std::move (*song));
  5973. }
  5974. else
  5975. {
  5976. // missing plugins get their LYNX substitute; substitutes whose original is installed now go back to it
  5977. engine.getPluginHost().applySubstitutes (*song);
  5978. engine.setSong (std::move (*song));
  5979. }
  5980. currentFile = file;
  5981. importedFlpFile = juce::File();
  5982. projectName = file.getFileNameWithoutExtension();
  5983. importedSuffix = {};
  5984. rememberRecent (file);
  5985. updateTitle();
  5986. playlist.showSongAfterOpen();
  5987. // pain point 37 (round 177d): a project from a newer LYNX SHARE opens, but saving it here would drop what that
  5988. // version added, so say so once (FL warns about a project from a more recent version too)
  5989. if (safety::savedByNewerVersion (savedBy.toStdString(), JUCE_APPLICATION_VERSION_STRING))
  5990. {
  5991. platform::testModeLog ("project saved by newer version " + savedBy);
  5992. if (! platform::testMode())
  5993. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Saved by a newer version"),
  5994. tr ("This project was saved by LYNX SHARE {0}, and this is {1}. What the newer version added may be "
  5995. "lost if you save it here: use File › Save as... to keep the original.",
  5996. { savedBy, JUCE_APPLICATION_VERSION_STRING }));
  5997. }
  5998. if (engine.pluginsOff())
  5999. {
  6000. platform::testModeLog ("project opened without third-party plugins");
  6001. ui::postHint ({ tr ("Opened without third-party plugins: their settings are kept"), {}, false, false }, 8000);
  6002. if (persistent && ! engine.hostedPluginUses().empty())
  6003. showPluginsOff();
  6004. }
  6005. if (persistent)
  6006. {
  6007. showMissingFiles (true);
  6008. if (engine.getSong().info.showOnOpen && platform::testMode())
  6009. platform::testModeLog ("project info shown on open");
  6010. else if (engine.getSong().info.showOnOpen)
  6011. openSettings (1);
  6012. }
  6013. }
  6014. void MainComponent::openSettings (int page)
  6015. {
  6016. const juce::Component::SafePointer<MainComponent> safe (this);
  6017. SettingsHooks hooks;
  6018. hooks.browserFoldersChanged = [safe] {
  6019. if (safe != nullptr)
  6020. safe->browser.reloadUserFolders();
  6021. };
  6022. hooks.getGeneral = [safe] {
  6023. GeneralOptions o;
  6024. if (safe == nullptr)
  6025. return o;
  6026. o.language = i18n::saved();
  6027. o.uiFont = theme::savedUiFont();
  6028. o.uiScale = safe->toolbarLayout.uiScale;
  6029. o.compactMenus = theme::menus::compact();
  6030. o.waveSpectral = ui::WaveformCache::spectral;
  6031. o.waveStereo = ui::WaveformCache::stereo;
  6032. o.noteNames = notenames::currentStyle.load();
  6033. o.noteFlats = notenames::currentFlats.load();
  6034. o.noteNamesEveryKey = notenames::everyKey.load();
  6035. o.rackPlayheadColumn = ChannelRackComponent::playheadColumn.load();
  6036. o.rackStepsChannelColour = ChannelRackComponent::stepsChannelColour.load();
  6037. o.reducedEffects = skin::reducedEffects();
  6038. o.animationRate = ui::FrameTicker::rateLimit();
  6039. o.artMotion = skin::artMotion();
  6040. o.uiAnimations = ui::motion::enabled();
  6041. o.gpuRendering = gpuRenderingEnabled();
  6042. o.pluginStyle = skin::forcedStyle();
  6043. o.splash = safe->startup.splash;
  6044. o.startupSound = safe->startup.sound;
  6045. o.scanAtStart = backgroundScanAtStart();
  6046. o.defaultTemplate = juce::String::fromUTF8 (defaultTemplate().toText().c_str());
  6047. o.startupProject = (int) startupProject();
  6048. o.typingPiano = safe->typingPiano;
  6049. o.keepEditorsOpen = ChannelRackComponent::keepEditorsOpen;
  6050. o.selectFirstChannelWithNotes = ChannelRackComponent::selectFirstChannelWithNotes;
  6051. o.monophonicPainting = PianoRollComponent::monophonicPainting;
  6052. o.detachNewPlugins = safe->engine.detachesNewPlugins();
  6053. o.autoSelectLinked = ChannelRackComponent::autoSelectLinked;
  6054. o.alternateUndo = safe->alternateUndo;
  6055. o.rememberSeek = EditorGlobals::get().rememberSeek;
  6056. o.stretchedClipsLoop = stretchedClipsLoop();
  6057. o.autoClipsAtPlayback = autoclipplace::atPlayback();
  6058. o.disableTypingPriority = pluginkeys::newPluginsHostFirst().load();
  6059. o.layoutStyle = (int) safe->layoutStyle;
  6060. o.alsSessionOnPlaylist = AudioEngine::alsSessionOnPlaylist.load();
  6061. o.editPatternsIn = PlaylistComponent::editPatternsIn;
  6062. o.undoLevels = safe->engine.getUndoLevels();
  6063. o.autosaveMinutes = safe->autosaveMinutes;
  6064. o.autosaveKeep = safe->autosaveKeep;
  6065. o.askUnusedRecordings = safe->askUnusedRecordings;
  6066. o.backupWaitsForQuiet = safe->backupWaitsForQuiet;
  6067. o.backupLongestWaitMinutes = safe->backupLongestWaitMinutes;
  6068. o.hoverValues = safe->hoverValues;
  6069. o.crossfadesInNewProjects = newProjectDefaults().autoCrossfades;
  6070. o.pluginSandbox = pluginSandboxEnabled();
  6071. o.menuEntry = appImageMenuEntryInstalled();
  6072. o.pluginSubstitutes = pluginSubstitutesEnabled();
  6073. o.limitEditors = editorlimit::enabled();
  6074. o.crashReports = (int) crashreporter::consent();
  6075. o.checkUpdates = updater::automatic();
  6076. return o;
  6077. };
  6078. hooks.setGeneral = [safe] (const GeneralOptions& o) {
  6079. if (safe == nullptr)
  6080. return;
  6081. auto& self = *safe;
  6082. if (o.uiScale != self.toolbarLayout.uiScale)
  6083. {
  6084. auto layout = self.toolbarLayout;
  6085. layout.uiScale = toolbarlayout::clampScale (o.uiScale);
  6086. self.setToolbarLayout (layout, true);
  6087. }
  6088. theme::menus::setCompact (o.compactMenus);
  6089. ui::FrameTicker::rateLimit() = o.animationRate; // (the tickers read it every frame)
  6090. ui::motion::enabled() = o.uiAnimations;
  6091. if (o.reducedEffects != skin::reducedEffects() || o.pluginStyle != skin::forcedStyle() || o.artMotion != skin::artMotion())
  6092. {
  6093. skin::setArtMotion (o.artMotion);
  6094. skin::setReducedEffects (o.reducedEffects);
  6095. skin::setForcedStyle (o.pluginStyle);
  6096. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // open editors redraw at once
  6097. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  6098. }
  6099. if (o.noteNames != notenames::currentStyle.load() || o.noteFlats != notenames::currentFlats.load()
  6100. || o.noteNamesEveryKey != notenames::everyKey.load())
  6101. {
  6102. notenames::currentStyle.store (juce::jlimit (0, 2, o.noteNames));
  6103. notenames::currentFlats.store (o.noteFlats);
  6104. notenames::everyKey.store (o.noteNamesEveryKey);
  6105. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // the keyboards redraw with the new names
  6106. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  6107. }
  6108. if (o.rackPlayheadColumn != ChannelRackComponent::playheadColumn.load()
  6109. || o.rackStepsChannelColour != ChannelRackComponent::stepsChannelColour.load())
  6110. {
  6111. ChannelRackComponent::playheadColumn.store (o.rackPlayheadColumn);
  6112. ChannelRackComponent::stepsChannelColour.store (o.rackStepsChannelColour);
  6113. self.rack.repaint();
  6114. }
  6115. if (o.gpuRendering != gpuRenderingEnabled())
  6116. setGpuRenderingEnabled (o.gpuRendering);
  6117. if (o.waveSpectral != ui::WaveformCache::spectral || o.waveStereo != ui::WaveformCache::stereo)
  6118. {
  6119. ui::WaveformCache::spectral = o.waveSpectral;
  6120. ui::WaveformCache::stereo = o.waveStereo;
  6121. ui::WaveformCache::getInstance()->settingsChanged();
  6122. }
  6123. if (o.typingPiano != self.typingPiano)
  6124. self.setTypingPiano (o.typingPiano);
  6125. if (o.scanAtStart != backgroundScanAtStart())
  6126. setBackgroundScanAtStart (o.scanAtStart);
  6127. if (o.defaultTemplate.toStdString() != defaultTemplate().toText())
  6128. setDefaultTemplate (TemplateChoice::parse (o.defaultTemplate.toStdString()));
  6129. if (o.startupProject != (int) startupProject())
  6130. setStartupProject ((StartupProject) juce::jlimit (0, 2, o.startupProject));
  6131. if (o.pluginSandbox != pluginSandboxEnabled())
  6132. setPluginSandboxEnabled (o.pluginSandbox);
  6133. if (runningAsAppImage() && o.menuEntry != appImageMenuEntryInstalled())
  6134. setAppImageMenuEntry (o.menuEntry);
  6135. editorlimit::enabled() = o.limitEditors;
  6136. if (o.pluginSubstitutes != pluginSubstitutesEnabled())
  6137. setPluginSubstitutesEnabled (o.pluginSubstitutes);
  6138. if (o.crashReports != (int) crashreporter::consent())
  6139. crashreporter::setConsent ((crashreport::Consent) juce::jlimit (0, 2, o.crashReports));
  6140. updater::setAutomatic (o.checkUpdates);
  6141. ChannelRackComponent::keepEditorsOpen = o.keepEditorsOpen;
  6142. ChannelRackComponent::selectFirstChannelWithNotes = o.selectFirstChannelWithNotes;
  6143. PianoRollComponent::monophonicPainting = o.monophonicPainting;
  6144. self.engine.setDetachNewPlugins (o.detachNewPlugins);
  6145. ChannelRackComponent::autoSelectLinked = o.autoSelectLinked;
  6146. self.alternateUndo = o.alternateUndo;
  6147. EditorGlobals::get().rememberSeek = o.rememberSeek;
  6148. autoclipplace::setAtPlayback (o.autoClipsAtPlayback);
  6149. pluginkeys::newPluginsHostFirst() = o.disableTypingPriority;
  6150. self.setLayoutStyle ((layoutstyle::Style) juce::jlimit (0, layoutstyle::count - 1, o.layoutStyle));
  6151. AudioEngine::alsSessionOnPlaylist = o.alsSessionOnPlaylist;
  6152. if (o.stretchedClipsLoop != stretchedClipsLoop())
  6153. {
  6154. setStretchedClipsLoop (o.stretchedClipsLoop);
  6155. self.repaint(); // the Playlist draws what plays
  6156. }
  6157. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, o.editPatternsIn);
  6158. self.startup.splash = o.splash;
  6159. self.startup.sound = o.startupSound;
  6160. self.engine.setUndoLevels (o.undoLevels);
  6161. self.autosaveMinutes = prefs::clampAutosaveMinutes (o.autosaveMinutes);
  6162. self.autosaveKeep = prefs::clampAutosaveKeep (o.autosaveKeep);
  6163. self.askUnusedRecordings = o.askUnusedRecordings;
  6164. self.backupWaitsForQuiet = o.backupWaitsForQuiet;
  6165. self.backupLongestWaitMinutes = prefs::clampBackupLongestWait (o.backupLongestWaitMinutes);
  6166. if (self.hoverValues && ! o.hoverValues && self.hoverTipShown)
  6167. ui::hideValueTip();
  6168. self.hoverValues = o.hoverValues;
  6169. self.hoverTipShown = false;
  6170. newProjectDefaults().autoCrossfades = o.crossfadesInNewProjects;
  6171. self.autosaveTicks = 0;
  6172. self.saveUiSettings();
  6173. if (o.uiFont != theme::savedUiFont())
  6174. theme::saveUiFont (o.uiFont);
  6175. if (o.language != i18n::saved())
  6176. self.showLanguageChoice (o.language);
  6177. };
  6178. hooks.manageShortcuts = [safe] {
  6179. if (safe != nullptr)
  6180. safe->showShortcutManager();
  6181. };
  6182. hooks.managePlugins = [safe] {
  6183. if (safe != nullptr)
  6184. safe->showPluginManager();
  6185. };
  6186. hooks.runAction = [safe] (const std::string& id) { return safe != nullptr && safe->runAction (id); };
  6187. hooks.midiChanged = [safe] {
  6188. if (safe != nullptr)
  6189. safe->updateGamepad();
  6190. };
  6191. showSettings (engine, (SettingsPage) juce::jlimit (0, (int) SettingsPage::extras, page), std::move (hooks)); // (Theme was clamped to MIDI)
  6192. }
  6193. void MainComponent::showPluginManager()
  6194. {
  6195. lynx::showPluginManager (engine, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  6196. if (safe != nullptr)
  6197. safe->openSettings ((int) SettingsPage::files);
  6198. });
  6199. }
  6200. void MainComponent::showShortcutManager()
  6201. {
  6202. lynx::showShortcutManager ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  6203. if (safe == nullptr)
  6204. return;
  6205. safe->loadKeyMap();
  6206. safe->setControlHints();
  6207. safe->menuItemsChanged();
  6208. });
  6209. }
  6210. void MainComponent::showMissingFiles (bool afterOpening)
  6211. {
  6212. if (afterOpening && platform::testMode()) // (LYNX_TEST_MODE: nothing waits for a click)
  6213. {
  6214. platform::testModeLog ("Missing files dialog after opening " + projectName);
  6215. return;
  6216. }
  6217. MissingFilesInfo info;
  6218. info.projectName = projectName;
  6219. const auto fromFlp = importedFlpFile.existsAsFile() && currentFile == juce::File();
  6220. 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(); };
  6221. if (fromFlp)
  6222. {
  6223. // the import dropped the samples it couldn't find: its report keeps them (minus the ones located since)
  6224. const auto& report = engine.getImportReport();
  6225. for (const auto& m : report.missingFiles)
  6226. info.files.push_back (m);
  6227. info.plugins = engine.getMissingPluginDetails();
  6228. info.autoRelocated = report.relocatedFiles;
  6229. info.searchFolders.add (importedFlpFile.getParentDirectory().getFullPathName());
  6230. }
  6231. else
  6232. {
  6233. const auto& song = engine.getSong();
  6234. info.files = findMissingSamples (song, exists);
  6235. auto& host = engine.getPluginHost();
  6236. auto addPlugin = [&info] (const PluginRef& ref, const std::string& user, const char* replacement) {
  6237. const auto name = ref.name.empty() ? ref.id : ref.name;
  6238. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  6239. if (it == info.plugins.end())
  6240. it = info.plugins.insert (info.plugins.end(), MissingPlugin { name, {}, replacement });
  6241. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  6242. it->usedBy.push_back (user);
  6243. };
  6244. for (const auto& c : song.channels)
  6245. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty() && host.find (juce::String::fromUTF8 (c.plugin.id.c_str())) == nullptr)
  6246. addPlugin (c.plugin, c.name, "Silence: the channel keeps the plugin's settings until it is installed");
  6247. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  6248. for (const auto& fx : song.mixer[t].effects)
  6249. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty() && host.find (juce::String::fromUTF8 (fx.plugin.id.c_str())) == nullptr)
  6250. addPlugin (fx.plugin, song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name,
  6251. "Bypassed: the slot keeps the plugin's settings until it is installed");
  6252. // played by a LYNX substitute until the original is installed
  6253. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  6254. for (const auto& fx : song.mixer[t].effects)
  6255. if (fx.isSubstitute())
  6256. {
  6257. const auto name = substituteOriginalName (fx);
  6258. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  6259. if (it == info.plugins.end())
  6260. it = info.plugins.insert (info.plugins.end(),
  6261. 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"),
  6262. effectInfo (fx.kind).name });
  6263. const auto user = song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name;
  6264. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  6265. it->usedBy.push_back (user);
  6266. }
  6267. // installed, but failed to load: they play silence / are bypassed
  6268. for (const auto& line : host.getLoadFailures())
  6269. if (std::none_of (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == line.toStdString(); }))
  6270. info.plugins.push_back ({ line.toStdString(), {}, "Silence: the plugin is installed but did not load" });
  6271. if (currentFile.existsAsFile())
  6272. info.searchFolders.add (currentFile.getParentDirectory().getFullPathName());
  6273. }
  6274. if (afterOpening && info.files.empty() && info.plugins.empty())
  6275. {
  6276. if (fromFlp)
  6277. showImportReport();
  6278. return;
  6279. }
  6280. auto safe = juce::Component::SafePointer<MainComponent> (this);
  6281. const auto flp = fromFlp ? importedFlpFile : juce::File();
  6282. showMissingFilesDialog (
  6283. std::move (info),
  6284. [safe, flp] (const std::map<std::string, std::string>& relocations) {
  6285. if (safe == nullptr)
  6286. return;
  6287. if (flp != juce::File())
  6288. {
  6289. // FL import: imported again with the located samples (the channels become samplers, slices are read...)
  6290. juce::String error;
  6291. if (! safe->engine.importFlpFile (flp, error, relocations, true))
  6292. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6293. }
  6294. else
  6295. safe->engine.editSong ([&relocations] (Song& s) { applyRelocations (s, relocations); });
  6296. safe->updateTitle();
  6297. },
  6298. [safe, afterOpening, fromFlp] {
  6299. if (safe != nullptr && afterOpening && fromFlp)
  6300. safe->showImportReport();
  6301. });
  6302. }
  6303. juce::PopupMenu MainComponent::makeSwitchAudioClipsMenu (bool selectedOnly)
  6304. {
  6305. // FL's groups where LYNX has a match (Realtime: Resample), LYNX's stretch engine, and its Ableton-style warp modes
  6306. juce::PopupMenu m;
  6307. auto item = [this, &m, selectedOnly] (const char* name, bool keepPitch, StretchMethod method) {
  6308. m.addItem (tr (name), [this, selectedOnly, keepPitch, method, name] { switchAudioClips (selectedOnly, keepPitch, method, tr (name)); });
  6309. };
  6310. m.addSectionHeader (tr ("Realtime"));
  6311. item (TR_NOOP ("Resample"), false, StretchMethod::general);
  6312. m.addSectionHeader (tr ("Stretch engine"));
  6313. item (TR_NOOP ("General"), true, StretchMethod::general);
  6314. item (TR_NOOP ("Drums / transients"), true, StretchMethod::transients);
  6315. item (TR_NOOP ("Vocal / mono"), true, StretchMethod::mono);
  6316. m.addSectionHeader (tr ("Warp (Ableton-style)"));
  6317. item (TR_NOOP ("Beats"), true, StretchMethod::beats);
  6318. item (TR_NOOP ("Tones"), true, StretchMethod::tones);
  6319. item (TR_NOOP ("Texture"), true, StretchMethod::texture);
  6320. item (TR_NOOP ("Complex"), true, StretchMethod::complex);
  6321. return m;
  6322. }
  6323. void MainComponent::switchAudioClips (bool selectedOnly, bool keepPitch, StretchMethod method, const juce::String& modeName)
  6324. {
  6325. // FL's FUN_01213a20 (REA round 181b): the error when there is none, else a question, then the change (undoable)
  6326. std::vector<int> channels;
  6327. if (selectedOnly)
  6328. channels = engine.getSelectedChannels();
  6329. else
  6330. for (int i = 0; i < (int) engine.getSong().channels.size(); ++i)
  6331. channels.push_back (i);
  6332. if (audioClipsAmong (engine.getSong(), channels) == 0)
  6333. {
  6334. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  6335. selectedOnly ? tr ("No audio clip channels were selected.") : tr ("No audio clip channels were found."));
  6336. return;
  6337. }
  6338. const auto text = selectedOnly ? tr ("Selected audio clip channels will be set to {0} mode. Some channels may need manual time adjustment.", { modeName })
  6339. : tr ("All audio clip channels will be set to {0} mode. Some channels may need manual time adjustment.", { modeName });
  6340. auto options = juce::MessageBoxOptions()
  6341. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  6342. .withTitle (tr ("Confirm"))
  6343. .withMessage (text)
  6344. .withButton (tr ("OK"))
  6345. .withButton (tr ("Cancel"));
  6346. juce::AlertWindow::showAsync (options, [this, channels, keepPitch, method] (int result) {
  6347. if (result == 1)
  6348. engine.editSong ([&channels, keepPitch, method] (Song& s) { setStretchOfAudioClips (s, channels, keepPitch, method); });
  6349. });
  6350. }
  6351. void MainComponent::saveClipboardToBrowser (bool midi)
  6352. {
  6353. // FL's FUN_0124d070 (REA round 181b): the clipboard as "Audio clipboard.wav" / "MIDI clipboard.mid" in the
  6354. // Browser's Clipboard files
  6355. juce::File file;
  6356. if (midi)
  6357. {
  6358. if (const auto smf = midiclipboard::get())
  6359. file = audioclipboard::save ("MIDI clipboard", ".mid", smf->getData(), smf->getSize());
  6360. else
  6361. return;
  6362. }
  6363. else
  6364. {
  6365. const auto data = audioclipboard::wav();
  6366. if (data.empty())
  6367. return;
  6368. file = audioclipboard::save ("Audio clipboard", ".wav", data.data(), data.size());
  6369. }
  6370. if (file == juce::File())
  6371. {
  6372. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  6373. tr ("Unable to create folder: {0}", { audioclipboard::folder().getFullPathName() }));
  6374. return;
  6375. }
  6376. browser.refreshRoots();
  6377. ui::postHint ({ tr ("Saved to Clipboard files: {0}", { file.getFileName() }), {}, false, false }, 5000);
  6378. }
  6379. void MainComponent::confirmPrepareForMidiExport()
  6380. {
  6381. // FL's text, without its "(no undo)": this edit can be undone in LYNX
  6382. auto options = juce::MessageBoxOptions()
  6383. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  6384. .withTitle (tr ("Confirm"))
  6385. .withMessage (tr ("All of the channels are about to be turned into MIDI Out channels in order to allow output to a MIDI file."))
  6386. .withButton (tr ("OK"))
  6387. .withButton (tr ("Cancel"));
  6388. juce::AlertWindow::showAsync (options, [this] (int result) {
  6389. if (result == 1)
  6390. engine.editSongStructural ([] (Song& s) { prepareForMidiExport (s); });
  6391. });
  6392. }
  6393. void MainComponent::changeDeclickOfSelectedClips (int mode)
  6394. {
  6395. const auto selected = engine.getSelectedChannels();
  6396. if (audioClipsAmong (engine.getSong(), selected) == 0)
  6397. {
  6398. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("No selection"), tr ("There are no audio clip channels selected."));
  6399. return;
  6400. }
  6401. auto options = juce::MessageBoxOptions()
  6402. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  6403. .withTitle (tr ("Change declicking mode?"))
  6404. .withMessage (tr ("Change the declicking mode of all selected audio clip channels?"))
  6405. .withButton (tr ("OK"))
  6406. .withButton (tr ("Cancel"));
  6407. juce::AlertWindow::showAsync (options, [this, selected, mode] (int result) {
  6408. if (result == 1)
  6409. engine.editSong ([&selected, mode] (Song& s) { setDeclickOfAudioClips (s, selected, mode); });
  6410. });
  6411. }
  6412. void MainComponent::switchSmartDisableForAll()
  6413. {
  6414. // FL's Tools › Macros › "Switch smart disable for all plugins" (FLEngine FUN_0124d430, REA round 139): every
  6415. // effect slot of every insert is set to smart disable
  6416. engine.editSong ([] (Song& s) {
  6417. for (auto& track : s.mixer)
  6418. for (auto& slot : track.effects)
  6419. slot.smartDisable = true;
  6420. });
  6421. }
  6422. void MainComponent::exportAudio (int format)
  6423. {
  6424. showExportDialog (engine, currentFile.getParentDirectory(), projectName, format);
  6425. }
  6426. void MainComponent::exportForOtherApps()
  6427. {
  6428. engine.capturePluginStates();
  6429. showOtherAppsExportDialog (engine,
  6430. currentFile != juce::File() ? currentFile.getParentDirectory()
  6431. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  6432. projectStem (projectName));
  6433. }
  6434. void MainComponent::importMidiFile()
  6435. {
  6436. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  6437. fileChooser = lynx::ui::makeFileChooser (tr ("Import MIDI file"), folder, "*.mid;*.midi");
  6438. juce::Component::SafePointer<MainComponent> safe (this);
  6439. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe] (const juce::FileChooser& fc) {
  6440. const auto file = fc.getResult();
  6441. if (safe == nullptr || file == juce::File())
  6442. return;
  6443. juce::String error;
  6444. const auto midi = MidiFileIo::parseFile (file, error);
  6445. if (! midi)
  6446. {
  6447. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  6448. return;
  6449. }
  6450. static MidiFileIo::ImportOptions remembered; // FL keeps the window's choices
  6451. showMidiImportDialog (file.getFileName(), *midi, remembered, false, [safe, file] (const MidiFileIo::ImportOptions& o) {
  6452. remembered = o;
  6453. if (safe != nullptr)
  6454. safe->importMidiFile (file, o);
  6455. });
  6456. });
  6457. }
  6458. void MainComponent::importMidiFile (const juce::File& file, const MidiFileIo::ImportOptions& o)
  6459. {
  6460. juce::String error;
  6461. if (o.newProject)
  6462. {
  6463. confirmDiscard ([this, file, o] {
  6464. Song song;
  6465. juce::String err;
  6466. if (! MidiFileIo::importInto (song, file, o, err))
  6467. {
  6468. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), err);
  6469. return;
  6470. }
  6471. engine.stop();
  6472. engine.rewind();
  6473. engine.setSong (std::move (song));
  6474. currentFile = juce::File();
  6475. projectName = file.getFileNameWithoutExtension();
  6476. importedSuffix = " " + tr ("(imported from MIDI)");
  6477. updateTitle();
  6478. });
  6479. return;
  6480. }
  6481. auto song = engine.getSong();
  6482. if (! MidiFileIo::importInto (song, file, o, error))
  6483. {
  6484. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  6485. return;
  6486. }
  6487. engine.editSong ([&song] (Song& s) { s = std::move (song); });
  6488. showPanel (Panel::channelRack);
  6489. }
  6490. void MainComponent::exportMidiFile()
  6491. {
  6492. // FL's File › Export › "MIDI file...": the arrangement's notes (or the current pattern's) as a Standard MIDI File
  6493. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  6494. const auto name = projectName.isNotEmpty() ? projectName : juce::String ("LYNX SHARE");
  6495. fileChooser = lynx::ui::makeFileChooser (tr ("Export MIDI file"), folder.getChildFile (name + ".mid"), "*.mid");
  6496. juce::Component::SafePointer<MainComponent> safe (this);
  6497. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  6498. [safe] (const juce::FileChooser& fc) {
  6499. auto file = fc.getResult();
  6500. if (safe == nullptr || file == juce::File())
  6501. return;
  6502. if (! file.hasFileExtension (".mid;.midi"))
  6503. file = file.withFileExtension (".mid");
  6504. juce::String error;
  6505. if (! MidiFileIo::saveSong (safe->engine.getSong(), file, error))
  6506. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not export"), error);
  6507. else
  6508. file.revealToUser();
  6509. });
  6510. }
  6511. void MainComponent::save (bool askForFile, std::function<void()> afterSaved)
  6512. {
  6513. auto write = [this, afterSaved] (const juce::File& file) {
  6514. juce::String error;
  6515. engine.capturePluginStates(); // plugin state lives in the plugins; copy it before saving
  6516. keepOverwrittenCopy (file); // the version this save replaces goes to the backup folder (like FL)
  6517. if (ProjectFile::save (engine.getSong(), file, error))
  6518. {
  6519. engine.markSaved();
  6520. rememberRecent (file);
  6521. currentFile = file;
  6522. projectName = file.getFileNameWithoutExtension();
  6523. importedSuffix = {};
  6524. updateTitle();
  6525. if (afterSaved)
  6526. afterSaved();
  6527. }
  6528. else
  6529. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  6530. };
  6531. // a project opened from the backup folder is saved somewhere else (old backups there are deleted)
  6532. if (! askForFile && currentFile != juce::File() && ! currentFile.isAChildOf (autosaveFolder()))
  6533. {
  6534. write (ProjectFile::withProjectExtension (currentFile));
  6535. return;
  6536. }
  6537. const auto startFolder = currentFile.isAChildOf (autosaveFolder()) ? juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
  6538. : currentFile.getParentDirectory();
  6539. fileChooser = lynx::ui::makeFileChooser (tr ("Save project"), startFolder, juce::String ("*") + ProjectFile::extension);
  6540. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  6541. [this, write] (const juce::FileChooser& chooser) {
  6542. const auto chosen = chooser.getResult();
  6543. if (chosen == juce::File())
  6544. return;
  6545. const auto file = ProjectFile::withProjectExtension (chosen);
  6546. // the dialog's overwrite warning was about the name typed, without the extension
  6547. if (file != chosen && file != currentFile && file.existsAsFile())
  6548. {
  6549. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  6550. tr ("{0} already exists. Choose another name or folder.", { file.getFullPathName() }));
  6551. return;
  6552. }
  6553. if (! file.isAChildOf (autosaveFolder()))
  6554. {
  6555. write (file);
  6556. return;
  6557. }
  6558. // FL warns the same way: the backup folder is cleaned up as new backups arrive
  6559. auto* w = new juce::AlertWindow (tr ("Save in the backup folder?"),
  6560. tr ("This folder keeps LYNX SHARE's automatic backups and old ones are deleted as new "
  6561. "ones arrive, so a project saved here can be lost. If you opened a backup, save it "
  6562. "somewhere else."),
  6563. juce::MessageBoxIconType::WarningIcon);
  6564. w->addButton (tr ("Save anyway"), 1);
  6565. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6566. w->enterModalState (true, juce::ModalCallbackFunction::create ([write, file] (int r) {
  6567. if (r == 1)
  6568. write (file);
  6569. }),
  6570. true);
  6571. });
  6572. }
  6573. void MainComponent::placeHintBar (juce::Rectangle<int> row)
  6574. {
  6575. // the read-out takes the right part of the hint row once something was tweaked (2/5 of it, 170..280 px), and
  6576. // only when the hint keeps at least 220 px
  6577. const auto readoutWidth = juce::jlimit (170, 280, row.getWidth() * 2 / 5);
  6578. if (tweakReadout.hasContent() && row.getWidth() - readoutWidth - 6 >= 220)
  6579. {
  6580. tweakReadout.setBounds (row.removeFromRight (readoutWidth));
  6581. tweakReadout.setVisible (true);
  6582. row.removeFromRight (6);
  6583. }
  6584. else
  6585. {
  6586. tweakReadout.setVisible (false);
  6587. tweakReadout.setBounds ({});
  6588. }
  6589. hintBar.setVisible (true);
  6590. hintBar.setBounds (row);
  6591. }
  6592. // Settings › General › "Show a control's value next to the mouse..." (round 177d, pain point 10; off by default = FL,
  6593. // whose value shows in the hint bar only): the value the hint bar shows for the control under the mouse, in the
  6594. // drag read-out's pill just above the cursor. A drag shows its own read-out, so nothing here while one runs.
  6595. void MainComponent::updateHoverValue (juce::Component* hovered, const ui::Hint& hint, bool live)
  6596. {
  6597. if (live)
  6598. {
  6599. hoverTipShown = false; // (the drag's read-out owns the pill now)
  6600. return;
  6601. }
  6602. const auto at = juce::Desktop::getInstance().getMainMouseSource().getScreenPosition().roundToInt();
  6603. const auto show = hovered != nullptr && hint.value.isNotEmpty() && ! juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  6604. && (hovered->getTopLevelComponent() == getTopLevelComponent()
  6605. || (bool) hovered->getTopLevelComponent()->getProperties().getWithDefault ("lynxNativeChild", false));
  6606. if (! show)
  6607. {
  6608. if (hoverTipShown)
  6609. ui::hideValueTip();
  6610. hoverTipShown = false;
  6611. return;
  6612. }
  6613. if (hoverTipShown && hint.value == hoverTipText && at == hoverTipAt)
  6614. return;
  6615. hoverTipShown = true;
  6616. hoverTipText = hint.value;
  6617. hoverTipAt = at;
  6618. ui::showValueTip (*hovered, juce::Rectangle<int> (1, 18).withCentre (hovered->getLocalPoint (nullptr, at)), hint.value);
  6619. }
  6620. void MainComponent::refreshTweakReadout()
  6621. {
  6622. const auto had = tweakReadout.hasContent();
  6623. if (const auto t = engine.getLastTweaked (0))
  6624. tweakReadout.setContent (describeAutomationTarget (engine, *t), describeTargetValue (engine, *t));
  6625. else
  6626. tweakReadout.setContent ({}, {});
  6627. if (had != tweakReadout.hasContent())
  6628. resized(); // the read-out appears (or goes, with its target)
  6629. }
  6630. juce::PopupMenu MainComponent::makeLastTweakedMenu (int which)
  6631. {
  6632. juce::PopupMenu menu;
  6633. const auto target = engine.getLastTweaked (which);
  6634. if (! target)
  6635. {
  6636. menu.addItem (tr ("No parameter"), false, false, [] {});
  6637. return menu;
  6638. }
  6639. // as FL: the parameter's name, then the items of its own menu (events, automation clip, remote control, value)
  6640. const auto valueNow = describeTargetValue (engine, *target); // (round 162d: with its value, as the read-out shows it)
  6641. ui::addItemHeader (menu, tr ("Parameter"), describeAutomationTarget (engine, *target) + (valueNow.isNotEmpty() ? ": " + valueNow : juce::String()),
  6642. juce::Colours::transparentBlack);
  6643. const auto& song = engine.getSong();
  6644. int clip = -1;
  6645. for (int a = 0; a < (int) song.automations.size(); ++a)
  6646. if (song.automations[(std::size_t) a].target == *target)
  6647. clip = a;
  6648. juce::ignoreUnused (clip);
  6649. addAutomationItem (menu, engine, *target, true);
  6650. menu.addSectionHeader (tr ("Value"));
  6651. const auto value = engine.currentTargetValue (*target);
  6652. menu.addItem (tr ("Copy value"), value >= 0.0f, false, [value] { lastTweakedClipboard() = value; });
  6653. menu.addItem (tr ("Paste value"), lastTweakedClipboard() >= 0.0f, false, [this, t = *target] { setTweakedValue (t, lastTweakedClipboard()); });
  6654. menu.addItem (tr ("Type in value..."), value >= 0.0f, false, [this, t = *target, value] {
  6655. auto spec = ui::percentSpec (describeAutomationTarget (engine, t), value);
  6656. ui::typeValue (*this, spec, value, [this, t] (double v) { setTweakedValue (t, (float) v); });
  6657. });
  6658. return menu;
  6659. }
  6660. float& MainComponent::lastTweakedClipboard()
  6661. {
  6662. static float copied = -1.0f;
  6663. return copied;
  6664. }
  6665. void MainComponent::setTweakedValue (const AutomationTarget& target, float value)
  6666. {
  6667. value = juce::jlimit (0.0f, 1.0f, value);
  6668. auto plugin = false;
  6669. engine.editSong ([&] (Song& s) {
  6670. if (target.kind == AutomationTargetKind::tempo)
  6671. clipops::followTempo (s, tempoFromValue (value)); // (issue #87: audio clips follow)
  6672. else
  6673. plugin = ! s.setTargetValue (target, value);
  6674. });
  6675. if (plugin)
  6676. {
  6677. if (target.kind == AutomationTargetKind::channelParam)
  6678. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (target.index).get()))
  6679. p->setParameterFromUi (target.param, value);
  6680. if (target.kind == AutomationTargetKind::effectParam)
  6681. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (target.index, target.slot).get()))
  6682. p->setParameterFromUi (target.param, value);
  6683. }
  6684. engine.noteTweaked (target);
  6685. }
  6686. juce::StringArray MainComponent::getMenuBarNames()
  6687. {
  6688. // FL's menu bar order (REA round 139): FILE EDIT ADD PATTERNS VIEW OPTIONS TOOLS HELP
  6689. return { tr ("File"), tr ("Edit"), tr ("Add"), tr ("Patterns"), tr ("View"), tr ("Options"), tr ("Tools"), tr ("Help") };
  6690. }
  6691. juce::PopupMenu MainComponent::getMenuForIndex (int barIndex, const juce::String&)
  6692. {
  6693. juce::PopupMenu menu;
  6694. // the bar's position → the menu built below (0 File, 1 Edit, 2 View, 3 Patterns, 4 Options, 5 Help, 10 Add, 11 Tools)
  6695. static constexpr int menus[] = { 0, 1, 10, 3, 2, 4, 11, 5 };
  6696. const auto index = juce::isPositiveAndBelow (barIndex, (int) std::size (menus)) ? menus[barIndex] : 5;
  6697. if (index == 10)
  6698. {
  6699. // FL's ADD menu: a channel (LYNX's instruments and the installed plugins), a pattern, the plugin tools
  6700. menu.addSectionHeader (tr ("Channel"));
  6701. rack.addInstrumentItems (menu, -1);
  6702. menu.addSectionHeader (tr ("Other"));
  6703. // FL's "Automation for last tweaked parameter" (Add_AutoLastMenu → FUN_01231100, REA round 143)
  6704. const auto last = engine.getLastTweaked (0);
  6705. menu.addItem ((last ? tr ("Automation for last tweaked parameter ({0})", { describeAutomationTarget (engine, *last) })
  6706. : tr ("Automation for last tweaked parameter"))
  6707. + shortcutText ("automation.lastTweaked"),
  6708. last.has_value(), false, [this] { runAction ("automation.lastTweaked"); });
  6709. menu.addItem (tr ("Pattern"), [this] { newPatternButton.onClick(); });
  6710. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  6711. return menu;
  6712. }
  6713. if (index == 11)
  6714. {
  6715. // FL's TOOLS menu, with the tools LYNX has (REA round 139)
  6716. menu.addItem (tr ("Browser find") + shortcutText ("browser.search"), [this] {
  6717. showPanel (Panel::browser);
  6718. browser.focusSearch();
  6719. });
  6720. menu.addItem (tr ("One-click audio recording: arm the selected insert..."), [this] { armSelectedInsertForAudio(); });
  6721. // FL's Tools menu has these two here; they work on the selected channel's Piano Roll (round 181b)
  6722. menu.addItem (tr ("Riff machine..."), [this] {
  6723. openPianoRoll();
  6724. pianoRoll.runAction ("pianoRoll.riffMachine");
  6725. });
  6726. menu.addItem (tr ("Chord progression tool..."), [this] {
  6727. openPianoRoll();
  6728. pianoRoll.runAction ("pianoRoll.chordProgression");
  6729. });
  6730. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  6731. menu.addItem (tr ("Modulators..."), [this] { openModulators (engine); }); // round 177b: LYNX's own (FL has none)
  6732. // FL's Clipboard and Score logger sections, in FL's place (round 181b)
  6733. menu.addSectionHeader (tr ("Clipboard"));
  6734. menu.addItem (tr ("Save audio clipboard to browser"), audioclipboard::hasAudio(), false, [this] { saveClipboardToBrowser (false); });
  6735. menu.addItem (tr ("Save MIDI clipboard to browser"), midiclipboard::hasMidi(), false, [this] { saveClipboardToBrowser (true); });
  6736. {
  6737. // FL's score logger (REA round 165f): the notes played lately, recording or not, into the current pattern
  6738. menu.addSectionHeader (tr ("Score logger"));
  6739. juce::PopupMenu dumpMenu;
  6740. for (const auto minutes : { 2, 5, 10, 20, 30 })
  6741. dumpMenu.addItem (tr ("Last {0} minutes", { juce::String (minutes) }), [this, minutes] { dumpScoreLog (minutes); });
  6742. menu.addSubMenu (tr ("Dump score log to selected pattern"), dumpMenu);
  6743. menu.addItem (tr ("Clear log"), ! engine.scoreLogEmpty(), false, [this] {
  6744. auto options = juce::MessageBoxOptions()
  6745. .withIconType (juce::MessageBoxIconType::WarningIcon)
  6746. .withTitle (tr ("Score logger"))
  6747. .withMessage (tr ("This will clear all logged notes!"))
  6748. .withButton (tr ("Clear log"))
  6749. .withButton (tr ("Cancel"));
  6750. juce::AlertWindow::showAsync (options, [this] (int result) {
  6751. if (result == 1)
  6752. engine.clearScoreLog();
  6753. });
  6754. });
  6755. }
  6756. addAudioLoggerMenu (menu); // FL's Tools menu has it just above "Last tweaked parameters"
  6757. // FL's "Last tweaked parameters" section (LastTweaked1Menu / LastTweaked2Menu → FUN_0123d1d0, REA round 143):
  6758. // the parameter's own menu for the last two moved controls
  6759. menu.addSectionHeader (tr ("Last tweaked parameters"));
  6760. menu.addSubMenu (tr ("Last tweaked"), makeLastTweakedMenu (0), engine.getLastTweaked (0).has_value());
  6761. menu.addSubMenu (tr ("Next to last tweaked"), makeLastTweakedMenu (1), engine.getLastTweaked (1).has_value());
  6762. menu.addSectionHeader (tr ("Macros"));
  6763. menu.addItem (tr ("Stop sound") + shortcutText ("tools.stopSound"), [this] { engine.stopSound(); });
  6764. // FL's next item, MacroCancelRecordingAction (round 187a; REA 169k §2.3): greyed while not recording
  6765. menu.addItem (tr ("Cancel recording"), engine.isRecording(), false, [this] { engine.cancelRecording(); });
  6766. menu.addSeparator();
  6767. // FL's Macros order (round 181b; [DFM] mainmenu, round 168f)
  6768. menu.addItem (tr ("Prepare for performance mode..."), [this] { prepareForPerformance(); });
  6769. menu.addItem (tr ("Prepare for MIDI export"), [this] { confirmPrepareForMidiExport(); });
  6770. menu.addItem (tr ("Select unused channels"), [this] {
  6771. showPanel (Panel::channelRack);
  6772. rack.selectUnused();
  6773. });
  6774. menu.addItem (tr ("Purge unused audio clips"), [this] { playlist.runAction ("playlist.purgeUnusedAudio"); });
  6775. menu.addItem (tr ("Switch smart disable for all plugins"), [this] { switchSmartDisableForAll(); });
  6776. // FL's two Switch items, with LYNX's own modes inside (user's decision, round 181b)
  6777. menu.addSubMenu (tr ("Switch all audio clip channels to"), makeSwitchAudioClipsMenu (false));
  6778. menu.addSubMenu (tr ("Switch selected audio clip channels to"), makeSwitchAudioClipsMenu (true));
  6779. menu.addItem (tr ("Lock all playlist tracks to content"), [this] { playlist.runAction ("playlist.lockAllToContent"); });
  6780. menu.addItem (tr ("Unlock all playlist tracks from content"), [this] { playlist.runAction ("playlist.unlockAllFromContent"); });
  6781. menu.addItem (tr ("Reset empty playlist tracks"), [this] { playlist.runAction ("playlist.resetEmptyTracks"); });
  6782. // greyed until the project has a file, as in FL 2026 (seen in an unsaved project, round 181b)
  6783. menu.addItem (tr ("Delete unused files and save project"), currentFile != juce::File(), false, [this] { deleteUnusedRecordingsAndSave(); });
  6784. // FL's next item (round 190i, issue #116; FL 2026's Tools menu, shots fl2-01 / fl2-02): every plugin editor
  6785. // docked in the desktop (FL's word: Attached) or in a window of its own
  6786. if (nativechild::dockingEnabled())
  6787. {
  6788. juce::PopupMenu editors;
  6789. editors.addItem (tr ("Attached"), [this] { PluginWindows::setAllDetached (engine, false); });
  6790. editors.addItem (tr ("Detached"), [this] { PluginWindows::setAllDetached (engine, true); });
  6791. menu.addSubMenu (tr ("Switch all plugin editors to"), editors);
  6792. }
  6793. {
  6794. juce::PopupMenu declick;
  6795. int mode = 0;
  6796. for (const auto* name : { TR_NOOP ("Out only (no bleeding)"), TR_NOOP ("Transient (no bleeding)"), TR_NOOP ("Transient (bleeding)"),
  6797. TR_NOOP ("Generic (bleeding)"), TR_NOOP ("Smooth (bleeding)"), TR_NOOP ("Crossfade (bleeding)") })
  6798. {
  6799. declick.addItem (tr (name), [this, mode] { changeDeclickOfSelectedClips (mode); });
  6800. ++mode;
  6801. }
  6802. menu.addSubMenu (tr ("Change declicking for selected channels to"), declick);
  6803. }
  6804. menu.addItem (tr ("Collect project samples into a folder..."), [this] { collectSamples(); });
  6805. return menu;
  6806. }
  6807. if (index == 0)
  6808. {
  6809. // FL names the default template in the item ("New (Basic with limiter)", REA_rodada186a); LYNX's own default: "New"
  6810. const auto startTemplate = defaultTemplate();
  6811. menu.addItem ((startTemplate.isLynxDefault() ? tr ("New") : tr ("New") + " (" + templateChoiceName (startTemplate) + ")") + shortcutText ("file.new"),
  6812. [this] { newProject(); });
  6813. menu.addItem (tr ("New project..."), [this] { newProject (true); });
  6814. // FL's File › New from template (REA_rodada186a): the templates, the user's after LYNX's own, then "Change default
  6815. // template..." (FL's last item; it opens Settings › General where the default is chosen)
  6816. juce::PopupMenu templates;
  6817. bool userSection = false;
  6818. for (const auto& choice : availableTemplates())
  6819. {
  6820. if (choice.isLynxDefault())
  6821. continue;
  6822. if (choice.kind == TemplateChoice::Kind::user && ! userSection)
  6823. {
  6824. templates.addSeparator();
  6825. userSection = true;
  6826. }
  6827. templates.addItem (templateChoiceName (choice), [this, choice] {
  6828. confirmDiscard ([this, choice] {
  6829. auto song = makeFromTemplate (choice);
  6830. if (! song)
  6831. {
  6832. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("New from template"),
  6833. tr ("{0} could not be opened.", { templateChoiceName (choice) }));
  6834. return;
  6835. }
  6836. startNewProject (std::move (*song), {});
  6837. });
  6838. });
  6839. }
  6840. templates.addSeparator();
  6841. templates.addItem (tr ("Change default template..."), [this] { openSettings (3); });
  6842. menu.addSubMenu (tr ("New from template"), templates);
  6843. menu.addItem (tr ("Open...") + shortcutText ("file.open"), [this] { chooseFileToOpen(); });
  6844. // round 190ap: a project that will not open, or crashes while it loads: its plugins stay off until switched on
  6845. menu.addItem (tr ("Open without third-party plugins..."), [this] { chooseFileToOpenWithoutPlugins(); });
  6846. if (engine.pluginsOff())
  6847. menu.addItem (tr ("Switch plugins back on..."), [this] { showPluginsOff(); });
  6848. menu.addSeparator();
  6849. // FL's order (REA round 139): saving, then Export, then the recent projects listed in the menu itself
  6850. menu.addItem (tr ("Save") + shortcutText ("file.save"), [this] { save (false); });
  6851. menu.addItem (tr ("Save as...") + shortcutText ("file.saveAs"), [this] { save (true); });
  6852. menu.addItem (tr ("Save new version") + shortcutText ("file.saveNewVersion"), [this] { saveNewVersion(); });
  6853. menu.addItem (tr ("Save to new project folder..."), [this] { saveToNewProjectFolder(); });
  6854. menu.addItem (tr ("Save as template..."), [this] { saveAsTemplate(); });
  6855. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  6856. menu.addSeparator();
  6857. {
  6858. // FL's File › Import (ImportMenu › ImportMIDIMenu → FileImportMIDIFileAction, REA round 143)
  6859. juce::PopupMenu imports;
  6860. imports.addItem (tr ("MIDI file..."), [this] { importMidiFile(); });
  6861. imports.addItem (tr ("Video file..."), [this] { videotracks::chooseAndImport (engine, this); }); // round 174d
  6862. menu.addSubMenu (tr ("Import"), imports);
  6863. }
  6864. {
  6865. // FL's File › Export (REA round 139): one entry per format, then the formats of the last export
  6866. juce::PopupMenu exports;
  6867. exports.addItem (tr ("Wave file..."), [this] { exportAudio (0); });
  6868. exports.addItem (tr ("MP3 file...") + shortcutText ("file.exportMp3"), [this] { exportAudio (1); });
  6869. exports.addItem (tr ("OGG file..."), [this] { exportAudio (2); });
  6870. exports.addItem (tr ("FLAC file..."), [this] { exportAudio (3); });
  6871. exports.addItem (tr ("MIDI file...") + shortcutText ("file.exportMidi"), [this] { exportMidiFile(); });
  6872. exports.addItem (tr ("Last exported format(s)...") + shortcutText ("file.export"), [this] { exportAudio(); });
  6873. exports.addSeparator();
  6874. // FL's FileExportMasterAction ("Render the project to a file and master it"; FL Cloud there, on the computer here)
  6875. exports.addItem (tr ("Master...") + shortcutText ("file.exportMaster"), [this] { showMasterDialog (engine, currentFile.getParentDirectory(), projectName); });
  6876. exports.addSeparator();
  6877. // FL's ExportAllPLTracksMenu / ExportAllPLTrackGroupsMenu (FileExportPLTracks… / FileExportPLGroups…, REA round 168e)
  6878. exports.addSubMenu (tr ("All playlist tracks"), playlistTrackExportMenu (false));
  6879. exports.addSubMenu (tr ("All playlist track groups"), playlistTrackExportMenu (true));
  6880. exports.addSeparator();
  6881. exports.addItem (tr ("Project with samples (.zip)..."), [this] { exportPackage(); });
  6882. // Export to FL Studio (round 171e, idea by Tookolld): a .flp or FL's zipped loop package
  6883. exports.addItem (tr ("FL Studio project..."), [this] {
  6884. engine.capturePluginStates();
  6885. showFlStudioExportDialog (engine,
  6886. currentFile != juce::File() ? currentFile.getParentDirectory()
  6887. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  6888. projectStem (projectName));
  6889. });
  6890. // Export to Live 12 / Live 11 (round 175a, N2): "<name> Project/<name>.als" with the samples alongside
  6891. exports.addItem (tr ("Ableton Live set (.als)..."), [this] {
  6892. showAlsExportDialog (engine,
  6893. currentFile != juce::File() ? currentFile.getParentDirectory()
  6894. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  6895. projectStem (projectName));
  6896. });
  6897. // Export for other apps (round 184a, S9): stems, MIDI, a Live set, an FL Studio project, the mixdown and a README
  6898. exports.addItem (tr ("For other apps..."), [this] { exportForOtherApps(); });
  6899. // FL's "Project bones..." (FileExportProjectBonesAction; REA round 168e)
  6900. exports.addItem (tr ("Project bones..."), [this] { exportProjectBones (engine, currentFile.getParentDirectory(), projectName); });
  6901. exports.addItem (tr ("Project data files (collect the samples into a folder)..."), [this] { collectSamples(); });
  6902. menu.addSubMenu (tr ("Export"), exports);
  6903. }
  6904. {
  6905. // Online Sessions, phase 1 (docs/design/ONLINE_SESSIONS.md, round 168a): a project goes to a friend as a
  6906. // .lynxpack, his part comes back the same way
  6907. const auto guestCopy = engine.getSong().session.isGuestCopy();
  6908. juce::PopupMenu online;
  6909. online.addItem (tr ("Send project..."), ! guestCopy, false, [this] { sessionui::sendProject (sessionContext()); });
  6910. online.addItem (tr ("Send my part back..."), guestCopy, false, [this] { sessionui::sendPartBack (sessionContext()); });
  6911. online.addItem (tr ("Merge a part..."), ! guestCopy, false, [this] { sessionui::mergePart (sessionContext()); });
  6912. online.addSeparator();
  6913. liveui::addMenuItems (online, liveContext());
  6914. menu.addSubMenu (tr ("Online session"), online);
  6915. }
  6916. menu.addSectionHeader (tr ("Recent projects"));
  6917. const auto shown = juce::jmin (recent.getNumFiles(), 10);
  6918. for (int i = 0; i < shown; ++i)
  6919. {
  6920. const auto file = recent.getFile (i);
  6921. juce::PopupMenu::Item item (file.getFileName());
  6922. item.shortcutKeyDescription = file.getParentDirectory().getFileName(); // its folder on the right
  6923. item.setEnabled (file.existsAsFile()).setAction ([this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  6924. menu.addItem (std::move (item));
  6925. }
  6926. if (recent.getNumFiles() > shown)
  6927. {
  6928. juce::PopupMenu more;
  6929. for (int i = shown; i < recent.getNumFiles(); ++i)
  6930. {
  6931. const auto file = recent.getFile (i);
  6932. more.addItem (file.getFileName() + " (" + file.getParentDirectory().getFullPathName() + ")", file.existsAsFile(),
  6933. false, [this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  6934. }
  6935. menu.addSubMenu (tr ("More recent projects"), more);
  6936. }
  6937. if (recent.getNumFiles() == 0)
  6938. menu.addItem (tr ("(none)"), false, false, [] {});
  6939. menu.addSeparator();
  6940. menu.addItem (tr ("Versions..."), [this] { showVersions(); }); // round 190ap: the saved versions and the backups in one list
  6941. menu.addItem (tr ("Revert to last backup..."), [this] { revertToLastBackup(); });
  6942. menu.addItem (tr ("Open autosave folder"), [] {
  6943. autosaveFolder().createDirectory();
  6944. autosaveFolder().startAsProcess();
  6945. });
  6946. menu.addSeparator();
  6947. menu.addItem (tr ("Exit"), [] { juce::JUCEApplication::getInstance()->systemRequestedQuit(); });
  6948. }
  6949. else if (index == 1)
  6950. {
  6951. // FL's Edit menu: "Undo backwards" (Ctrl+Alt+Z) above "Undo" (Ctrl+Z: undo, or redo after an undo)
  6952. // ("Alternate undo mode" swaps the two shortcuts, as FL's menu does: round 190b)
  6953. const auto backwardsId = alternateUndo ? "edit.undo" : "edit.undoBackwards";
  6954. const auto toggleId = alternateUndo ? "edit.undoBackwards" : "edit.undo";
  6955. menu.addItem (tr ("Undo backwards") + shortcutText (backwardsId), engine.canUndo(), false, [this] { undoRedo (false); });
  6956. menu.addItem ((engine.canRedo() ? tr ("Undo (redo)") : tr ("Undo")) + shortcutText (toggleId), engine.canUndo() || engine.canRedo(), false,
  6957. [this] { runUndoStep (undokeys::toggle (engine.canUndo(), engine.canRedo())); });
  6958. menu.addItem (tr ("Redo") + shortcutText ("edit.redo"), engine.canRedo(), false, [this] { undoRedo (true); });
  6959. menu.addItem (tr ("Undo history...") + shortcutText ("edit.history"), [this] { showHistory(); });
  6960. menu.addItem (tr ("Audio editor..."), [this] { openAudioEditor (engine); });
  6961. menu.addSeparator();
  6962. menu.addItem (tr ("Plugin picker") + shortcutText ("view.pluginPicker"), [this] { togglePluginPicker(); });
  6963. menu.addItem (tr ("Quick-add palette...") + shortcutText ("panel.quickAdd"), [this] { showQuickAdd(); });
  6964. menu.addItem (tr ("Search the Browser") + shortcutText ("browser.search"), [this] {
  6965. showPanel (Panel::browser);
  6966. browser.focusSearch();
  6967. });
  6968. }
  6969. else if (index == 2)
  6970. {
  6971. for (auto panel : panelOrder)
  6972. menu.addItem (panelName (panel) + shortcutText (panelAction (panel)), true, workspace.isPanelVisible (panel), [this, panel] { togglePanel (panel); });
  6973. menu.addSeparator();
  6974. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  6975. workspace.toggleMaximised (Panel::playlist);
  6976. refreshPanelButtons();
  6977. });
  6978. {
  6979. juce::PopupMenu detach;
  6980. for (auto panel : panelOrder)
  6981. detach.addItem (panelName (panel), true, workspace.isDetached (panel), [this, panel] {
  6982. workspace.setDetached (panel, ! workspace.isDetached (panel));
  6983. refreshPanelButtons();
  6984. });
  6985. menu.addSubMenu (tr ("Detached panels (own window)"), detach);
  6986. }
  6987. menu.addSeparator();
  6988. menu.addItem (tr ("Reset layout"), [this] {
  6989. workspace.resetLayout();
  6990. refreshPanelButtons();
  6991. });
  6992. menu.addItem (tr ("Save layout as..."), [this] { saveLayoutAs(); });
  6993. menu.addSubMenu (tr ("Load layout"), layoutsMenu());
  6994. addLayoutStyleItems (menu);
  6995. menu.addItem (tr ("Bring back off-screen panels"), [this] { workspace.bringBackOffscreen(); });
  6996. menu.addItem (tr ("Close all windows (plugins, channel settings, tools)") + shortcutText ("view.closeWindows"), [this] { runAction ("view.closeWindows"); });
  6997. menu.addItem (tr ("Close all plugin windows") + shortcutText ("view.closePluginWindows"), [this] { runAction ("view.closePluginWindows"); });
  6998. menu.addItem (tr ("Close all windows except the focused one") + shortcutText ("view.closeUnfocusedWindows"), [this] { runAction ("view.closeUnfocusedWindows"); });
  6999. menu.addItem (tr ("Align all channel editors") + shortcutText ("view.alignChannelEditors"), [this] { runAction ("view.alignChannelEditors"); });
  7000. menu.addSeparator();
  7001. menu.addItem (tr ("Plugin database (in the Browser)") + shortcutText ("view.pluginDatabase"), [this] { runAction ("view.pluginDatabase"); });
  7002. menu.addItem (tr ("Audio editor") + shortcutText ("view.audioEditor"), [this] { openAudioEditorForSelection(); });
  7003. menu.addItem (tr ("Tempo tapper") + shortcutText ("view.tempoTapper"), [this] { openTempoTapper (engine); });
  7004. menu.addItem (tr ("Sample browser (separate window)") + shortcutText ("view.sampleBrowser"), true, findToolWindow ("sampleBrowser") != nullptr,
  7005. [this] { toggleSampleBrowser(); });
  7006. menu.addSeparator();
  7007. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  7008. menu.addItem (tr ("Touch keyboard") + shortcutText ("view.touchKeyboard"), true, isTouchKeyboardOpen(), [this] { toggleTouchKeyboard (engine); });
  7009. {
  7010. // FL's View › Background (audit round 165z-a): the workspace image and colour of Options › Theme
  7011. juce::PopupMenu background;
  7012. background.addItem (tr ("Set image wallpaper..."), [] { themeui::setImageWallpaper(); });
  7013. background.addItem (tr ("Remove image wallpaper"), ! themeui::current().image.empty(), false, [] { themeui::removeImageWallpaper(); });
  7014. background.addItem (tr ("Set background color..."), [this] { openSettings ((int) SettingsPage::theme); });
  7015. menu.addSubMenu (tr ("Background"), background);
  7016. }
  7017. menu.addSeparator();
  7018. // FL's "Auto scrolling" (round 162, issue #9)
  7019. menu.addItem (tr ("Playlist follows the playhead (auto scrolling)") + shortcutText ("playlist.follow"), true,
  7020. EditorGlobals::get().isFollowing (false), [this] { runAction ("playlist.follow"); });
  7021. menu.addItem (tr ("Piano Roll follows the playhead (auto scrolling)") + shortcutText ("pianoRoll.follow"), true,
  7022. EditorGlobals::get().isFollowing (true), [this] { runAction ("pianoRoll.follow"); });
  7023. }
  7024. else if (index == 3)
  7025. {
  7026. menu = makePatternMenu();
  7027. }
  7028. else if (index == 4)
  7029. {
  7030. // the Settings window's pages (Settings › General gathers the app options that were menu items here)
  7031. menu.addItem (tr ("Audio settings..."), [this] { openSettings ((int) SettingsPage::audio); });
  7032. menu.addItem (tr ("MIDI settings...") + shortcutText ("view.midiSettings"), [this] { openSettings ((int) SettingsPage::midi); });
  7033. menu.addItem (tr ("General settings..."), [this] { openSettings ((int) SettingsPage::general); });
  7034. menu.addItem (tr ("Theme (colors, background)..."), [this] { openSettings ((int) SettingsPage::theme); });
  7035. menu.addItem (tr ("File settings (search folders)..."), [this] { openSettings ((int) SettingsPage::files); });
  7036. menu.addItem (tr ("LYNX extras..."), [this] { openSettings ((int) SettingsPage::extras); }); // round 190am
  7037. menu.addItem (tr ("Project settings (tempo, time signature)..."), [this] { openSettings ((int) SettingsPage::project); });
  7038. menu.addItem (tr ("Project info...") + shortcutText ("view.projectInfo"), [this] { openSettings ((int) SettingsPage::info); });
  7039. {
  7040. juce::PopupMenu mixerMenu; // round 163: clean mixer, inserts and Master chain of new projects
  7041. mixeroptions::addItems (mixerMenu, engine, true);
  7042. menu.addSubMenu (tr ("Mixer"), mixerMenu);
  7043. }
  7044. menu.addSeparator();
  7045. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  7046. const auto scanning = engine.getPluginHost().backgroundScan().running;
  7047. menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins ({0})", { platform::pluginFormatNames() }), [this, scanning] {
  7048. if (scanning)
  7049. engine.getPluginHost().cancelBackgroundScan();
  7050. else
  7051. engine.getPluginHost().startBackgroundScan(); // progress in the hint bar; LYNX stays usable
  7052. });
  7053. menu.addItem (tr ("Manage shortcuts..."), [this] { showShortcutManager(); });
  7054. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  7055. menu.addSeparator();
  7056. menu.addItem (tr ("Record input audio"), true, engine.isAudioRecordingArmed(), [this] {
  7057. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  7058. });
  7059. // FL's Options menu, "Switches" section (TFruityLoopsMainForm DFM: KBToMIDIMenu = OptionsTypingKbToPianoAction,
  7060. // "Typing keyboard to piano", Ctrl+T, checkable, right before Metronome; round 168t, issue #34)
  7061. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  7062. menu.addItem (tr ("Metronome") + shortcutText ("transport.metronome"), true, engine.getTransport().metronome.load(), [this] {
  7063. metronomeButton.setToggleState (! metronomeButton.getToggleState(), juce::sendNotification);
  7064. });
  7065. menu.addItem (tr ("Metronome volume ({0})...", { ui::utilityVolumeText (engine.getTransport().metronomeVolume.load()) }),
  7066. [this] { showMetronomeVolume(); });
  7067. {
  7068. // FL's Options › "Auto scrolling" (audit round 165z-a): one switch for every editor's Follow (Playlist,
  7069. // Piano roll, Channel rack, Audio editor); each window's own Follow button still sets just that window
  7070. auto& globals = EditorGlobals::get();
  7071. const auto on = globals.isFollowing (false) && globals.isFollowing (true);
  7072. menu.addItem (tr ("Auto scrolling"), true, on, [on] {
  7073. auto& g = EditorGlobals::get();
  7074. for (auto v : { EditorGlobals::FollowView::playlist, EditorGlobals::FollowView::pianoRoll,
  7075. EditorGlobals::FollowView::channelRack, EditorGlobals::FollowView::audioEditor })
  7076. g.setFollowingView (v, ! on);
  7077. });
  7078. }
  7079. // FL's "Multilink to controllers" (Ctrl+J), the last of FL's Switches (after Auto scrolling and Enable groups;
  7080. // round 177b-4): the controls moved while it is on link, in that order, to the controllers moved next
  7081. menu.addItem (tr ("Multilink to controllers") + shortcutText ("options.multilink"), true, engine.isMultilinkOn(),
  7082. [this] { runAction ("options.multilink"); });
  7083. {
  7084. juce::PopupMenu recording;
  7085. addRecordOptions (recording);
  7086. menu.addSubMenu (tr ("Recording"), recording);
  7087. }
  7088. // LYNX's own ADR (round 174d, issue #83): cues, the record cycle with streamers and beeps, takes, comp, Align
  7089. menu.addItem (tr ("ADR (dialogue replacement)..."), [this] { adrwindow::show (engine); });
  7090. {
  7091. // LYNX's own (REA round 153): everything the Master plays, after the fader, goes to a WAV in the background
  7092. auto& logger = engine.getAudioLogger();
  7093. menu.addItem (tr ("Record the Master to a file"), true, logger.isLogging(), [this] {
  7094. auto& log = engine.getAudioLogger();
  7095. if (log.isLogging())
  7096. {
  7097. const auto file = log.currentFile();
  7098. const auto seconds = log.secondsWritten();
  7099. log.stop();
  7100. ui::postHint ({ tr ("Recording of the Master saved: {0} ({1} s)", { file.getFileName(), juce::String (seconds, 1) }), {}, false, false }, 5000);
  7101. }
  7102. else if (! log.start (AudioLogger::defaultFolder(), engine.getTransport().sampleRate.load()))
  7103. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Record the Master to a file"),
  7104. tr ("Could not create a file in {0}", { AudioLogger::defaultFolder().getFullPathName() }));
  7105. else
  7106. ui::postHint ({ tr ("Recording the Master to {0}", { log.currentFile().getFileName() }), {}, false, false }, 5000);
  7107. });
  7108. menu.addItem (tr ("Show the recordings of the Master"), [] {
  7109. const auto folder = AudioLogger::defaultFolder();
  7110. folder.createDirectory();
  7111. folder.startAsProcess();
  7112. });
  7113. }
  7114. menu.addSubMenu (tr ("Toolbar"), makeToolbarMenu());
  7115. menu.addSeparator();
  7116. menu.addItem (tr ("Setup wizard (language, audio, plugin folders)..."), [this] { showSetupWizard(); });
  7117. }
  7118. else
  7119. {
  7120. menu.addItem (tr ("Shortcuts") + shortcutText ("help.shortcuts"), [this] { showHelp(); });
  7121. menu.addItem (tr ("Missing files..."), [this] { showMissingFiles (false); });
  7122. menu.addItem (tr ("Last project import report"), [this] {
  7123. const auto& r = engine.getImportReport();
  7124. if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.droppedEffects.empty() && r.partialEffects.empty() && r.missingSamples == 0
  7125. && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty() && engine.getPluginsWithoutState().isEmpty()
  7126. && engine.getPluginHost().getLoadFailures().isEmpty())
  7127. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Project import"),
  7128. tr ("Nothing to report (no .flp, .als or .flm project imported in this session, or everything was converted)."));
  7129. else
  7130. showImportReport();
  7131. });
  7132. menu.addItem (tr ("Built-in plugins (online list)..."), [] {
  7133. juce::URL ("https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/PLUGINS.md").launchInDefaultBrowser();
  7134. });
  7135. menu.addItem (tr ("Report a problem..."), [this] { crashreporter::showManualReport (&engine.getDeviceManager()); });
  7136. if (updater::offered()) // (not in the Store build: the Store updates it)
  7137. menu.addItem (tr ("Check for updates..."), [] { updater::checkNow(); });
  7138. menu.addItem (tr ("About LYNX SHARE"), [] {
  7139. auto* window = makeAboutWindow().release();
  7140. window->enterModalState (true, nullptr, true);
  7141. keepAboveMainWindow (*window);
  7142. });
  7143. }
  7144. return menu;
  7145. }
  7146. std::unique_ptr<juce::AlertWindow> MainComponent::makeAboutWindow()
  7147. {
  7148. struct Logo final : juce::Component
  7149. {
  7150. Logo() { setSize (300, 150); }
  7151. void paint (juce::Graphics& g) override
  7152. {
  7153. g.drawImageWithin (logoImage(), 0, 0, getWidth(), getHeight(), juce::RectanglePlacement::centred);
  7154. }
  7155. };
  7156. struct About final : juce::AlertWindow
  7157. {
  7158. About()
  7159. : juce::AlertWindow ("LYNX SHARE " JUCE_APPLICATION_VERSION_STRING,
  7160. tr ("Lightweight C++/JUCE DAW: FL Studio-style patterns and Ableton Live-style clips.\n"
  7161. "Independent implementation: no Image-Line or Ableton code was copied."),
  7162. juce::MessageBoxIconType::NoIcon)
  7163. {
  7164. addCustomComponent (&logo);
  7165. }
  7166. Logo logo;
  7167. };
  7168. auto window = std::make_unique<About>();
  7169. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7170. return std::unique_ptr<juce::AlertWindow> (window.release());
  7171. }
  7172. void MainComponent::showLanguageChoice (const juce::String& id)
  7173. {
  7174. if (id == i18n::saved())
  7175. return;
  7176. i18n::save (id);
  7177. const auto restart = [this] {
  7178. confirmDiscard ([] {
  7179. lynx::platform::relaunchApp(); // through the package in the Store build (platform/Package.h)
  7180. juce::JUCEApplication::quit();
  7181. });
  7182. };
  7183. // the message is shown in the language just chosen
  7184. const auto table = i18n::tableText (id);
  7185. const juce::LocalisedStrings strings (table, false);
  7186. auto say = [&] (const char* text) { return table.isEmpty() ? juce::String::fromUTF8 (text) : strings.translate (juce::String::fromUTF8 (text)); };
  7187. auto* window = new juce::AlertWindow (say (TR_NOOP ("Language")), say (TR_NOOP ("The new language is applied when LYNX SHARE restarts.")),
  7188. juce::MessageBoxIconType::InfoIcon);
  7189. window->addButton (say (TR_NOOP ("Restart now")), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7190. window->addButton (say (TR_NOOP ("Later")), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7191. window->enterModalState (true, juce::ModalCallbackFunction::create ([restart] (int result) {
  7192. if (result == 1)
  7193. restart();
  7194. }),
  7195. true);
  7196. }
  7197. void MainComponent::rememberRecent (const juce::File& file)
  7198. {
  7199. recent.addFile (file);
  7200. PluginHost::settingsFolder().getChildFile ("recentes.txt").replaceWithText (recent.toString());
  7201. menuItemsChanged();
  7202. }
  7203. std::unique_ptr<juce::Component> MainComponent::makeHelpContent (const keys::KeyMap* keyMapIn)
  7204. {
  7205. // shortcut sheet: sections of "keys - action" rows, in two columns
  7206. struct Row
  7207. {
  7208. const char* keys;
  7209. const char* action;
  7210. };
  7211. struct Section
  7212. {
  7213. const char* title;
  7214. std::vector<Row> rows;
  7215. };
  7216. static const std::vector<Section> sections {
  7217. { TR_NOOP ("General"),
  7218. { { TR_NOOP ("Space"), TR_NOOP ("Play / stop (back to where playback started)") },
  7219. { "Ctrl+Space", TR_NOOP ("Play / pause") },
  7220. { "Ctrl+Z / Ctrl+Y", TR_NOOP ("Undo / redo") },
  7221. { "Ctrl+N / Ctrl+O", TR_NOOP ("New project / open") },
  7222. { "Ctrl+S / Ctrl+Shift+S", TR_NOOP ("Save / save as") },
  7223. { "Ctrl+R", TR_NOOP ("Export audio") },
  7224. { "Enter", TR_NOOP ("Maximize or restore the Playlist") },
  7225. { "L", TR_NOOP ("Pattern / song mode") },
  7226. { "Ctrl+T", TR_NOOP ("Typing keyboard to piano on/off") },
  7227. { "Z..M Q..P", TR_NOOP ("PC keyboard as a piano (selected channels)") },
  7228. { "Numpad +/-", TR_NOOP ("Next / previous pattern") },
  7229. { "Ctrl+Shift+Ins", TR_NOOP ("Insert an empty pattern before the current one") } } },
  7230. { TR_NOOP ("Workspace"),
  7231. { { TR_NOOP ("Drag a panel title"), TR_NOOP ("Move (snaps; Alt: free)") },
  7232. { TR_NOOP ("Double-click a title"), TR_NOOP ("Maximize / restore") },
  7233. { TR_NOOP ("Title buttons"), TR_NOOP ("Detach into a window, maximize, close") },
  7234. { TR_NOOP ("View menu"), TR_NOOP ("Reset, save and load layouts") } } },
  7235. { TR_NOOP ("Channel Rack and Mixer"),
  7236. { { TR_NOOP ("Click the name"), TR_NOOP ("Open/close the editor (Alt keeps others open)") },
  7237. { TR_NOOP ("Ctrl+click the name"), TR_NOOP ("Audition the channel") },
  7238. { TR_NOOP ("Selector / Up, Down"), TR_NOOP ("Select (Ctrl: add, Shift: range)") },
  7239. { "Alt+Up / Alt+Down", TR_NOOP ("Move the selected channels") },
  7240. { "Alt+C / Alt+Del", TR_NOOP ("Clone / delete the selected channels") },
  7241. { "Ctrl+L", TR_NOOP ("Send the selected channels to free mixer inserts") },
  7242. { TR_NOOP ("1..0 / Ctrl+1..0"), TR_NOOP ("Mute / solo channels 1-10 (typing piano off)") },
  7243. { TR_NOOP ("Knobs and faders"), TR_NOOP ("Drag (Ctrl: fine), wheel, Alt+click or middle-click resets") },
  7244. { TR_NOOP ("Right-click a knob/fader"), TR_NOOP ("Type value, reset, automation, MIDI link") },
  7245. { TR_NOOP ("Right-click Pattern / Song"), TR_NOOP ("Show the Channel Rack / Playlist") },
  7246. { TR_NOOP ("Double-click Stop"), TR_NOOP ("All notes off") } } },
  7247. { "Piano Roll",
  7248. { { TR_NOOP ("Click"), TR_NOOP ("Create a note (or chord, via the selector)") },
  7249. { TR_NOOP ("Drag"), TR_NOOP ("Move; the right edge changes the length") },
  7250. { TR_NOOP ("Right-click"), TR_NOOP ("Delete") },
  7251. { TR_NOOP ("Ctrl+drag"), TR_NOOP ("Select (Ctrl+click adds to the selection)") },
  7252. { TR_NOOP ("Shift+drag"), TR_NOOP ("Copy") },
  7253. { "Ctrl+A/C/X/V", TR_NOOP ("Select all, copy, cut, paste") },
  7254. { "Ctrl+B / Ctrl+Q", TR_NOOP ("Duplicate / quantize") },
  7255. { "Alt+M / Shift+Alt+M", TR_NOOP ("Mute / unmute") },
  7256. { "Ctrl+P / Ctrl+D", TR_NOOP ("Portamento / deselect") },
  7257. { TR_NOOP ("Shift+arrows"), TR_NOOP ("Transpose a semitone / move by the grid (Ctrl+Up/Down: an octave)") },
  7258. { TR_NOOP ("Alt / Ctrl+wheel"), TR_NOOP ("Disable snap / zoom") } } },
  7259. { "Playlist",
  7260. { { TR_NOOP ("Click"), TR_NOOP ("Paint the current pattern") },
  7261. { TR_NOOP ("Drag on the ruler"), TR_NOOP ("Set the loop (right-click clears)") },
  7262. { TR_NOOP ("Right-click a clip name"), TR_NOOP ("Split, make unique...") },
  7263. { TR_NOOP ("Track LED"), TR_NOOP ("Mute the track") },
  7264. { "Ctrl+A/C/X/V Ctrl+B", TR_NOOP ("Edit and duplicate") } } },
  7265. };
  7266. // the fourth column: every F-key of the live key map (issue #23: the sheet listed no F-keys), custom keys included
  7267. const keys::KeyMap defaults;
  7268. const auto& map = keyMapIn != nullptr ? *keyMapIn : defaults;
  7269. std::vector<std::pair<juce::String, juce::String>> functionKeys;
  7270. for (const auto& b : map.functionKeyBindings())
  7271. if (const auto* action = keys::findAction (b.actionId))
  7272. {
  7273. auto text = tr (action->description);
  7274. if (b.context != keys::Context::global)
  7275. text << " (" << tr (b.context == keys::Context::browser ? "Browser"
  7276. : b.context == keys::Context::mixer ? "Mixer"
  7277. : b.context == keys::Context::playlist ? "Playlist"
  7278. : b.context == keys::Context::pianoRoll ? "Piano Roll"
  7279. : "Channel Rack")
  7280. << ")";
  7281. functionKeys.push_back ({ juce::String (keys::displayString (b.chord)), text });
  7282. }
  7283. struct Sheet final : juce::Component
  7284. {
  7285. explicit Sheet (std::vector<std::pair<juce::String, juce::String>> f) : fkeys (std::move (f))
  7286. {
  7287. setSize (1500, juce::jmax (520, 20 + 28 + (int) fkeys.size() * 22 + 20));
  7288. }
  7289. void paint (juce::Graphics& g) override
  7290. {
  7291. using namespace theme;
  7292. g.fillAll (colour::bg2);
  7293. const auto columnWidth = (getWidth() - 5 * 24) / 4;
  7294. int column = 0, y = 20;
  7295. for (std::size_t i = 0; i < sections.size(); ++i)
  7296. {
  7297. if (i == 2 || i == 3) // next column
  7298. {
  7299. ++column;
  7300. y = 20;
  7301. }
  7302. const auto x = 24 + column * (columnWidth + 24);
  7303. const auto& section = sections[i];
  7304. g.setColour (colour::accent);
  7305. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  7306. g.setColour (colour::textPrimary);
  7307. g.setFont (font (type::title, true));
  7308. g.drawText (tr (section.title), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  7309. y += 28;
  7310. for (const auto& row : section.rows)
  7311. {
  7312. const auto keys = tr (row.keys);
  7313. g.setFont (font (type::small, true));
  7314. const auto keyWidth = juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14;
  7315. g.setColour (colour::bg4);
  7316. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  7317. g.setColour (colour::textPrimary);
  7318. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  7319. g.setColour (colour::textSecondary);
  7320. g.setFont (font (type::body));
  7321. g.drawFittedText (tr (row.action), x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.85f);
  7322. y += 24;
  7323. }
  7324. y += 14;
  7325. }
  7326. // Function keys
  7327. const auto x = 24 + 3 * (columnWidth + 24);
  7328. y = 20;
  7329. g.setColour (colour::accent);
  7330. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  7331. g.setColour (colour::textPrimary);
  7332. g.setFont (font (type::title, true));
  7333. g.drawText (tr ("Function keys"), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  7334. y += 28;
  7335. g.setFont (font (type::small, true));
  7336. int keyWidth = 0;
  7337. for (const auto& [keys, text] : fkeys)
  7338. keyWidth = juce::jmax (keyWidth, juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14);
  7339. for (const auto& [keys, text] : fkeys)
  7340. {
  7341. g.setFont (font (type::small, true));
  7342. g.setColour (colour::bg4);
  7343. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  7344. g.setColour (colour::textPrimary);
  7345. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  7346. g.setColour (colour::textSecondary);
  7347. g.setFont (font (type::body));
  7348. g.drawFittedText (text, x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.8f);
  7349. y += 22;
  7350. }
  7351. }
  7352. std::vector<std::pair<juce::String, juce::String>> fkeys;
  7353. };
  7354. return std::make_unique<Sheet> (std::move (functionKeys));
  7355. }
  7356. void MainComponent::showHelp()
  7357. {
  7358. juce::DialogWindow::LaunchOptions options;
  7359. options.content.setOwned (makeHelpContent (&keyMap).release());
  7360. options.dialogTitle = tr ("LYNX SHARE shortcuts");
  7361. options.dialogBackgroundColour = theme::colour::bg2;
  7362. options.useNativeTitleBar = true;
  7363. options.resizable = true;
  7364. options.escapeKeyTriggersCloseButton = true;
  7365. if (auto* dialog = options.launchAsync())
  7366. {
  7367. keepAboveMainWindow (*dialog);
  7368. helpWindow = dialog;
  7369. }
  7370. }
  7371. void MainComponent::closeHelp()
  7372. {
  7373. // (the key may come from the sheet itself: delete it after this call stack)
  7374. if (helpWindow == nullptr)
  7375. return;
  7376. helpWindow->setVisible (false);
  7377. juce::MessageManager::callAsync ([w = helpWindow] { delete w.getComponent(); });
  7378. helpWindow = nullptr;
  7379. }
  7380. void MainComponent::closeUnfocusedWindows()
  7381. {
  7382. // FL's Ctrl+F12 (CloseAllUnfocusedWindowsAction, round 167o): every window but the focused one closes. LYNX's
  7383. // docked or detached panels and dialogs that wait for an answer stay, as for F12.
  7384. auto* focused = juce::TopLevelWindow::getActiveTopLevelWindow();
  7385. auto* main = getTopLevelComponent();
  7386. juce::Array<juce::Component::SafePointer<juce::DocumentWindow>> close;
  7387. for (int i = 0; i < juce::TopLevelWindow::getNumTopLevelWindows(); ++i)
  7388. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (i)))
  7389. if (w != focused && w != main && w->isVisible() && ! w->isCurrentlyModal() && ! (bool) w->getProperties()["lynxPanel"])
  7390. close.add (w);
  7391. for (auto& w : close)
  7392. if (w != nullptr)
  7393. w->closeButtonPressed();
  7394. }
  7395. void MainComponent::showSetupWizard()
  7396. {
  7397. // on top of the main window (round 140), so the DAW is visible behind it from the first start on
  7398. if (setupOverlay != nullptr)
  7399. return;
  7400. auto safe = juce::Component::SafePointer<MainComponent> (this);
  7401. setupOverlay = lynx::makeSetupWizardOverlay (
  7402. engine,
  7403. [safe] (const juce::String& language) {
  7404. if (safe != nullptr)
  7405. safe->showLanguageChoice (language);
  7406. },
  7407. [safe] {
  7408. juce::MessageManager::callAsync ([safe] { // the overlay's own button is still running
  7409. if (safe != nullptr)
  7410. safe->setupOverlay.reset();
  7411. });
  7412. },
  7413. (int) layoutStyle,
  7414. [safe] (int style) { // round 184a S17: the workflow chosen in the wizard (Pattern stays selected unless changed)
  7415. juce::MessageManager::callAsync ([safe, style] {
  7416. if (safe == nullptr)
  7417. return;
  7418. safe->setLayoutStyle ((layoutstyle::Style) juce::jlimit (0, layoutstyle::count - 1, style));
  7419. safe->saveUiSettings();
  7420. });
  7421. });
  7422. addAndMakeVisible (*setupOverlay);
  7423. setupOverlay->setBounds (getLocalBounds());
  7424. setupOverlay->toFront (true);
  7425. hostSetupOverlayNatively();
  7426. }
  7427. void MainComponent::showImportReport()
  7428. {
  7429. // summary of what the .flp had that LYNX doesn't reproduce exactly (only when there is something to say)
  7430. const auto& r = engine.getImportReport();
  7431. const auto& missing = engine.getMissingPlugins();
  7432. auto list = [] (const std::map<std::string, int>& items) {
  7433. std::vector<std::pair<int, std::string>> sorted;
  7434. for (const auto& [name, count] : items)
  7435. sorted.push_back ({ count, name });
  7436. std::sort (sorted.rbegin(), sorted.rend());
  7437. juce::StringArray lines;
  7438. for (const auto& [count, name] : sorted)
  7439. lines.add (" " + juce::String::fromUTF8 (name.c_str()) + (count > 1 ? " (" + juce::String (count) + ")" : juce::String()));
  7440. return lines.joinIntoString ("\n");
  7441. };
  7442. juce::String text;
  7443. if (! r.approximated.empty())
  7444. text << tr ("Approximated by the built-in synth:") << "\n" << list (r.approximated) << "\n\n";
  7445. if (! r.unsupported.empty())
  7446. text << tr ("No equivalent (played with a synth preset):") << "\n" << list (r.unsupported) << "\n\n";
  7447. if (const auto& matched = engine.getMatchedPlugins(); ! matched.isEmpty())
  7448. text << tr ("Plugins found on this PC:") << "\n " << matched.joinIntoString ("\n ") << "\n\n";
  7449. if (! missing.isEmpty())
  7450. text << tr ("Plugins not installed on this PC (or in a folder LYNX SHARE doesn't scan; Options > Setup wizard):") << "\n "
  7451. << missing.joinIntoString ("\n ") << "\n\n";
  7452. if (const auto& lost = engine.getPluginsWithoutState(); ! lost.isEmpty())
  7453. text << tr ("Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):") << "\n "
  7454. << lost.joinIntoString ("\n ") << "\n\n";
  7455. if (const auto failed = engine.getPluginHost().getLoadFailures(); ! failed.isEmpty())
  7456. text << tr ("Plugins installed but not loaded (silent):") << "\n " << failed.joinIntoString ("\n ") << "\n\n";
  7457. if (! r.droppedEffects.empty())
  7458. text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
  7459. if (! r.partialEffects.empty())
  7460. text << tr ("Effects kept but approximated or partly reproduced:") << "\n" << list (r.partialEffects) << "\n\n";
  7461. if (r.missingSamples > 0)
  7462. text << tr ("Samples missing on this machine: {0}", { juce::String (r.missingSamples) }) << "\n";
  7463. if (r.relocatedSamples > 0)
  7464. text << tr ("Samples found in another folder than the project says (FL Studio's folders or next to the project): {0}",
  7465. { juce::String (r.relocatedSamples) }) << "\n";
  7466. if (text.isNotEmpty())
  7467. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Project import"), text.trimEnd());
  7468. }
  7469. void MainComponent::showAudioSettings()
  7470. {
  7471. openSettings ((int) SettingsPage::audio);
  7472. }
  7473. // --- the Channel Rack's filter box ---------------------------------------------------------------
  7474. void MainComponent::FilterBox::paint (juce::Graphics& g)
  7475. {
  7476. using namespace theme;
  7477. auto area = getLocalBounds().toFloat();
  7478. g.setColour (hovered ? colour::bg3 : colour::bg1);
  7479. g.fillRoundedRectangle (area, radius::sm);
  7480. g.setColour (hovered ? colour::borderStrong : colour::border);
  7481. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  7482. // round 170e2: a funnel names the box (it showed only "All")
  7483. icons::draw (g, Icon::filter, area.withWidth (22.0f).withSizeKeepingCentre (13.0f, 13.0f), colour::textSecondary);
  7484. g.setColour (colour::textPrimary);
  7485. g.setFont (font (type::small));
  7486. g.drawText (text, getLocalBounds().withTrimmedLeft (22).withTrimmedRight (16), juce::Justification::centredLeft, true);
  7487. icons::draw (g, Icon::chevronDown, area.removeFromRight (16.0f).reduced (3.0f).translated (-2.0f, 0.0f), colour::textSecondary);
  7488. }
  7489. // FL's Tools › Macros › Prepare for performance mode ([DECOMP] FUN_0122d010, its "Marker settings" dialog: marker count
  7490. // 4 / 8 / 16 / 32 / 64, default 16; spacing 1…128 steps, default 16 = a bar): room for a launch grid before the song,
  7491. // a marker per column, a Start marker, Performance mode on, the zone in view. FL warns it can't be undone; in LYNX it
  7492. // is one undo step.
  7493. void MainComponent::prepareForPerformance()
  7494. {
  7495. auto* window = new juce::AlertWindow (tr ("Prepare for performance mode"),
  7496. tr ("Inserts empty columns before the song for the clips to launch, a marker on each, and a Start "
  7497. "marker where the song begins; Performance mode is turned on."),
  7498. juce::MessageBoxIconType::NoIcon);
  7499. window->addComboBox ("count", { "4", "8", "16", "32", "64" }, tr ("Marker count"));
  7500. 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") },
  7501. tr ("Spacing"));
  7502. if (auto* c = window->getComboBoxComponent ("count"))
  7503. c->setSelectedItemIndex (2, juce::dontSendNotification);
  7504. if (auto* c = window->getComboBoxComponent ("spacing"))
  7505. c->setSelectedItemIndex (4, juce::dontSendNotification);
  7506. window->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  7507. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7508. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  7509. if (result != 1)
  7510. return;
  7511. const auto count = 4 << juce::jlimit (0, 4, window->getComboBoxComponent ("count")->getSelectedItemIndex());
  7512. const auto steps = 1 << juce::jlimit (0, 7, window->getComboBoxComponent ("spacing")->getSelectedItemIndex());
  7513. engine.editSong ([count, steps] (Song& s) { perf::prepareForPerformance (s, count, (std::int64_t) steps * (ppq / 4)); });
  7514. showPanel (Panel::playlist);
  7515. playlist.runAction ("playlist.zoomPerformance");
  7516. }),
  7517. true);
  7518. keepAboveMainWindow (*window);
  7519. }
  7520. } // namespace lynx
  7521. // --- the game controller (round 184a, S16) ---------------------------------------------------------------------------
  7522. namespace lynx
  7523. {
  7524. void MainComponent::updateGamepad()
  7525. {
  7526. const auto on = engine.getMidiPrefs().gamepad;
  7527. if (on == (gamepadInput != nullptr))
  7528. return;
  7529. if (! on)
  7530. {
  7531. gamepadInput.reset();
  7532. if (gamepadHints != nullptr)
  7533. removeChildComponent (gamepadHints.get());
  7534. gamepadHints.reset();
  7535. return;
  7536. }
  7537. gamepadInput = std::make_unique<GamepadInput> ([safe = juce::Component::SafePointer<MainComponent> (this)] (const gamepad::Changes& c,
  7538. const gamepad::State& s, double dt) {
  7539. if (safe != nullptr)
  7540. safe->gamepadChanges (c, s, dt);
  7541. });
  7542. if (! gamepadInput->available())
  7543. ui::postHint ({ tr ("Game controllers are not supported on this system yet."), {} }, 5000);
  7544. }
  7545. int MainComponent::gamepadInsert() const
  7546. {
  7547. const auto& song = engine.getSong();
  7548. const auto track = playlist.getCurrentTrack();
  7549. if (track >= 0 && track < (int) song.playlistTracks.size())
  7550. if (const auto insert = song.playlistTracks[(std::size_t) track].mixerTrack; insert >= 0 && insert < (int) song.mixer.size())
  7551. return insert;
  7552. const auto channel = engine.getSelectedChannel();
  7553. if (channel >= 0 && channel < (int) song.channels.size())
  7554. if (const auto insert = song.channels[(std::size_t) channel].mixerTrack; insert >= 0 && insert < (int) song.mixer.size())
  7555. return insert;
  7556. return -1;
  7557. }
  7558. void MainComponent::gamepadChanges (const gamepad::Changes& c, const gamepad::State& s, double seconds)
  7559. {
  7560. using namespace gamepad;
  7561. // every change is also a MIDI controller on channel 16, so Link to controller can learn it
  7562. for (int i = 0; i < c.controllerCount; ++i)
  7563. engine.injectMidiInput (juce::MidiMessage::controllerEvent (midiChannel, c.controller[(std::size_t) i], c.value[(std::size_t) i]));
  7564. if (c.connectedChanged)
  7565. ui::postHint ({ s.connected ? tr ("Game controller connected") : tr ("Game controller disconnected"), {} }, 3000);
  7566. const auto& map = defaultMap();
  7567. for (int i = 0; i < c.pressedCount; ++i)
  7568. {
  7569. const auto action = map[(std::size_t) c.pressed[(std::size_t) i]];
  7570. switch (action)
  7571. {
  7572. case Action::playStop: runAction ("transport.playStop"); break;
  7573. case Action::record: runAction ("transport.record"); break;
  7574. case Action::undo: runAction ("edit.undo"); break;
  7575. case Action::metronome: runAction ("transport.metronome"); break;
  7576. case Action::previousPattern: runAction ("pattern.previous"); break;
  7577. case Action::nextPattern: runAction ("pattern.next"); break;
  7578. case Action::finish: runAction ("file.export"); break;
  7579. case Action::previousTrack:
  7580. case Action::nextTrack:
  7581. {
  7582. const auto t = playlist.getCurrentTrack();
  7583. playlist.selectTrack (t < 0 ? 0 : t + (action == Action::nextTrack ? 1 : -1));
  7584. const auto& song = engine.getSong();
  7585. const auto now = playlist.getCurrentTrack();
  7586. if (now >= 0 && now < (int) song.playlistTracks.size())
  7587. if (const auto ch = song.playlistTracks[(std::size_t) now].channel; ch >= 0 && ch < (int) song.channels.size())
  7588. engine.setSelectedChannel (ch); // an instrument track: its channel plays the keys
  7589. break;
  7590. }
  7591. case Action::barBack:
  7592. case Action::barForward:
  7593. {
  7594. // to the previous / next bar line (from inside a bar, back goes to its start)
  7595. const auto bar = (double) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  7596. const auto at = engine.getTransport().positionTicks.load() / bar;
  7597. const auto target = action == Action::barForward ? std::floor (at + 1e-6) + 1.0 : std::ceil (at - 1e-6) - 1.0;
  7598. engine.seek (juce::jmax (0.0, target) * bar);
  7599. break;
  7600. }
  7601. case Action::hints:
  7602. if (gamepadHints == nullptr)
  7603. {
  7604. gamepadHints = makeGamepadHints();
  7605. addChildComponent (*gamepadHints);
  7606. }
  7607. gamepadHints->setCentrePosition (getLocalBounds().getCentre());
  7608. gamepadHints->setVisible (true);
  7609. gamepadHints->toFront (false);
  7610. break;
  7611. case Action::none:
  7612. break;
  7613. }
  7614. }
  7615. for (int i = 0; i < c.releasedCount; ++i)
  7616. if (map[(std::size_t) c.released[(std::size_t) i]] == Action::hints && gamepadHints != nullptr)
  7617. gamepadHints->setVisible (false);
  7618. // the triggers: the selected track's volume; the left stick's X: its pan (only while pushed)
  7619. const auto insert = gamepadInsert();
  7620. if (insert < 0)
  7621. return;
  7622. if (const auto db = volumeStepDb (s, seconds); db != 0.0)
  7623. engine.editLevels ([insert, db] (Song& song) {
  7624. auto& v = song.mixer[(std::size_t) insert].volume;
  7625. v = juce::jlimit (0.0f, 1.0f, faderPosition (faderGain (v) * juce::Decibels::decibelsToGain ((float) db)));
  7626. });
  7627. if (const auto pan = axis (s, Axis::leftX); pan != 0.0f)
  7628. engine.editLevels ([insert, pan] (Song& song) { song.mixer[(std::size_t) insert].pan = juce::jlimit (-1.0f, 1.0f, pan); });
  7629. }
  7630. } // namespace lynx