MainComponent.cpp 286 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687
  1. #include "ui/ThemeSettings.h"
  2. #include "ui/ColourPicker.h"
  3. #include "core/NoteNames.h"
  4. #include "ui/ProjectLoading.h"
  5. #include "ui/UiTrace.h"
  6. #include "core/LoadTrace.h"
  7. #include "ui/MainComponent.h"
  8. #include "core/Performance.h"
  9. #include "core/TransportEdit.h"
  10. #include "ui/CrashReporter.h"
  11. #include "ui/DanceView.h"
  12. #include "engine/AudioLogger.h"
  13. #include "ui/PluginSkin.h"
  14. #include "platform/Paths.h"
  15. #include "ui/SetupWizard.h"
  16. #include "core/FlPluginDb.h"
  17. #include "core/Preferences.h"
  18. #include "core/EditorPolish.h"
  19. #include "ui/HistoryPanel.h"
  20. #include "ui/MissingFilesDialog.h"
  21. #include "ui/SettingsDialog.h"
  22. #include "ui/PluginManager.h"
  23. #include "ui/ShortcutManager.h"
  24. #include "ui/WaveformView.h"
  25. #include "ui/QuickAddPalette.h"
  26. #include "ui/PatcherEditor.h"
  27. #include "ui/ToolWindow.h"
  28. #include "ui/LoopStarterWindow.h"
  29. #include "ui/WindowOwner.h"
  30. #include "engine/PluginSandbox.h"
  31. #include "platform/FileTypes.h"
  32. #include "platform/CrashGuard.h"
  33. #include "platform/LinuxRealtime.h"
  34. #include "platform/Package.h"
  35. #include "engine/Text.h"
  36. #include "core/MetronomeVoice.h"
  37. #include "core/RackOps.h"
  38. #include "core/Templates.h"
  39. #include "ui/NewProjectDialog.h"
  40. #include "ui/PluginMonitorWindow.h"
  41. #include "ui/TouchKeyboard.h"
  42. #include "engine/MidiFileIo.h"
  43. #include "engine/ProjectFile.h"
  44. #include "engine/ProjectPackage.h"
  45. #include "engine/SessionPack.h"
  46. #include "ui/SessionDialogs.h"
  47. #include "engine/LiveSessions.h"
  48. #include "ui/LiveChat.h"
  49. #include "core/ProjectSafety.h"
  50. #include "core/MissingFiles.h"
  51. #include "ui/AutomationUi.h"
  52. #include "ui/ChannelSettings.h"
  53. #include "ui/Dialogs.h"
  54. #include "ui/EditorTools.h"
  55. #include "ui/AudioEditor.h"
  56. #include "ui/TempoTapper.h"
  57. #include "ui/ExportDialog.h"
  58. #include "ui/ParametricEqEditor.h"
  59. #include "ui/PluginWindow.h"
  60. #include "ui/I18n.h"
  61. #include "ui/Theme.h"
  62. #include "ui/WaveformView.h"
  63. #include "core/HintMarkup.h"
  64. #include "core/SongStats.h"
  65. namespace lynx
  66. {
  67. namespace
  68. {
  69. using workspace::Panel;
  70. constexpr Panel panelOrder[] = { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser };
  71. const char* panelAction (Panel p)
  72. {
  73. switch (p)
  74. {
  75. case Panel::playlist: return "panel.playlist";
  76. case Panel::channelRack: return "panel.channelRack";
  77. case Panel::pianoRoll: return "panel.pianoRoll";
  78. case Panel::mixer: return "panel.mixer";
  79. case Panel::browser: return "panel.browser";
  80. }
  81. return "";
  82. }
  83. juce::String panelName (Panel p)
  84. {
  85. switch (p)
  86. {
  87. case Panel::playlist: return "Playlist";
  88. case Panel::channelRack: return "Channel Rack";
  89. case Panel::pianoRoll: return "Piano Roll";
  90. case Panel::mixer: return "Mixer";
  91. case Panel::browser: return "Browser";
  92. }
  93. return {};
  94. }
  95. } // namespace
  96. MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
  97. : persistent (restoreUserSettings),
  98. engine (e),
  99. rack (e),
  100. pianoRoll (e),
  101. playlist (e),
  102. mixer (e),
  103. browser (e)
  104. {
  105. heldKeys.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on, true); });
  106. connectBrowser (browser);
  107. addChildComponent (updateBar);
  108. updateBar.onVisibilityChanged = [this] { resized(); };
  109. if (restoreUserSettings) // (the real window: Update saves the project as on quit and reopens it)
  110. updater::setHost ({ [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  111. if (safe != nullptr)
  112. safe->confirmDiscard (std::move (then));
  113. },
  114. [safe = juce::Component::SafePointer<MainComponent> (this)] {
  115. return safe != nullptr ? safe->currentFile : juce::File();
  116. } });
  117. mixeroptions::changed = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  118. if (safe != nullptr)
  119. {
  120. safe->saveUiSettings();
  121. safe->playlist.repaint();
  122. }
  123. };
  124. mixeroptions::setShowUsedOnly = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  125. if (safe != nullptr)
  126. safe->mixer.getStripsForSnapshot().setShowUsedOnly (on);
  127. };
  128. mixeroptions::renderTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks,
  129. std::function<void (const std::vector<juce::File>&)> done) {
  130. if (safe != nullptr)
  131. showExportDialogForTracks (safe->engine, safe->currentFile.getParentDirectory(), safe->projectName, tracks, std::move (done));
  132. };
  133. if (persistent)
  134. {
  135. loadUiSettings();
  136. // the start-up song follows Options › Mixer too (round 163) and the automatic crossfades of new projects (166e)
  137. engine.setSong (makeNewProject());
  138. skin::onStyleSettingsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // an editor's own style was picked
  139. if (safe != nullptr) safe->saveUiSettings();
  140. };
  141. loadKeyMap();
  142. startSession();
  143. if (BrowserComponent::sampleBrowserWasOpen()) // it was open when LYNX closed (round 163)
  144. juce::Timer::callAfterDelay (800, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  145. if (safe != nullptr && findToolWindow ("sampleBrowser") == nullptr)
  146. safe->openSampleBrowser();
  147. });
  148. EditorGlobals::get().onOptionsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // Follow on/off
  149. if (safe != nullptr) safe->saveUiSettings();
  150. };
  151. }
  152. PianoRollComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  153. pianoRoll.onBrowseScores = [this] { // (round 168g: the Piano roll's File › Browse scores)
  154. showPanel (Panel::browser);
  155. browser.showScores();
  156. };
  157. newButton.setTooltip (tr ("New project") + " (Ctrl+N)");
  158. newButton.onClick = [this] { newProject(); };
  159. openButton.setTooltip (tr ("Open project") + " (Ctrl+O)");
  160. openButton.onClick = [this] { chooseFileToOpen(); };
  161. saveButton.setTooltip (tr ("Save project") + " (Ctrl+S)");
  162. saveButton.onClick = [this] { save (false); };
  163. exportButton.setTooltip (tr ("Export audio: WAV, FLAC or OGG") + " (Ctrl+R)");
  164. exportButton.onClick = [this] { exportAudio(); };
  165. auto withKey = [this] (const juce::String& text, const char* id) {
  166. const auto key = shortcutText (id).trim();
  167. return key.isEmpty() ? text : text + " (" + key + ")";
  168. };
  169. undoButton.setTooltip (withKey (tr ("Undo"), "edit.undo"));
  170. undoButton.onClick = [this] { flUndo(); }; // FL's toolbar Undo is its Edit › Undo (UndoAction)
  171. undoButton.onRightClick = [this] { showHistory(); };
  172. redoButton.setTooltip (withKey (tr ("Redo"), "edit.redo"));
  173. redoButton.onClick = [this] { undoRedo (true); };
  174. redoButton.onRightClick = [this] { showHistory(); };
  175. pluginPickerButton.setTooltip (withKey (tr ("Plugin picker: add an instrument or plugin as a new channel"), "panel.quickAdd"));
  176. pluginPickerButton.onClick = [this] { showQuickAdd(); };
  177. // transport: Play toggles play / stop-and-back; Stop returns to the start; double-click Stop = all notes off
  178. playButton.setTooltip (tr ("Play; pressed again, stops and goes back to where it started") + " (Space; Ctrl+Space pauses)");
  179. playButton.onClick = [this] { playStop(); };
  180. stopButton.setTooltip (tr ("Stop and return to the start (double-click: back to the start and all notes off)"));
  181. stopButton.onClick = [this] { stopAndRewind(); };
  182. stopButton.onDoubleClick = [this] { // FL-like: a double Stop goes back to the very start (and silences hanging notes)
  183. engine.panic();
  184. stopAndRewind (true);
  185. };
  186. stopButton.onRightClick = [this] { showStopMenu(); };
  187. output.onModeChanged = [this] { saveUiSettings(); };
  188. recordButton.setOnColour (theme::colour::record);
  189. recordButton.setIconColour (theme::colour::record.withMultipliedSaturation (0.8f));
  190. recordButton.onClick = [this] { toggleRecording(); };
  191. recordMenuButton.setTooltip (tr ("Recording options: what to record"));
  192. recordMenuButton.onClick = [this] { showRecordMenu(); };
  193. recordButton.onRightClick = [this] { showRecordMenu(); };
  194. // Pattern / Song: a two-segment switch (L toggles); right-click shows the matching panel
  195. // as in FL, a two-line switch in front of the transport buttons: pattern on top, song below
  196. patternModeButton.setText (tr ("Pattern"));
  197. songModeButton.setText (tr ("Song"));
  198. for (auto* b : { &patternModeButton, &songModeButton })
  199. {
  200. b->setOnColour (theme::colour::bg6);
  201. b->setIconColourWhenOn (theme::colour::textPrimary);
  202. }
  203. patternModeButton.setTooltip (tr ("Pattern mode: plays the current pattern in a loop") + " (L)\n" + tr ("Right-click: show the Channel Rack"));
  204. songModeButton.setTooltip (tr ("Song mode: plays the Playlist arrangement") + " (L)\n" + tr ("Right-click: show the Playlist"));
  205. patternModeButton.onClick = [this] {
  206. if (engine.getSong().mode != PlayMode::pattern)
  207. toggleMode();
  208. };
  209. songModeButton.onClick = [this] {
  210. if (engine.getSong().mode != PlayMode::song)
  211. toggleMode();
  212. };
  213. patternModeButton.onRightClick = [this] { showPanel (Panel::channelRack); };
  214. songModeButton.onRightClick = [this] { showPanel (Panel::playlist); };
  215. metronomeButton.setClickingTogglesState (true);
  216. metronomeButton.setOnColour (theme::colour::bg6);
  217. metronomeButton.setIconColourWhenOn (theme::colour::accent);
  218. metronomeButton.setTooltip (tr ("Metronome"));
  219. metronomeButton.onClick = [this] { engine.getTransport().metronome.store (metronomeButton.getToggleState()); };
  220. midiLight.onReconnect = [this] {
  221. engine.reconnectMidiInputs();
  222. midiInputTicks = 0; // shows the reopened inputs at the next tick
  223. };
  224. metronomeButton.onRightClick = [this] { showMetronomeMenu(); };
  225. typingPianoButton.setOnColour (theme::colour::bg6);
  226. typingPianoButton.setIconColourWhenOn (theme::colour::accent);
  227. typingPianoButton.onClick = [this] { toggleTypingPiano(); };
  228. typingPianoButton.onRightClick = [this] { showTypingPianoMenu(); };
  229. // count-in and wait-for-input switches next to the metronome, as in FL's recording panel
  230. for (auto* b : { &countInButton, &waitInputButton })
  231. {
  232. b->setOnColour (theme::colour::bg6);
  233. b->setIconColourWhenOn (theme::colour::accent);
  234. }
  235. countInButton.onClick = [this] { runAction ("record.countIn"); };
  236. waitInputButton.onClick = [this] { runAction ("record.waitForInput"); };
  237. for (int i = 0; i < workspace::panelCount; ++i)
  238. {
  239. const auto panel = (Panel) i;
  240. auto& b = panelButtons[(std::size_t) i];
  241. b.setFlat (true);
  242. b.setOnColour (theme::colour::bg5);
  243. b.setIconColourWhenOn (theme::colour::textPrimary);
  244. b.setTooltip (panelName (panel) + " (" + keys::displayString (keyMap.chordsFor (panelAction (panel)).empty() ? keys::Chord {}
  245. : keyMap.chordsFor (panelAction (panel)).front()) + ")\n"
  246. + tr ("Click: show, focus or hide. Right-click: show maximized"));
  247. b.onClick = [this, panel] { togglePanel (panel); };
  248. b.onRightClick = [this, panel] {
  249. showPanel (panel);
  250. if (! workspace.isMaximised (panel) && ! workspace.isDetached (panel))
  251. workspace.toggleMaximised (panel);
  252. refreshPanelButtons();
  253. };
  254. }
  255. patternBox.setTooltip (tr ("Current pattern (Numpad +/-: next/previous, F4: next empty, F2: rename)"));
  256. patternBox.setScrollWheelEnabled (true);
  257. gridBox.setScrollWheelEnabled (true);
  258. patternBox.onChange = [this]
  259. {
  260. const auto index = patternBox.getSelectedItemIndex();
  261. if (index >= 0 && index != engine.getSong().currentPattern)
  262. selectPattern (index);
  263. };
  264. newPatternButton.setTooltip (tr ("New pattern"));
  265. newPatternButton.onClick = [this]
  266. {
  267. engine.editSong ([] (Song& s) {
  268. Pattern p;
  269. p.name = newPatternName (s);
  270. s.patterns.push_back (std::move (p));
  271. s.currentPattern = (int) s.patterns.size() - 1;
  272. });
  273. };
  274. swingSlider.setRange (0.0, 1.0, 0.01);
  275. swingSlider.setDoubleClickReturnValue (true, 0.0);
  276. swingSlider.setValue (engine.getSong().swing, juce::dontSendNotification);
  277. swingSlider.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  278. swingSlider.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  279. swingSlider.onValueChange = [this] { engine.editSong ([v = (float) swingSlider.getValue()] (Song& s) { s.swing = v; }); };
  280. swingSlider.setTooltip (tr ("Swing of the Channel Rack (all channels)"));
  281. swingSlider.setMouseClickGrabsKeyboardFocus (false);
  282. swingSlider.setWantsKeyboardFocus (false);
  283. patternMenuButton.setTooltip (tr ("Pattern: rename, color, clone, insert, split, length, delete"));
  284. patternMenuButton.onClick = [this] { showPatternMenu(); };
  285. // the workspace panels
  286. rack.onOpenPianoRoll = [this] { openPianoRoll(); };
  287. mixerinput::openAudioSettings = [this] { openSettings ((int) SettingsPage::audio); };
  288. PatcherWindows::onBrowsePluginDatabase = [this] (bool) {
  289. showPanel (Panel::browser);
  290. browser.showPluginDatabaseForSnapshot(); // (its Generators and Effects folders open)
  291. if (auto* w = getTopLevelComponent())
  292. w->toFront (true);
  293. };
  294. rack.onOpenMixerInsert = [this] (int insert) { // double-click on a channel's route box
  295. showPanel (Panel::mixer);
  296. mixer.selectTrack (insert);
  297. };
  298. openMixerInsertHandler() = rack.onOpenMixerInsert; // and on the channel window's TRACK box (round 168s)
  299. mixer.onInstrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); };
  300. rackViewport.setViewedComponent (&rack, false);
  301. rackViewport.setScrollBarsShown (true, true);
  302. workspace.setContent (Panel::playlist, playlistArea, "Playlist", Icon::playlist);
  303. workspace.setContent (Panel::channelRack, rackViewport, "Channel Rack", Icon::channelRack);
  304. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll);
  305. workspace.setContent (Panel::mixer, mixer, "Mixer", Icon::mixer);
  306. workspace.setContent (Panel::browser, browser, "Browser", Icon::browser);
  307. workspace.setTitleTooltip (Panel::channelRack, tr ("Shift+wheel here changes the pattern"));
  308. // FL keeps the channel filter, the global swing and the graph editor switch in the rack's title bar
  309. rackFilterBox.text = rack.filterName();
  310. rackFilterBox.onClick = [this] { rack.showFilterMenu (&rackFilterBox); };
  311. rack.onFilterChanged = [this] {
  312. rackFilterBox.text = rack.filterName();
  313. rackFilterBox.repaint();
  314. rackGraphButton.setToggleState (rack.areGraphLanesShown(), juce::dontSendNotification);
  315. rackPianoRollButton.setToggleState (rack.isPianoRollView(), juce::dontSendNotification);
  316. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  317. };
  318. rackGraphButton.setClickingTogglesState (false);
  319. rackGraphButton.onClick = [this] { rack.toggleGraphLanes(); };
  320. // the step sequencer / piano-roll view switch (FL keeps it in the rack's title bar too)
  321. rackPianoRollButton.setClickingTogglesState (false);
  322. rackPianoRollButton.setOnColour (theme::colour::bg6);
  323. rackPianoRollButton.setIconColourWhenOn (theme::colour::accent);
  324. rackPianoRollButton.onClick = [this] { runAction ("rack.pianoRollView"); };
  325. ui::setHint (rackPianoRollButton, tr ("Piano-roll view: every channel shows its notes as a miniature piano roll (click one to edit it) "
  326. "instead of the step buttons; click again for the steps"));
  327. rackTitleTools.addAndMakeVisible (rackPianoRollButton);
  328. // Follow (issue #12): a long pattern pages along with the playing step
  329. rackFollowButton.setClickingTogglesState (false);
  330. rackFollowButton.setOnColour (theme::colour::bg6);
  331. rackFollowButton.setIconColourWhenOn (theme::colour::accent);
  332. rackFollowButton.setWantsKeyboardFocus (false);
  333. rackFollowButton.setMouseClickGrabsKeyboardFocus (false);
  334. rackFollowButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  335. rackFollowButton.setTooltip (tr ("Follow: a pattern longer than the Channel Rack pages along with the playing step; off, it stays where you scrolled"));
  336. ui::setQuickTip (rackFollowButton, tr ("Follow the playhead"));
  337. rackFollowButton.onClick = [this] { runAction ("rack.follow"); };
  338. rackTitleTools.addAndMakeVisible (rackFollowButton);
  339. // FL's Loop button (round 165f-rack): click switches the pattern's channel looping, right-click its loop type and burns
  340. rackLoopButton.setClickingTogglesState (false);
  341. rackLoopButton.setOnColour (theme::colour::bg6);
  342. rackLoopButton.setIconColourWhenOn (theme::colour::accent);
  343. rackLoopButton.onClick = [this] { rack.toggleLooping(); };
  344. rackLoopButton.onRightClick = [this] { rack.showLoopMenu (&rackLoopButton); };
  345. ui::setHint (rackLoopButton, tr ("Channel looping: channels shorter than the pattern repeat to its end (polyrhythms) [LMB] on / off "
  346. "[RMB] loop type (step channels, all channels, advanced) and Burn to pattern"));
  347. rackTitleTools.addAndMakeVisible (rackLoopButton);
  348. // Loop Starter (round 168b; FL 25's dice in the Channel Rack): a drum loop of the genre's kit, re-rolled with dice
  349. rackLoopStarterButton.setWantsKeyboardFocus (false);
  350. rackLoopStarterButton.onClick = [this] { loopstarterui::open (engine); };
  351. 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"));
  352. rackTitleTools.addAndMakeVisible (rackLoopStarterButton);
  353. // the pattern selector (issue #9): change the pattern the rack edits right from its title bar
  354. rackPatternSelector.onStep = [this] (int delta) { selectPattern (stepPattern (engine.getSong(), delta)); };
  355. rackPatternSelector.onMenu = [this] { showRackPatternList(); };
  356. ui::setHint (rackPatternSelector, tr ("Pattern the Channel Rack edits: [LMB] on the name: the list of patterns, on the arrows: previous / next [Wheel] step"));
  357. rackTitleTools.addAndMakeVisible (rackPatternSelector);
  358. rackTitleTools.addAndMakeVisible (rackFilterBox);
  359. rackTitleTools.addAndMakeVisible (swingSlider);
  360. // the pattern length in bars (issue #12)
  361. rackLengthBox.onSet = [this] (int bars) {
  362. const auto index = engine.getSong().currentPattern;
  363. const auto ticks = (std::int64_t) juce::jlimit (0, 999, bars) * ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  364. if (index >= 0 && index < (int) engine.getSong().patterns.size() && engine.getSong().patterns[(std::size_t) index].lengthTicks != ticks)
  365. engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; });
  366. refreshRackLengthBox();
  367. };
  368. rackLengthBox.onMenu = [this] { showPatternLengthMenu(); };
  369. ui::setHint (rackLengthBox, tr ("Pattern length in bars: [LMB] drag or [Wheel] change it [2xLMB] automatic (from the notes) [RMB] menu"));
  370. rackTitleTools.addAndMakeVisible (rackLengthBox);
  371. rackTitleTools.addAndMakeVisible (rackGraphButton);
  372. rackTitleTools.layout = [this] {
  373. auto r = rackTitleTools.getLocalBounds();
  374. rackPatternSelector.setBounds (r.removeFromLeft (rackPatternSelectorWidth).reduced (0, 3));
  375. r.removeFromLeft (6);
  376. rackFilterBox.setBounds (r.removeFromLeft (96).reduced (0, 3));
  377. r.removeFromLeft (4);
  378. swingSlider.setBounds (r.removeFromLeft (26));
  379. r.removeFromLeft (4);
  380. rackLengthBox.setBounds (r.removeFromLeft (rackLengthBoxWidth).reduced (0, 3));
  381. r.removeFromLeft (4);
  382. rackGraphButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  383. r.removeFromLeft (4);
  384. rackPianoRollButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  385. r.removeFromLeft (4);
  386. rackFollowButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  387. r.removeFromLeft (4);
  388. rackLoopButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  389. r.removeFromLeft (4);
  390. rackLoopStarterButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  391. };
  392. workspace.setTitleAccessory (Panel::channelRack, &rackTitleTools, rackTitleToolsWidth);
  393. workspace.setTitleAccessory (Panel::mixer, &mixer.getLayoutBox(), MixerLayoutBox::width); // FL's "Mixer layout" (issue #52)
  394. mixer.getStripsForSnapshot().onLayoutChanged = [this] {
  395. mixer.getLayoutBox().repaint();
  396. mixer.selectTrack (mixer.getStripsForSnapshot().getSelectedTrack()); // keep the selected strip in view
  397. saveUiSettings();
  398. };
  399. workspace.onPanelMenu = [this] (Panel panel, juce::PopupMenu& menu) { addPanelMenuItems (panel, menu); };
  400. workspace.onFocusChanged = [this] (Panel panel) {
  401. refreshPanelButtons();
  402. // another panel took over (a click, F5..F9): the Browser's search box gives the keys back (issue #9)
  403. if (panel != Panel::browser)
  404. browser.leaveSearchBox();
  405. };
  406. workspace.onKeyInDetachedWindow = [this] (const juce::KeyPress& key) { return keyPressed (key); };
  407. workspace.onTitleWheel = [this] (Panel panel, const juce::MouseEvent& ev, const juce::MouseWheelDetails& wheel) {
  408. if (panel == Panel::channelRack && ev.mods.isShiftDown())
  409. selectPattern (stepPattern (engine.getSong(), (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1));
  410. };
  411. workspace.onTitleRightClick = [this] (Panel panel, const juce::MouseEvent&) {
  412. if (panel == Panel::channelRack)
  413. showPatternMenu();
  414. };
  415. workspace.onDefaultLayout = [this] { fitChannelRack (true); };
  416. workspace.setPersistent (persistent);
  417. playlist.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  418. playlist.onOpenPianoRoll = [this] {
  419. // edit a channel that plays in this pattern
  420. const auto& song = engine.getSong();
  421. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  422. const auto channel = engine.getSelectedChannel();
  423. if (! notes.empty() && std::none_of (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }))
  424. engine.setSelectedChannel (notes.front().channel);
  425. openPianoRoll();
  426. };
  427. picker.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  428. picker.onPatternMenu = [this] { makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition()); };
  429. picker.onNewPattern = [this] { newPatternButton.onClick(); };
  430. playlist.onRenamePattern = [this] (int p) { showRenamePattern (p); };
  431. playlist.onOpenInSampler = [this] (int channel) {
  432. // the audio clip's file in a new Sampler channel (to play it from notes), its settings open
  433. const auto& song = engine.getSong();
  434. if (channel < 0 || channel >= (int) song.channels.size())
  435. return;
  436. ChannelDef c;
  437. c.name = song.channels[(std::size_t) channel].name;
  438. c.instrument = InstrumentKind::sampler;
  439. c.samplePath = song.channels[(std::size_t) channel].samplePath;
  440. c.colour = song.channels[(std::size_t) channel].colour;
  441. const auto added = rack.addChannel (c, false);
  442. showPanel (Panel::channelRack);
  443. rack.toggleEditor (added, false);
  444. };
  445. ui::setHint (pianoRoll, tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  446. ui::setHint (playlist, tr ("Playlist: [LMB] paint the current pattern [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  447. // recent files (stored in %APPDATA%\LYNX)
  448. recent.setMaxNumberOfItems (12);
  449. recent.restoreFromString (PluginHost::settingsFolder().getChildFile ("recentes.txt").loadFileAsString());
  450. addAndMakeVisible (menuBar);
  451. for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  452. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  453. &tempoDisplay, &patternBox, &newPatternButton, &patternMenuButton, &pluginPickerButton, &timeDisplay,
  454. &songPosition, &masterVolume, &masterPitch, &perfMeter, &output, &hintBar, &tweakReadout, &workspace, &midiLight })
  455. {
  456. addAndMakeVisible (c);
  457. c->setMouseClickGrabsKeyboardFocus (false); // the PC keyboard stays with the main window
  458. }
  459. // the dancers of the project's dance channels (FL's Fruity Dance) over the workspace (round 165e)
  460. danceStage = std::make_unique<DanceStage> (engine);
  461. danceStage->setMouseClickGrabsKeyboardFocus (false);
  462. addAndMakeVisible (*danceStage);
  463. for (auto& b : panelButtons)
  464. {
  465. addAndMakeVisible (b);
  466. b.setMouseClickGrabsKeyboardFocus (false);
  467. b.setWantsKeyboardFocus (false);
  468. }
  469. for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  470. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  471. &newPatternButton, &patternMenuButton, &pluginPickerButton })
  472. b->setWantsKeyboardFocus (false);
  473. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton, &patternMenuButton,
  474. &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton })
  475. b->setFlat (true);
  476. // a light header: every toolbar button is flat; "on" is a faint wash, in the accent for the states that
  477. // matter while working (playing, recording, metronome, recording options)
  478. {
  479. using namespace theme;
  480. const auto onWash = colour::accent.withAlpha (0.16f), onIcon = colour::accentHover;
  481. for (auto* b : { &playButton, &stopButton, &recordButton, &patternModeButton, &songModeButton })
  482. b->setFlat (true);
  483. playButton.setOnColour (onWash);
  484. playButton.setIconColourWhenOn (onIcon);
  485. recordButton.setOnColour (colour::record.withAlpha (0.2f));
  486. recordButton.setIconColourWhenOn (colour::record);
  487. for (auto* b : { &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &patternModeButton, &songModeButton })
  488. {
  489. b->setOnColour (onWash);
  490. b->setIconColourWhenOn (onIcon);
  491. }
  492. for (auto& b : panelButtons)
  493. {
  494. b.setOnColour (colour::textPrimary.withAlpha (0.08f));
  495. b.setIconColourWhenOn (colour::textPrimary);
  496. }
  497. }
  498. quickTips = std::make_unique<ui::QuickTipWindow>();
  499. ui::installSliderContract();
  500. // FL's Last tweaked and automation recording (REA round 143): every automatable control reports its moves
  501. ui::onTweak = [this] (const AutomationTarget& t) { engine.noteTweaked (t); };
  502. // Options › Theme › Startup sound: its Play button (issue #12)
  503. themeui::previewStartupSound = [this] (const juce::String& path) {
  504. std::shared_ptr<const SampleData> sound;
  505. if (path.isNotEmpty() && juce::File (path).existsAsFile())
  506. sound = engine.getSampleLibrary().load (path);
  507. engine.previewSample (sound != nullptr ? sound : makeStartupSample());
  508. };
  509. // the toolbar's last-tweaked read-out opens the parameter's own menu (FL's Tools › Last tweaked; round 162d)
  510. tweakReadout.onClick = [this] {
  511. makeLastTweakedMenu (0).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&tweakReadout));
  512. };
  513. // FL's "Edit events in piano roll" (REA round 146): the channel's own parameter selects its channel
  514. onEditEventsInPianoRoll = [this] (const AutomationTarget& t) {
  515. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  516. || t.kind == AutomationTargetKind::channelParam;
  517. if (onChannel && t.index >= 0 && t.index < (int) engine.getSong().channels.size())
  518. engine.setSelectedChannel (t.index);
  519. openPianoRoll();
  520. pianoRoll.showEventLane (t);
  521. };
  522. PluginWindows::onGesture = [this] (const juce::AudioPluginInstance& plugin, int param, bool starting) {
  523. if (const auto t = engine.targetOfPlugin (plugin, param))
  524. {
  525. if (starting)
  526. engine.noteTweaked (*t, true);
  527. else
  528. engine.tweakReleased (*t);
  529. }
  530. };
  531. engine.nameAutomation = [this] (const AutomationTarget& t) { return describeAutomationTarget (engine, t).toStdString(); };
  532. addAndMakeVisible (gridBox); // global grid (editors)
  533. engine.addChangeListener (this);
  534. setTypingPiano (typingPiano);
  535. refreshRecordOptionButtons();
  536. refreshToolbar();
  537. refreshPanelButtons();
  538. setToolbarLayout (toolbarLayout, false); // icon sizes and row height (loaded with the UI options)
  539. if (persistent && toolbarLayout.uiScale != 100)
  540. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  541. setControlHints();
  542. fittedChannelCount = (int) engine.getSong().channels.size();
  543. hintBar.setHint ({ idleHint(), {}, false, false });
  544. setWantsKeyboardFocus (true);
  545. installDialogTextFocus(); // dialogs open with their text field focused (round 165q)
  546. setSize (1180, 642);
  547. startTimerHz (30);
  548. uiTraceMonitor.start ([this, last = std::make_shared<RtStats::Snapshot>()] {
  549. // the audio side of the second (the watchdog thread: atomics only)
  550. const auto rt = engine.getRtStats().snapshot();
  551. const auto calls = rt.callbacks - last->callbacks;
  552. juce::String text;
  553. text << "audio: callbacks " << juce::String ((juce::int64) calls) << ", over deadline " << juce::String ((juce::int64) (rt.overBudget - last->overBudget))
  554. << ", late " << juce::String ((juce::int64) (rt.lateCalls - last->lateCalls)) << ", max load since start " << juce::String (rt.maxLoad * 100.0, 0)
  555. << "%, cpu " << juce::String (engine.getDeviceManager().getCpuUsage() * 100.0, 1) << "%";
  556. *last = rt;
  557. return text;
  558. });
  559. // new or updated plugins since the last run: an incremental scan in the background (unchanged files are
  560. // skipped), a few seconds after start so it doesn't compete with loading; the first run asks in the wizard
  561. if (persistent && setupWizardDone() && backgroundScanAtStart() && platform::testMode())
  562. platform::testModeLog ("background plugin scan at start");
  563. else if (persistent && setupWizardDone() && backgroundScanAtStart())
  564. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  565. if (safe != nullptr)
  566. safe->engine.getPluginHost().startBackgroundScan();
  567. });
  568. // round 168t (the YouTube review, 168d #9: "How do we get back to the playlist? Where is the playlist?"): the first
  569. // three starts name the window buttons and their keys in the hint bar for a while
  570. if (persistent)
  571. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  572. if (safe != nullptr)
  573. safe->showWindowsTip();
  574. });
  575. // Online Sessions P2 (round 169b): live sessions
  576. live = std::make_unique<LiveSessionManager> (engine);
  577. liveui::attach (*live);
  578. live->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  579. if (safe != nullptr)
  580. {
  581. safe->repaint (safe->titleArea);
  582. safe->menuItemsChanged();
  583. }
  584. };
  585. live->onJoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  586. if (safe == nullptr)
  587. return;
  588. const auto* host = song.session.find (session::hostTag);
  589. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  590. safe->startNewProject (std::move (song), {});
  591. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  592. safe->updateTitle();
  593. };
  594. // round 169j: the host's LYNX SHARE restarted during a session: its journal's song becomes the open project again
  595. live->onResumed = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  596. if (safe == nullptr)
  597. return;
  598. const auto journal = LiveSessionManager::readJournal (LiveSessionManager::defaultJournal());
  599. safe->startNewProject (std::move (song), {});
  600. if (journal && journal->projectFile.existsAsFile())
  601. {
  602. safe->currentFile = journal->projectFile;
  603. safe->projectName = journal->projectFile.getFileNameWithoutExtension();
  604. }
  605. safe->updateTitle();
  606. };
  607. engine.onSessionUndoSkipped = [] (const juce::StringArray& skipped) {
  608. ui::postHint ({ tr ("Undo left alone what someone else changed since: {0}", { skipped.joinIntoString (", ") }), {} }, 4000);
  609. };
  610. juce::Timer::callAfterDelay (1500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  611. if (safe != nullptr)
  612. safe->startLiveFromCommandLine();
  613. });
  614. // the keys a secondary window (tool, plugin, channel window) leaves unused run the global shortcuts, as in FL
  615. setSecondaryWindowKeyHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  616. return safe != nullptr && safe->keyFromSecondaryWindow (key);
  617. });
  618. }
  619. MainComponent::~MainComponent()
  620. {
  621. engine.onSessionUndoSkipped = nullptr;
  622. liveui::closeChat();
  623. live.reset(); // (a session still on ends: the others are told)
  624. setSecondaryWindowKeyHandler (nullptr);
  625. cancelProjectLoad(); // an open in progress uses the engine from its thread
  626. if (sessionLock != nullptr) // a clean exit: no "LYNX did not close properly" next time
  627. sessionMarker.deleteFile();
  628. mixerinput::openAudioSettings = nullptr;
  629. openMixerInsertHandler() = nullptr;
  630. PatcherWindows::onBrowsePluginDatabase = nullptr;
  631. EditorGlobals::get().onOptionsChanged = nullptr;
  632. PianoRollComponent::shortcutText = nullptr;
  633. saveUiSettings();
  634. workspace.saveState();
  635. ui::uninstallSliderContract();
  636. ui::onTweak = nullptr;
  637. themeui::previewStartupSound = nullptr;
  638. onEditEventsInPianoRoll = nullptr;
  639. PluginWindows::onGesture = nullptr;
  640. removeDialogTextFocus();
  641. engine.nameAutomation = nullptr;
  642. PluginWindows::closeAll(); // plugin UIs before the engine
  643. ParametricEqWindows::closeAll();
  644. closeAutomationEditors();
  645. closeChannelSettings();
  646. closeAllToolWindows(); // note tools, history, quick-add (they edit the song)
  647. engine.removeChangeListener (this);
  648. stopTimer();
  649. }
  650. void MainComponent::paint (juce::Graphics& g)
  651. {
  652. const uitrace::Scope trace ("MainComponent paint", true, g.getClipBounds());
  653. using namespace theme;
  654. g.fillAll (colour::bg1);
  655. // the toolbar: one band, its panels separated by hairlines
  656. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  657. g.setColour (colour::bg3);
  658. g.fillRect (bar);
  659. g.setColour (colour::border);
  660. g.fillRect (bar.withHeight (1).withY (bar.getBottom() - 1));
  661. g.setColour (colour::border.brighter (0.08f));
  662. if (toolbarLayout.separators) // (the toolbar menu's "Separators")
  663. for (auto x : dividers)
  664. g.fillRect (x, bar.getY() + 12, 1, bar.getHeight() - 24);
  665. // play, stop and record share one quiet well
  666. if (! transportArea.isEmpty())
  667. {
  668. g.setColour (colour::bg2);
  669. g.fillRoundedRectangle (transportArea.toFloat(), radius::lg);
  670. g.setColour (colour::border);
  671. g.drawRoundedRectangle (transportArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  672. }
  673. // the hint bar sits in an inset well under the menu
  674. if (! hintBar.getBounds().isEmpty())
  675. {
  676. g.setColour (colour::bg1);
  677. g.fillRoundedRectangle (hintBar.getBounds().toFloat(), radius::md);
  678. }
  679. // the project name, beside the menus (FL's title/hint panel: the title above the hint bar)
  680. if (! titleArea.isEmpty())
  681. {
  682. // the people of a live session first (round 169b), the project's name after them
  683. const auto people = live != nullptr ? liveui::paintPresence (g, titleArea, *live) : 0;
  684. const auto name = projectName.isNotEmpty() ? projectName : tr ("Untitled");
  685. g.setFont (font (type::small, true));
  686. g.setColour (colour::textSecondary);
  687. if (const auto rest = titleArea.withTrimmedLeft (people > 0 ? people + 10 : 0); rest.getWidth() >= 50)
  688. g.drawFittedText ((engine.isModified() ? juce::String ("* ") : juce::String()) + name, rest, juce::Justification::centredRight, 1, 0.8f);
  689. }
  690. // captions that name the snap and pattern selectors
  691. g.setFont (font (type::caption - 1.0f, true));
  692. g.setColour (colour::textDisabled);
  693. if (! snapLabelArea.isEmpty())
  694. g.drawText (tr ("SNAP"), snapLabelArea, juce::Justification::centredLeft, true);
  695. if (! patternLabelArea.isEmpty())
  696. g.drawText (tr ("PATTERN"), patternLabelArea, juce::Justification::centredLeft, true);
  697. }
  698. void MainComponent::resized()
  699. {
  700. using toolbarlayout::Group;
  701. dividers.clear();
  702. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  703. auto toolbar = bar.reduced (8, 3);
  704. const auto row1 = toolbar.getY(), row2 = toolbar.getY() + rowHeight + 2, h = rowHeight;
  705. const auto big = h + 6; // transport buttons: one slim row, centred on both
  706. const auto bigWidth = h + 4;
  707. constexpr int gap = 17; // a divider and the space around it
  708. const auto grow = h - toolbarlayout::rowHeight (toolbarlayout::IconSize::medium); // wider panels for bigger rows
  709. // panel widths
  710. auto& lf = getLookAndFeel();
  711. auto measureMenu = [&] {
  712. int w = 0;
  713. for (const auto& name : getMenuBarNames())
  714. w += lf.getMenuBarItemWidth (menuBar, 0, name);
  715. return w;
  716. };
  717. menuBar.getProperties().set ("lynxTightMenuBar", false);
  718. int menuWidth = measureMenu();
  719. if (menuWidth > 390) // translated menu titles (German, Russian...): English stays as it was
  720. {
  721. menuBar.getProperties().set ("lynxTightMenuBar", true);
  722. menuWidth = measureMenu();
  723. }
  724. const auto modeWidth = juce::jmax (patternModeButton.getIdealWidth (h - 2), songModeButton.getIdealWidth (h - 2));
  725. const int tempoWidth = 90 + grow, timeWidth = 110 + grow, captionWidth = 50, gridWidth = 148;
  726. std::array<int, toolbarlayout::groupCount> widths {};
  727. widths[(std::size_t) Group::transport] = modeWidth + 8 + 3 * (bigWidth + 4) + 4 + tempoWidth + 6 + timeWidth;
  728. widths[(std::size_t) Group::master] = 92;
  729. widths[(std::size_t) Group::record] = 3 * h + 4;
  730. widths[(std::size_t) Group::snap] = captionWidth + gridWidth;
  731. widths[(std::size_t) Group::windows] = 3 * h + 4;
  732. widths[(std::size_t) Group::file] = 3 * h + 4;
  733. widths[(std::size_t) Group::meters] = 118;
  734. widths[(std::size_t) Group::output] = 116 + grow * 2;
  735. const auto room = toolbar.getWidth();
  736. const auto minHint = juce::jmax (menuWidth + 8, 320), maxHint = 620; // room for most hints on two lines
  737. auto visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  738. if (! toolbarLayout.visible) // Ctrl+F11: only the menu and the hint bar, on one row
  739. visible.fill (false);
  740. panelBounds = {};
  741. int used = 0;
  742. for (int i = 0; i < toolbarlayout::groupCount; ++i)
  743. used += visible[(std::size_t) i] ? widths[(std::size_t) i] + gap : 0;
  744. const auto hintWidth = juce::jlimit (juce::jmin (minHint, juce::jmax (160, room - used)), maxHint, room - used);
  745. // the spare room goes before the first of the meters / output in the toolbar order (they sit on the right)
  746. auto spare = juce::jmax (0, room - used - hintWidth);
  747. auto take = [&toolbar] (int width) { return toolbar.removeFromLeft (juce::jmin (width, toolbar.getWidth())); };
  748. auto divide = [&] {
  749. take (8);
  750. dividers.push_back (toolbar.getX());
  751. take (9);
  752. };
  753. auto hide = [] (std::initializer_list<juce::Component*> components) {
  754. for (auto* c : components)
  755. {
  756. c->setVisible (false);
  757. c->setBounds ({});
  758. }
  759. };
  760. auto put = [] (juce::Component& c, juce::Rectangle<int> r) {
  761. c.setVisible (true);
  762. c.setBounds (r);
  763. };
  764. // a block of icon buttons, three per row on both rows
  765. auto grid = [&] (juce::Rectangle<int> panel, std::initializer_list<juce::Component*> buttons) {
  766. int i = 0;
  767. for (auto* b : buttons)
  768. {
  769. const auto x = panel.getX() + (i % 3) * (h + 2);
  770. put (*b, juce::Rectangle<int> (x, i < 3 ? row1 : row2, h, h));
  771. ++i;
  772. }
  773. };
  774. // 1. the menu (and the project name beside it) over the hint bar; always first
  775. if (! toolbarLayout.visible)
  776. {
  777. const auto row = toolbar.withHeight (h);
  778. const auto menu = row.withWidth (juce::jmin (menuWidth + 8, row.getWidth()));
  779. put (menuBar, menu);
  780. titleArea = {};
  781. placeHintBar (row.withTrimmedLeft (menu.getWidth() + 12).withWidth (juce::jmin (900, row.getWidth() - menu.getWidth() - 12)).reduced (0, 1));
  782. fixedToolbarArea = bar;
  783. }
  784. else
  785. {
  786. auto column = take (hintWidth);
  787. const auto menu = column.withY (row1).withHeight (h).removeFromLeft (juce::jmin (menuWidth + 8, column.getWidth()));
  788. put (menuBar, menu);
  789. titleArea = column.withY (row1).withHeight (h).withTrimmedLeft (menu.getWidth() + 12).withTrimmedRight (4);
  790. if (titleArea.getWidth() < 60)
  791. titleArea = {};
  792. placeHintBar (column.withY (row2).withHeight (h).reduced (0, 1));
  793. fixedToolbarArea = juce::Rectangle<int> (column.getX() - 4, 0, column.getWidth() + 8, toolbarHeight);
  794. }
  795. snapLabelArea = patternLabelArea = transportArea = {};
  796. for (const auto& entry : toolbarLayout.entries)
  797. {
  798. const auto group = entry.group;
  799. if (! visible[(std::size_t) group])
  800. {
  801. switch (group)
  802. {
  803. case Group::transport:
  804. hide ({ &patternModeButton, &songModeButton, &playButton, &stopButton, &recordButton, &tempoDisplay, &timeDisplay, &songPosition });
  805. break;
  806. case Group::master: hide ({ &masterVolume, &masterPitch }); break;
  807. case Group::record: hide ({ &metronomeButton, &typingPianoButton, &recordMenuButton, &countInButton, &waitInputButton, &midiLight }); break;
  808. case Group::snap: hide ({ &gridBox, &patternBox, &newPatternButton, &patternMenuButton }); break;
  809. case Group::windows:
  810. for (auto& b : panelButtons)
  811. hide ({ &b });
  812. hide ({ &pluginPickerButton });
  813. break;
  814. case Group::file: hide ({ &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton }); break;
  815. case Group::meters: hide ({ &perfMeter }); break;
  816. case Group::output: hide ({ &output }); break;
  817. case Group::count_: break;
  818. }
  819. continue;
  820. }
  821. if (toolbarlayout::rightAligned (group) && spare > 0)
  822. {
  823. take (spare);
  824. spare = 0;
  825. }
  826. divide();
  827. auto panel = take (widths[(std::size_t) group]);
  828. panelBounds[(std::size_t) group] = juce::Rectangle<int> (panel.getX() - 5, 0, panel.getWidth() + 10, toolbarHeight);
  829. switch (group)
  830. {
  831. case Group::transport: // Pattern/Song switch, play, stop, record, tempo, time display with the song position under it
  832. {
  833. auto mode = panel.removeFromLeft (modeWidth);
  834. put (patternModeButton, mode.withY (row1).withHeight (h).reduced (0, 1));
  835. put (songModeButton, mode.withY (row2).withHeight (h).reduced (0, 1));
  836. panel.removeFromLeft (8);
  837. const auto y = panel.getCentreY() - big / 2;
  838. transportArea = juce::Rectangle<int> (panel.getX(), y, 3 * bigWidth + 2 * 4, big);
  839. for (auto* b : { &playButton, &stopButton, &recordButton })
  840. {
  841. put (*b, juce::Rectangle<int> (panel.getX(), y, bigWidth, big).reduced (0, 3));
  842. panel.removeFromLeft (bigWidth + 4);
  843. }
  844. panel.removeFromLeft (4);
  845. const auto displays = juce::Rectangle<int> (panel.getX(), row1 + 3, panel.getWidth(), 2 * h - 6);
  846. const auto displayHeight = displays.getHeight() - 10;
  847. put (tempoDisplay, displays.withWidth (tempoWidth).withHeight (displayHeight));
  848. put (timeDisplay, displays.withTrimmedLeft (tempoWidth + 6).withWidth (timeWidth).withHeight (displayHeight));
  849. put (songPosition, displays.withTop (displays.getY() + displayHeight + 1).withWidth (tempoWidth + 6 + timeWidth));
  850. break;
  851. }
  852. case Group::master: // master volume over master pitch
  853. put (masterVolume, panel.withY (row1).withHeight (h).reduced (0, 1));
  854. put (masterPitch, panel.withY (row2).withHeight (h).reduced (0, 1));
  855. break;
  856. case Group::record: // metronome, count-in and wait for input over "what to record", typing piano and the MIDI light
  857. grid (panel, { &metronomeButton, &countInButton, &waitInputButton, &recordMenuButton, &typingPianoButton, &midiLight });
  858. break;
  859. case Group::snap: // global snap over the pattern selector, each with its name
  860. {
  861. auto first = juce::Rectangle<int> (panel.getX(), row1, panel.getWidth(), h);
  862. snapLabelArea = first.removeFromLeft (captionWidth);
  863. put (gridBox, first.reduced (0, 1));
  864. auto second = juce::Rectangle<int> (panel.getX(), row2, panel.getWidth(), h);
  865. patternLabelArea = second.removeFromLeft (captionWidth);
  866. put (patternMenuButton, second.removeFromRight (h));
  867. put (newPatternButton, second.removeFromRight (h));
  868. second.removeFromRight (2);
  869. put (patternBox, second.reduced (0, 1));
  870. break;
  871. }
  872. case Group::windows: // the windows and the plugin picker
  873. grid (panel, { &panelButtons[(std::size_t) Panel::playlist], &panelButtons[(std::size_t) Panel::channelRack],
  874. &panelButtons[(std::size_t) Panel::pianoRoll], &panelButtons[(std::size_t) Panel::mixer],
  875. &panelButtons[(std::size_t) Panel::browser], &pluginPickerButton });
  876. break;
  877. case Group::file: // new, open, save over export, undo, redo
  878. grid (panel, { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton });
  879. break;
  880. case Group::meters: put (perfMeter, panel.withY (row1).withHeight (2 * h + 2)); break;
  881. case Group::output: put (output, panel.withY (row1).withHeight (2 * h + 2)); break;
  882. case Group::count_: break;
  883. }
  884. }
  885. // the toolbar's edit mode: its overlay over the toolbar, and its tray between the toolbar and the windows
  886. const auto tray = toolbarEditor != nullptr ? toolbar::EditOverlay::trayHeight : 0;
  887. if (toolbarEditor != nullptr)
  888. {
  889. toolbarEditor->setBounds (0, 0, getWidth(), toolbarHeight + tray);
  890. toolbarEditor->setToolbarHeight (toolbarHeight);
  891. toolbarEditor->toFront (false);
  892. }
  893. auto below = getLocalBounds().withTrimmedTop (toolbarHeight + tray);
  894. if (updateBar.isVisible())
  895. updateBar.setBounds (below.removeFromTop (updater::UpdateBar::height));
  896. workspace.setBounds (below);
  897. if (danceStage != nullptr)
  898. {
  899. danceStage->setBounds (getLocalBounds());
  900. danceStage->toFront (false);
  901. }
  902. if (setupOverlay != nullptr)
  903. {
  904. setupOverlay->setBounds (getLocalBounds());
  905. setupOverlay->toFront (false);
  906. }
  907. }
  908. // --- toolbar layout ------------------------------------------------------------------------------
  909. void MainComponent::setToolbarLayout (const toolbarlayout::Layout& layout, bool save)
  910. {
  911. const auto scaleChanged = layout.uiScale != toolbarLayout.uiScale;
  912. toolbarLayout = layout;
  913. const auto size = toolbarLayout.iconSize;
  914. rowHeight = toolbarlayout::rowHeight (size);
  915. toolbarHeight = toolbarLayout.visible ? 2 * rowHeight + 8 : rowHeight + 6;
  916. const auto fraction = toolbarlayout::iconFraction (size), maxPx = toolbarlayout::iconMaxPx (size);
  917. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton,
  918. &patternMenuButton, &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton })
  919. b->setIconSizing (fraction, maxPx);
  920. for (auto& b : panelButtons)
  921. b.setIconSizing (fraction, maxPx);
  922. for (auto* b : { &playButton, &stopButton, &recordButton }) // solid transport glyphs, a little smaller than the line icons
  923. b->setIconSizing (0.5f, maxPx - 2.0f);
  924. ToolStrip::iconSize = size;
  925. pianoRoll.resized();
  926. playlist.resized();
  927. if (save && scaleChanged)
  928. {
  929. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  930. // the windows grow with the zoom: keep their title bars and close buttons on the screen (round 163)
  931. juce::Timer::callAfterDelay (200, [] { fitAllWindowsOnScreen(); });
  932. }
  933. resized();
  934. repaint();
  935. if (toolbarEditor != nullptr)
  936. toolbarEditor->layoutChanged();
  937. if (save)
  938. saveUiSettings();
  939. }
  940. juce::PopupMenu MainComponent::makeToolbarMenu()
  941. {
  942. using toolbarlayout::Group;
  943. juce::PopupMenu menu;
  944. // FL's toolbar menu (Edit, Separators, Hide, Presets), then LYNX's direct switches per panel
  945. menu.addSectionHeader (tr ("Toolbar"));
  946. menu.addItem (tr ("Edit toolbar (drag panels to move, add or remove them)"), true, toolbarEditor != nullptr,
  947. [this] { setToolbarEditing (toolbarEditor == nullptr); });
  948. menu.addItem (tr ("Separators"), true, toolbarLayout.separators, [this] {
  949. auto layout = toolbarLayout;
  950. layout.separators = ! layout.separators;
  951. setToolbarLayout (layout);
  952. });
  953. menu.addItem (tr ("Hide the toolbar panels") + shortcutText ("view.toolbar"), true, ! toolbarLayout.visible, [this] {
  954. auto layout = toolbarLayout;
  955. layout.visible = ! layout.visible;
  956. setToolbarLayout (layout);
  957. });
  958. juce::PopupMenu presets;
  959. const auto current = toolbarlayout::matchingPreset (toolbarLayout);
  960. for (int p = 0; p < toolbarlayout::presetCount; ++p)
  961. presets.addItem (tr (toolbarlayout::presetName ((toolbarlayout::Preset) p)), true, current == p, [this, p] {
  962. auto layout = toolbarlayout::applyPreset (toolbarLayout, (toolbarlayout::Preset) p);
  963. layout.visible = true;
  964. setToolbarLayout (layout);
  965. });
  966. menu.addSubMenu (tr ("Presets"), presets);
  967. menu.addSectionHeader (tr ("Panels"));
  968. for (const auto& entry : toolbarLayout.entries)
  969. {
  970. const auto group = entry.group;
  971. menu.addItem (tr (toolbarlayout::groupName (group)), true, entry.shown, [this, group] {
  972. auto layout = toolbarLayout;
  973. layout.setShown (group, ! layout.isShown (group));
  974. layout.visible = true;
  975. setToolbarLayout (layout);
  976. });
  977. }
  978. menu.addSeparator();
  979. juce::PopupMenu sizes;
  980. const char* sizeNames[] = { TR_NOOP ("Small icons"), TR_NOOP ("Medium icons"), TR_NOOP ("Large icons") };
  981. for (int i = 0; i < 3; ++i)
  982. sizes.addItem (tr (sizeNames[i]), true, (int) toolbarLayout.iconSize == i, [this, i] {
  983. auto layout = toolbarLayout;
  984. layout.iconSize = (toolbarlayout::IconSize) i;
  985. setToolbarLayout (layout);
  986. });
  987. menu.addSubMenu (tr ("Icon size"), sizes);
  988. juce::PopupMenu scales;
  989. for (auto percent : toolbarlayout::uiScales)
  990. scales.addItem (juce::String (percent) + "%", true, toolbarLayout.uiScale == percent, [this, percent] {
  991. auto layout = toolbarLayout;
  992. layout.uiScale = percent;
  993. setToolbarLayout (layout);
  994. });
  995. menu.addSubMenu (tr ("UI scale"), scales);
  996. menu.addSeparator();
  997. menu.addItem (tr ("Customize toolbar..."), [this] { showCustomizeToolbar(); });
  998. menu.addItem (tr ("Reset toolbar to default"), ! toolbarLayout.isDefault(), false, [this] {
  999. setToolbarLayout (toolbarlayout::Layout::makeDefault());
  1000. });
  1001. return menu;
  1002. }
  1003. void MainComponent::setToolbarEditing (bool editing)
  1004. {
  1005. if (editing == (toolbarEditor != nullptr))
  1006. return;
  1007. if (! editing)
  1008. {
  1009. removeChildComponent (toolbarEditor.get());
  1010. toolbarEditor.reset();
  1011. resized();
  1012. repaint();
  1013. return;
  1014. }
  1015. if (! toolbarLayout.visible) // editing shows the panels
  1016. {
  1017. auto layout = toolbarLayout;
  1018. layout.visible = true;
  1019. setToolbarLayout (layout);
  1020. }
  1021. toolbar::EditOverlay::Host host;
  1022. host.layout = [this] { return toolbarLayout; };
  1023. host.setLayout = [this] (const toolbarlayout::Layout& layout) { setToolbarLayout (layout); };
  1024. host.panels = [this] { return panelBounds; };
  1025. host.fixedArea = [this] { return fixedToolbarArea; };
  1026. host.snapshot = [this] (juce::Rectangle<int> area) {
  1027. // the panel as it looks, without the edit overlay on it
  1028. if (toolbarEditor != nullptr)
  1029. toolbarEditor->setVisible (false);
  1030. auto image = createComponentSnapshot (area, true);
  1031. if (toolbarEditor != nullptr)
  1032. toolbarEditor->setVisible (true);
  1033. return image;
  1034. };
  1035. host.done = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  1036. // after the click that asked for it
  1037. juce::MessageManager::callAsync ([safe] {
  1038. if (safe != nullptr)
  1039. safe->setToolbarEditing (false);
  1040. });
  1041. };
  1042. toolbarEditor = std::make_unique<toolbar::EditOverlay> (std::move (host), toolbarHeight);
  1043. addAndMakeVisible (*toolbarEditor);
  1044. resized();
  1045. repaint();
  1046. if (isShowing())
  1047. toolbarEditor->grabKeyboardFocus();
  1048. }
  1049. void MainComponent::flUndo()
  1050. {
  1051. if (alternateUndo)
  1052. undoRedo (false);
  1053. else
  1054. undoRedo (engine.canRedo()); // something undone: Ctrl+Z redoes the next step (FL: "undo/redo on the same shortcut")
  1055. }
  1056. void MainComponent::undoRedo (bool redo)
  1057. {
  1058. // FL says in the hint bar what was undone and the undo level ("Undone: ... Level 2/3")
  1059. if (redo ? ! engine.canRedo() : ! engine.canUndo())
  1060. return;
  1061. const auto label = engine.getHistoryLabel (engine.getHistoryPosition() + (redo ? 1 : 0));
  1062. if (redo)
  1063. engine.redo();
  1064. else
  1065. engine.undo();
  1066. ui::Hint h;
  1067. h.text = (redo ? tr ("Redone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) })
  1068. : tr ("Undone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) }));
  1069. h.value = tr ("Level {0}/{1}", { juce::String (engine.getHistoryPosition() + 1), juce::String (engine.getHistorySize()) });
  1070. ui::postHint (h, 2500);
  1071. }
  1072. ui::Hint MainComponent::hintAt (juce::Point<int> p)
  1073. {
  1074. ui::Hint h;
  1075. if (p.y < toolbarHeight)
  1076. {
  1077. h.text = tr ("Toolbar: [RMB] toolbar menu (edit the panels: move, add, remove; presets; hide with Ctrl+F11)");
  1078. h.hasMenu = true;
  1079. }
  1080. return h;
  1081. }
  1082. void MainComponent::showToolbarMenu()
  1083. {
  1084. makeToolbarMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1085. }
  1086. void MainComponent::showCustomizeToolbar()
  1087. {
  1088. auto panel = std::make_unique<toolbar::CustomizePanel> (toolbarLayout);
  1089. panel->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] (const toolbarlayout::Layout& layout) {
  1090. if (safe != nullptr)
  1091. safe->setToolbarLayout (layout);
  1092. };
  1093. juce::DialogWindow::LaunchOptions options;
  1094. options.content.setOwned (fitContentToScreen (std::move (panel)).release());
  1095. options.dialogTitle = tr ("Customize toolbar");
  1096. options.dialogBackgroundColour = theme::colour::bg2;
  1097. options.useNativeTitleBar = true;
  1098. options.resizable = false;
  1099. options.escapeKeyTriggersCloseButton = true;
  1100. if (auto* dialog = options.launchAsync())
  1101. keepAboveMainWindow (*dialog);
  1102. }
  1103. void MainComponent::mouseDown (const juce::MouseEvent& e)
  1104. {
  1105. // a right-click on the toolbar's background (between the panels): show / hide groups, icon size, customize
  1106. if (e.mods.isPopupMenu() && e.y < toolbarHeight)
  1107. showToolbarMenu();
  1108. }
  1109. juce::Rectangle<int> MainComponent::getToolStripAreaForSnapshot (bool playlistStrip)
  1110. {
  1111. auto& editor = playlistStrip ? (juce::Component&) playlist : (juce::Component&) pianoRoll;
  1112. if (! editor.isVisible() || editor.getParentComponent() == nullptr || ! isParentOf (&editor))
  1113. return {};
  1114. const auto area = getLocalArea (&editor, editor.getLocalBounds());
  1115. return area.withHeight (40).withWidth (juce::jmin (area.getWidth(), 900)).getIntersection (getLocalBounds());
  1116. }
  1117. // --- keys --------------------------------------------------------------------------------------
  1118. keys::Context MainComponent::focusContext() const
  1119. {
  1120. switch (workspace.getFocused())
  1121. {
  1122. case Panel::playlist: return keys::Context::playlist;
  1123. case Panel::channelRack: return keys::Context::channelRack;
  1124. case Panel::pianoRoll: return keys::Context::pianoRoll;
  1125. case Panel::mixer: return keys::Context::mixer;
  1126. case Panel::browser: return keys::Context::browser;
  1127. }
  1128. return keys::Context::global;
  1129. }
  1130. void MainComponent::dragOperationStarted (const juce::DragAndDropTarget::SourceDetails&)
  1131. {
  1132. // a drop on a window above this one (the Sampler's waveform, a plugin...) lands there, not on the panel under it
  1133. matchWindowOrderToScreen();
  1134. }
  1135. bool MainComponent::keyPressed (const juce::KeyPress& key)
  1136. {
  1137. const auto chord = chordFromKeyPress (key);
  1138. // 1. the typing piano (its keys win over plain-letter shortcuts while it is on)
  1139. if (keys::KeyMap::playsNote (chord, typingPiano))
  1140. {
  1141. const auto note = keys::typingPianoNote (chord.key, typingOctave, typingRoot);
  1142. if (! heldKeys.hasTag (key.getKeyCode())) // key repeat: the note is already sounding
  1143. for (auto c : engine.getSelectedChannels())
  1144. heldKeys.press (c, note, 0.8f, key.getKeyCode());
  1145. return true;
  1146. }
  1147. // 2. a key the user gave an action himself (Options › Shortcuts) wins over the panels' built-in keys
  1148. // (issue #12: Metronome on 'C' did nothing while the Playlist, whose Knife is 'C', had the focus)
  1149. if (const auto own = keyMap.findUserBound (chord, focusContext(), typingPiano); ! own.empty() && runAction (own))
  1150. return true;
  1151. // 3. the focused panel's own keys
  1152. const auto focused = workspace.getFocused();
  1153. const auto panelShown = workspace.isPanelVisible (focused);
  1154. if (panelShown && focused == Panel::pianoRoll && pianoRoll.handleKey (key))
  1155. return true;
  1156. if (panelShown && focused == Panel::playlist && playlist.handleKey (key))
  1157. return true;
  1158. // 4. the key map
  1159. const auto action = keyMap.find (chord, focusContext(), typingPiano);
  1160. return ! action.empty() && runAction (action);
  1161. }
  1162. bool MainComponent::keyFromSecondaryWindow (const juce::KeyPress& key)
  1163. {
  1164. // (round 165q / issue #12) a text field keeps its typing keys; the rest runs the global actions
  1165. const auto typingIntoText = dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) != nullptr;
  1166. const auto action = keyMap.findFromSecondaryWindow (chordFromKeyPress (key), typingIntoText, typingPiano);
  1167. return ! action.empty() && runAction (action);
  1168. }
  1169. bool MainComponent::runAction (const std::string& id)
  1170. {
  1171. auto is = [&id] (const char* name) { return id == name; };
  1172. if (id == "rack.follow")
  1173. {
  1174. auto& g = EditorGlobals::get();
  1175. g.setFollowingView (EditorGlobals::FollowView::channelRack, ! g.isFollowingView (EditorGlobals::FollowView::channelRack));
  1176. rackFollowButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  1177. return true;
  1178. }
  1179. if (id.rfind ("pianoRoll.", 0) == 0 && pianoRoll.runKeyAction (id)) return true; // tools, slide, channel keys
  1180. if (id.rfind ("playlist.tool.", 0) == 0 && playlist.runKeyAction (id)) return true;
  1181. if (is ("transport.playStop")) playStop();
  1182. else if (is ("transport.pause")) playPause();
  1183. else if (is ("transport.playFromStart")) playFromStart();
  1184. else if (is ("transport.toggleMode")) toggleMode();
  1185. else if (is ("transport.nextMarker")) engine.jumpToNextMarker (true);
  1186. else if (is ("transport.previousMarker")) engine.jumpToNextMarker (false);
  1187. else if (is ("view.typingPiano")) toggleTypingPiano();
  1188. else if (is ("view.toolbar"))
  1189. {
  1190. auto layout = toolbarLayout;
  1191. layout.visible = ! layout.visible;
  1192. setToolbarLayout (layout);
  1193. }
  1194. else if (is ("panel.playlist")) togglePanel (Panel::playlist);
  1195. else if (is ("panel.channelRack")) togglePanel (Panel::channelRack);
  1196. else if (is ("panel.pianoRoll"))
  1197. {
  1198. togglePanel (Panel::pianoRoll);
  1199. if (workspace.isPanelVisible (Panel::pianoRoll))
  1200. pianoRoll.scrollToNotes();
  1201. }
  1202. else if (is ("panel.browser")) togglePanel (Panel::browser);
  1203. else if (is ("panel.mixer")) togglePanel (Panel::mixer);
  1204. else if (is ("panel.maximisePlaylist"))
  1205. {
  1206. workspace.toggleMaximised (Panel::playlist);
  1207. refreshPanelButtons();
  1208. }
  1209. else if (is ("pattern.next")) selectPattern (stepPattern (engine.getSong(), 1));
  1210. else if (is ("pattern.previous")) selectPattern (stepPattern (engine.getSong(), -1));
  1211. else if (is ("pattern.nextEmpty")) nextEmptyPattern();
  1212. else if (is ("pattern.firstEmpty")) { engine.editSong ([] (Song& s) { gotoFirstEmptyPattern (s); }); showRenamePattern (engine.getSong().currentPattern); }
  1213. else if (is ("pattern.nextEmptyNoName")) engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  1214. else if (is ("pattern.delete")) deleteCurrentPattern();
  1215. else if (is ("pattern.rename")) showRenamePattern (engine.getSong().currentPattern);
  1216. else if (is ("pattern.insert")) insertPatternHere();
  1217. else if (is ("pattern.clone")) clonePatternNow();
  1218. else if (is ("pattern.moveUp")) movePatternNow (-1);
  1219. else if (is ("pattern.moveDown")) movePatternNow (1);
  1220. else if (id.rfind ("pattern.select", 0) == 0) selectPattern (std::stoi (id.substr (14)) - 1);
  1221. else if (is ("panel.quickAdd"))
  1222. {
  1223. // FL's F8 opens the plugin picker or closes it (FLEngine 0xebf510, round 167o)
  1224. if (auto* open = findToolWindow ("quickadd"))
  1225. closeToolWindowOf (*open->getContentComponent());
  1226. else
  1227. showQuickAdd();
  1228. }
  1229. else if (is ("edit.history")) showHistory();
  1230. else if (is ("browser.search"))
  1231. {
  1232. showPanel (Panel::browser);
  1233. browser.focusSearch();
  1234. }
  1235. else if (is ("transport.record")) toggleRecording();
  1236. else if (is ("record.quickAudio")) quickRecordAudio();
  1237. else if (is ("transport.metronome"))
  1238. {
  1239. engine.getTransport().metronome.store (! engine.getTransport().metronome.load());
  1240. refreshModeButton();
  1241. }
  1242. else if (is ("record.countIn"))
  1243. {
  1244. auto o = engine.getRecordOptions();
  1245. o.countInBars = o.countInBars > 0 ? 0 : 1;
  1246. engine.setRecordOptions (o);
  1247. refreshRecordOptionButtons();
  1248. }
  1249. else if (is ("record.waitForInput"))
  1250. {
  1251. auto o = engine.getRecordOptions();
  1252. o.waitForInput = ! o.waitForInput;
  1253. engine.setRecordOptions (o);
  1254. refreshRecordOptionButtons();
  1255. }
  1256. else if (is ("rack.graphEditor")) rack.toggleGraphLanes();
  1257. else if (is ("rack.pianoRollView"))
  1258. {
  1259. rack.setPianoRollView (! rack.isPianoRollView());
  1260. saveUiSettings();
  1261. }
  1262. else if (is ("view.audioEditor")) openAudioEditorForSelection();
  1263. else if (is ("view.tempoTapper")) openTempoTapper (engine);
  1264. else if (is ("view.sampleBrowser")) toggleSampleBrowser();
  1265. else if (is ("view.pluginDatabase"))
  1266. {
  1267. showPanel (Panel::browser);
  1268. browser.showPluginDatabase();
  1269. }
  1270. else if (is ("view.midiSettings") || is ("view.projectInfo"))
  1271. {
  1272. // FL's F10 / F11 (round 167o, issue #23): the same key closes Settings showing that page; on another page it
  1273. // switches in place
  1274. const auto page = is ("view.midiSettings") ? SettingsPage::midi : SettingsPage::info;
  1275. const auto shown = shownSettingsPage();
  1276. switch (keys::settingsKeyPress (shown >= 0, shown, (int) page))
  1277. {
  1278. case keys::SettingsKey::close: closeSettings(); break;
  1279. case keys::SettingsKey::switchPage: switchSettingsPage (page); break;
  1280. case keys::SettingsKey::open: openSettings ((int) page); break;
  1281. }
  1282. }
  1283. else if (is ("view.closeUnfocusedWindows")) closeUnfocusedWindows();
  1284. else if (is ("view.touchKeyboard")) toggleTouchKeyboard (engine);
  1285. else if (is ("view.closePluginWindows") || is ("view.closeWindows"))
  1286. {
  1287. PluginWindows::closeAll();
  1288. ParametricEqWindows::closeAll(); // every native effect / controller editor
  1289. if (is ("view.closeWindows")) // FL's F12: the editors and tool windows too (LYNX's docked panels stay)
  1290. {
  1291. closeAutomationEditors();
  1292. closeChannelSettings();
  1293. closeAllToolWindows();
  1294. closeHelp();
  1295. }
  1296. }
  1297. else if (is ("rack.groupSelected")) rack.groupSelected();
  1298. else if (is ("rack.rotateLeft")) rack.rotateSelected (-1);
  1299. else if (is ("rack.rotateRight")) rack.rotateSelected (1);
  1300. else if (is ("browser.previous")) browser.step (-1, false);
  1301. else if (is ("browser.next")) browser.step (1, false);
  1302. else if (is ("browser.swapPrevious")) browser.step (-1, true);
  1303. else if (is ("browser.swapNext")) browser.step (1, true);
  1304. else if (is ("browser.load")) browser.loadSelected();
  1305. else if (is ("browser.closeFolder")) browser.openFolder (false);
  1306. else if (is ("browser.openFolder")) browser.openFolder (true);
  1307. else if (is ("browser.rename"))
  1308. {
  1309. if (! browser.renameSelectedPlugin()) // not a plugin: F2's global action (rename the pattern)
  1310. showRenamePattern (engine.getSong().currentPattern);
  1311. }
  1312. else if (id.rfind ("pianoRoll.", 0) == 0) return pianoRoll.runAction (id);
  1313. else if (id.rfind ("playlist.", 0) == 0) return playlist.runAction (id);
  1314. else if (id.rfind ("mixer.", 0) == 0) return mixer.runAction (id);
  1315. else if (is ("file.new")) newProject();
  1316. else if (is ("file.open")) chooseFileToOpen();
  1317. else if (is ("file.save")) save (false);
  1318. else if (is ("file.saveAs")) save (true);
  1319. else if (is ("file.saveNewVersion")) saveNewVersion();
  1320. else if (is ("file.export")) exportAudio();
  1321. else if (is ("file.exportMaster")) showMasterDialog (engine, currentFile.getParentDirectory(), projectName);
  1322. else if (is ("file.exportMp3")) exportAudio (1);
  1323. else if (is ("file.exportMidi")) exportMidiFile();
  1324. else if (is ("tools.consolidateSelection")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), false);
  1325. else if (is ("tools.consolidateSelectionSongStart")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), true);
  1326. else if (is ("edit.undo")) flUndo();
  1327. else if (is ("edit.undoBackwards")) undoRedo (false);
  1328. else if (is ("edit.redo")) undoRedo (true);
  1329. else if (is ("help.shortcuts"))
  1330. {
  1331. if (helpWindow != nullptr) // F1 again closes the sheet (issue #23)
  1332. closeHelp();
  1333. else
  1334. showHelp();
  1335. }
  1336. else if (is ("rack.selectPrevious")) rack.selectRelative (-1, false);
  1337. else if (is ("rack.selectNext")) rack.selectRelative (1, false);
  1338. else if (is ("rack.extendUp")) rack.selectRelative (-1, true);
  1339. else if (is ("rack.extendDown")) rack.selectRelative (1, true);
  1340. else if (is ("rack.moveUp")) rack.moveSelected (-1);
  1341. else if (is ("rack.moveDown")) rack.moveSelected (1);
  1342. else if (is ("rack.selectAll")) rack.selectAll();
  1343. else if (is ("rack.clone")) rack.cloneSelected();
  1344. else if (is ("rack.deleteSelected")) rack.deleteSelected();
  1345. else if (is ("rack.sendToInserts")) rack.sendSelectedToInserts();
  1346. else if (id.rfind ("rack.mute", 0) == 0) rack.toggleMute (std::stoi (id.substr (9)) - 1);
  1347. else if (id.rfind ("rack.solo", 0) == 0) rack.solo (std::stoi (id.substr (9)) - 1);
  1348. else
  1349. return false;
  1350. return true;
  1351. }
  1352. bool MainComponent::keyStateChanged (bool)
  1353. {
  1354. // JUCE has no per-key "keyReleased"; check which held keys were released (each held note remembers its
  1355. // channel and key, so the selection changing meanwhile can't leave one sounding)
  1356. std::vector<int> released;
  1357. heldKeys.forEachTag ([&released] (int code) {
  1358. if (! juce::KeyPress::isKeyCurrentlyDown (code))
  1359. released.push_back (code);
  1360. });
  1361. for (auto code : released)
  1362. heldKeys.releaseTag (code);
  1363. return false;
  1364. }
  1365. juce::String MainComponent::shortcutText (const char* actionId) const
  1366. {
  1367. const auto& chords = keyMap.chordsFor (actionId);
  1368. return chords.empty() ? juce::String() : "\t" + juce::String (keys::displayString (chords.front()));
  1369. }
  1370. void MainComponent::toggleTypingPiano()
  1371. {
  1372. setTypingPiano (! typingPiano);
  1373. // say what changed in the hint bar (issue #34: people did not find the typing piano; Ctrl+T gave no feedback)
  1374. ui::Hint hint;
  1375. hint.text = typingPiano ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  1376. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)");
  1377. ui::postHint (hint, 2500);
  1378. }
  1379. void MainComponent::setTypingPiano (bool on)
  1380. {
  1381. typingPiano = on;
  1382. EditorGlobals::get().typingPiano = on; // the editors' single-letter tool keys only work while it is off
  1383. typingPianoButton.setToggleState (on, juce::dontSendNotification);
  1384. typingPianoButton.setTooltip ((on ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  1385. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)"))
  1386. + juce::String (" (") + juce::String (keys::displayString (keyMap.chordsFor ("view.typingPiano").empty() ? keys::Chord {}
  1387. : keyMap.chordsFor ("view.typingPiano").front()))
  1388. + ")");
  1389. // release anything still sounding from the keyboard
  1390. heldKeys.releaseAll();
  1391. }
  1392. void MainComponent::loadKeyMap()
  1393. {
  1394. keyMap.resetToDefaults();
  1395. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  1396. if (file.existsAsFile())
  1397. {
  1398. std::vector<std::string> errors;
  1399. if (! keyMap.loadJson (file.loadFileAsString().toStdString(), &errors))
  1400. juce::Logger::writeToLog ("keys.json is not a JSON object; using the default keys");
  1401. for (const auto& e : errors)
  1402. juce::Logger::writeToLog ("keys.json: " + juce::String (e));
  1403. }
  1404. auto keyOf = [this] (const std::string& id) {
  1405. const auto& chords = keyMap.chordsFor (id);
  1406. return chords.empty() ? juce::String() : juce::String (keys::displayString (chords.front()));
  1407. };
  1408. pianoRoll.refreshToolKeys (keyOf);
  1409. playlist.refreshToolKeys (keyOf);
  1410. }
  1411. // --- Browsers ------------------------------------------------------------------------------------
  1412. // The main Browser and the separate Sample browser window (round 163) act on the project the same way.
  1413. void MainComponent::connectBrowser (BrowserComponent& b)
  1414. {
  1415. b.onOpenProject = [this] (const juce::File& file) { confirmDiscard ([this, file] { openFile (file); }); };
  1416. b.onLoadIntoChannel = [this] (const juce::File& file) { return rack.loadSampleIntoSelected (file); };
  1417. b.onOpenMixerPreset = [this] (const juce::File& file) {
  1418. if (! mixerpresets::isMixerPreset (file))
  1419. return false;
  1420. if (! mixer.loadPresetOnSelection (file))
  1421. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Open mixer track state"),
  1422. tr ("This file is not a mixer track state LYNX SHARE can read."));
  1423. return true;
  1424. };
  1425. // the Browser's "Current project" items (REA_rodada115)
  1426. b.onOpenPattern = [this] (int pattern) {
  1427. selectPattern (pattern);
  1428. openPianoRoll();
  1429. };
  1430. b.onPatternMenu = [this] (int pattern) {
  1431. selectPattern (pattern);
  1432. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1433. };
  1434. b.onOpenChannel = [this] (int channel) {
  1435. engine.setSelectedChannel (channel);
  1436. rack.toggleEditor (channel, true);
  1437. };
  1438. b.onOpenEffect = [this] (int track, int slot) {
  1439. showPanel (Panel::mixer);
  1440. mixer.openSlotEditor (track, slot);
  1441. };
  1442. b.onShowInsert = [this] (int track) {
  1443. showPanel (Panel::mixer);
  1444. mixer.selectTrack (track);
  1445. };
  1446. b.onOpenAutomation = [this] (int automation) { openAutomationEditor (engine, automation); };
  1447. // the Browser's Plugin database (round 142): the same targets as the quick-add palette
  1448. b.onAddInstrument = [this] (ChannelDef c) {
  1449. if (PatcherWindows::takeInstrumentFromBrowser (c)) // a Patcher's Add plugin › Browse plugin database (round 162)
  1450. return;
  1451. rack.addChannel (std::move (c), true);
  1452. showPanel (Panel::channelRack);
  1453. };
  1454. b.onAddEffect = [this] (EffectSlot slot) {
  1455. if (PatcherWindows::takeEffectFromBrowser (slot))
  1456. return;
  1457. if (! mixer.addEffectToSelected (std::move (slot)))
  1458. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  1459. tr ("The selected insert has no free effect slot."));
  1460. else
  1461. showPanel (Panel::mixer);
  1462. };
  1463. b.onPreviewVolumeChanged = [this] { saveUiSettings(); };
  1464. b.onSendToPlaylist = [this] (const juce::File& file) {
  1465. playlist.addAudioClipAtPlayhead (file);
  1466. showPanel (Panel::playlist);
  1467. };
  1468. b.onToggleSampleBrowser = [this] { toggleSampleBrowser(); };
  1469. }
  1470. void MainComponent::toggleSampleBrowser()
  1471. {
  1472. if (auto* w = findToolWindow ("sampleBrowser"))
  1473. {
  1474. w->closeButtonPressed(); // (hidden, then deleted: remembered as closed)
  1475. return;
  1476. }
  1477. openSampleBrowser();
  1478. }
  1479. void MainComponent::openSampleBrowser()
  1480. {
  1481. auto* window = openToolWindow (BrowserComponent::makeSampleBrowserContent (engine, [this] (BrowserComponent& b) { connectBrowser (b); }),
  1482. tr ("Sample browser"), "sampleBrowser");
  1483. if (window == nullptr)
  1484. return;
  1485. window->setResizable (true, false);
  1486. window->setResizeLimits (240, 260, 4000, 4000);
  1487. const auto saved = BrowserComponent::sampleBrowserBounds();
  1488. const auto area = juce::Desktop::getInstance().getDisplays().getTotalBounds (true);
  1489. if (saved.getWidth() >= 240 && saved.getHeight() >= 260 && area.intersects (saved))
  1490. window->setBounds (saved);
  1491. else if (auto* top = getTopLevelComponent())
  1492. window->setBounds (top->getScreenBounds().getRight() - 360, top->getScreenY() + 80, 340, juce::jmax (400, top->getHeight() - 160));
  1493. }
  1494. // --- UI options ----------------------------------------------------------------------------------
  1495. juce::File MainComponent::uiSettingsFile() const
  1496. {
  1497. return PluginHost::settingsFolder().getChildFile ("ui-options.txt");
  1498. }
  1499. void MainComponent::loadUiSettings()
  1500. {
  1501. juce::StringArray lines;
  1502. lines.addLines (uiSettingsFile().loadFileAsString());
  1503. // the sound in FL's order (0.1.20) wins over the old key, wherever each line is
  1504. const auto flMetronomeSound = std::any_of (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("metronomeSoundFl"); });
  1505. for (const auto& line : lines)
  1506. {
  1507. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  1508. const auto on = line.fromFirstOccurrenceOf ("=", false, false).trim() == "1";
  1509. if (key == "typingPiano")
  1510. typingPiano = on;
  1511. else if (key == "typingOctave")
  1512. typingOctave = keys::typingpiano::clampOctave (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1513. else if (key == "typingRoot")
  1514. typingRoot = keys::typingpiano::clampRoot (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1515. else if (key == "keepEditorsOpen")
  1516. ChannelRackComponent::keepEditorsOpen = on;
  1517. else if (key == "selFirstChanPatChanges")
  1518. ChannelRackComponent::selectFirstChannelWithNotes = on;
  1519. else if (key == "alternateUndo")
  1520. alternateUndo = on;
  1521. else if (key == "waveSpectral") // ("waveColours", the old spectral-by-default key, is ignored)
  1522. ui::WaveformCache::spectral = on;
  1523. else if (key == "pluginStyle") // "Automatic" or a style forced on every plugin
  1524. {
  1525. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim();
  1526. skin::setForcedStyle (v.equalsIgnoreCase ("Automatic") || v.isEmpty() ? -1 : (int) skin::styleFromName (v));
  1527. }
  1528. else if (key == "pluginStyleOverrides")
  1529. skin::overridesFromString (line.fromFirstOccurrenceOf ("=", false, false).trim());
  1530. else if (key == "reducedEffects")
  1531. skin::setReducedEffects (on);
  1532. else if (key == "waveStereo")
  1533. ui::WaveformCache::stereo = on;
  1534. else if (key == "noteNames")
  1535. notenames::currentStyle.store (juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1536. else if (key == "noteFlats")
  1537. notenames::currentFlats.store (on);
  1538. else if (key == "rememberSeek")
  1539. EditorGlobals::get().rememberSeek = on;
  1540. else if (key == "createVariants")
  1541. EditorGlobals::get().createVariants = on;
  1542. else if (key == "prGridHighlights") // (round 168g: the Piano roll's View items)
  1543. PianoRollComponent::gridHighlights = on;
  1544. else if (key == "prShowChordName")
  1545. PianoRollComponent::showChordName = on;
  1546. else if (key == "stretchedClipsLoop")
  1547. setStretchedClipsLoop (on);
  1548. else if (key == "followPlaylist" || key == "followPianoRoll")
  1549. EditorGlobals::get().setFollowing (key == "followPianoRoll", on, false);
  1550. else if (key == "followChannelRack" || key == "followAudioEditor")
  1551. EditorGlobals::get().setFollowingView (key == "followChannelRack" ? EditorGlobals::FollowView::channelRack
  1552. : EditorGlobals::FollowView::audioEditor, on, false);
  1553. else if (key == "scopeMode")
  1554. toolbar::OutputMonitor::mode = juce::jlimit (0, toolbar::OutputMonitor::modeCount - 1,
  1555. line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1556. else if (key == "toolbarGroups")
  1557. toolbarLayout.orderFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1558. else if (key == "toolbarIcons")
  1559. toolbarLayout.iconSize = toolbarlayout::Layout::iconSizeFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1560. else if (key == "toolbarSeparators")
  1561. toolbarLayout.separators = on;
  1562. else if (key == "toolbarVisible")
  1563. toolbarLayout.visible = on;
  1564. else if (key == "menuDensity")
  1565. theme::menus::setCompact (line.fromFirstOccurrenceOf ("=", false, false).trim() != "comfortable");
  1566. else if (key == "uiScale")
  1567. toolbarLayout.uiScale = toolbarlayout::clampScale (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1568. else if (key == "editPatternsIn")
  1569. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1570. else if (key == "autosaveMinutes")
  1571. autosaveMinutes = prefs::clampAutosaveMinutes (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1572. else if (key == "askUnusedRecordings")
  1573. askUnusedRecordings = on;
  1574. else if (key == "autosaveKeep")
  1575. autosaveKeep = prefs::clampAutosaveKeep (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1576. else if (key == "metronomeSound" && ! flMetronomeSound) // (before 0.1.20: 0 LYNX click, 1..5 hi-hat..pulse)
  1577. engine.getTransport().metronomeSound.store (metronome::soundFromLegacy (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1578. else if (key == "metronomeSoundFl") // FL's order: 0 Hi-hat, 1 Tick, 2 Beep, 3 Cowbell, 4 Pulse
  1579. engine.getTransport().metronomeSound.store (metronome::clampSound (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1580. else if (key == "metronomeTrack")
  1581. engine.getTransport().metronomeTrack.store (juce::jlimit (0, maxMixerTracks - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1582. else if (key == "playTruncatedOnTransport")
  1583. engine.getTransport().playTruncatedOnTransport.store (on);
  1584. else if (key == "resetPluginsOnTransport")
  1585. engine.getTransport().resetPluginsOnTransport.store (on);
  1586. else if (key == "metronomeVolume")
  1587. engine.getTransport().metronomeVolume.store ((float) controls::clampUtilityVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue()));
  1588. else if (key == "previewVolume")
  1589. engine.setPreviewVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  1590. else if (key == "editorVolume")
  1591. engine.setEditorVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  1592. else if (key == "rackPianoRollView")
  1593. rack.setPianoRollView (on);
  1594. else if (key == "undoLevels")
  1595. engine.setUndoLevels (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1596. else if (key == "askWhatToRecord" || key == "recordNotes" || key == "recordAudio" || key == "recordStartsPlayback" || key == "disarmOnStop"
  1597. || key == "recordOffOnStop" || key == "unarmAfterRender" || key == "renderAutoClip")
  1598. {
  1599. auto o = engine.getRecordOptions();
  1600. (key == "askWhatToRecord" ? o.askWhatToRecord : key == "recordNotes" ? o.recordNotes : key == "recordAudio" ? o.recordAudio
  1601. : key == "disarmOnStop" ? o.disarmOnStop : key == "recordOffOnStop" ? o.recordOffOnStop : key == "unarmAfterRender" ? o.unarmAfterRender
  1602. : key == "renderAutoClip" ? o.autoCreateClip
  1603. : o.startsPlayback) = on;
  1604. engine.setRecordOptions (o);
  1605. }
  1606. else if (key == "recordAutomation" || key == "recordQuantiseAutomation" || key == "recordClips")
  1607. {
  1608. auto o = engine.getRecordOptions();
  1609. (key == "recordAutomation" ? o.recordAutomation : key == "recordClips" ? o.recordClips : o.quantiseAutomation) = on;
  1610. engine.setRecordOptions (o);
  1611. }
  1612. else if (key == "recordToStepSequencer" || key == "recordingMarkers" || key == "recordNoteEnd")
  1613. {
  1614. auto o = engine.getRecordOptions();
  1615. if (key == "recordNoteEnd")
  1616. o.noteEnd = (NoteEnd) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1617. else
  1618. (key == "recordToStepSequencer" ? o.toStepSequencer : o.recordingMarkers) = on;
  1619. engine.setRecordOptions (o);
  1620. }
  1621. else if (key == "recordPunchLoop" || key == "recordPreRoll" || key == "recordPostRoll")
  1622. {
  1623. auto o = engine.getRecordOptions();
  1624. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  1625. if (key == "recordPunchLoop")
  1626. o.punchLoopRegion = v != 0;
  1627. else
  1628. (key == "recordPreRoll" ? o.preRollBars : o.postRollBars) = juce::jlimit (0, 8, v);
  1629. engine.setRecordOptions (o);
  1630. }
  1631. else if (key == "recordQuantiseStarts")
  1632. {
  1633. recordQuantiseOn = on;
  1634. updateRecordQuantise();
  1635. }
  1636. else if (key == "newInserts" || key == "newMasterChain" || key == "newCleanMixer" || key == "playlistTracks" || key == "newAutoCrossfades")
  1637. newProjectDefaults().readKey (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1638. else if (key == "mixerUsedOnly")
  1639. MixerStrips::showUsedOnly = on;
  1640. else if (key == "mixerLayout") // FL's FXViewMode numbering (issue #52)
  1641. {
  1642. MixerStrips::layout = mixerlayout::parse (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1643. mixer.getStripsForSnapshot().updateSize();
  1644. }
  1645. else if (key == "quantizeSongJumps")
  1646. engine.quantizeSongJumps.store (juce::jlimit (0, 5, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1647. }
  1648. startup = StartupOptions::load();
  1649. browser.refreshPreviewVolume();
  1650. }
  1651. void MainComponent::saveUiSettings()
  1652. {
  1653. if (! persistent)
  1654. return;
  1655. uiSettingsFile().replaceWithText ("typingPiano=" + juce::String (typingPiano ? 1 : 0) + "\ntypingOctave=" + juce::String (typingOctave)
  1656. + "\ntypingRoot=" + juce::String (typingRoot) + "\nkeepEditorsOpen="
  1657. + juce::String (ChannelRackComponent::keepEditorsOpen ? 1 : 0)
  1658. + "\nselFirstChanPatChanges=" + juce::String (ChannelRackComponent::selectFirstChannelWithNotes ? 1 : 0)
  1659. + "\nalternateUndo=" + juce::String (alternateUndo ? 1 : 0)
  1660. + "\neditPatternsIn="
  1661. + juce::String (PlaylistComponent::editPatternsIn) + "\nsplash=" + juce::String (startup.splash ? 1 : 0)
  1662. + "\nstartupSound=" + juce::String (startup.sound ? 1 : 0)
  1663. + "\nwaveSpectral=" + juce::String (ui::WaveformCache::spectral ? 1 : 0)
  1664. + "\nwaveStereo=" + juce::String (ui::WaveformCache::stereo ? 1 : 0)
  1665. + "\nnoteNames=" + juce::String (notenames::currentStyle.load())
  1666. + "\nnoteFlats=" + juce::String (notenames::currentFlats.load() ? 1 : 0)
  1667. + "\nreducedEffects=" + juce::String (skin::reducedEffects() ? 1 : 0)
  1668. + "\npluginStyle=" + juce::String (skin::forcedStyle() < 0 ? "Automatic" : skin::styleName ((skin::Style) skin::forcedStyle()))
  1669. + "\npluginStyleOverrides=" + skin::overridesToString()
  1670. + "\nrememberSeek=" + juce::String (EditorGlobals::get().rememberSeek ? 1 : 0)
  1671. + "\ncreateVariants=" + juce::String (EditorGlobals::get().createVariants ? 1 : 0)
  1672. + "\nprGridHighlights=" + juce::String (PianoRollComponent::gridHighlights ? 1 : 0)
  1673. + "\nprShowChordName=" + juce::String (PianoRollComponent::showChordName ? 1 : 0)
  1674. + "\nstretchedClipsLoop=" + juce::String (stretchedClipsLoop() ? 1 : 0)
  1675. + "\nfollowPlaylist=" + juce::String (EditorGlobals::get().isFollowing (false) ? 1 : 0)
  1676. + "\nfollowPianoRoll=" + juce::String (EditorGlobals::get().isFollowing (true) ? 1 : 0)
  1677. + "\nfollowChannelRack=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack) ? 1 : 0)
  1678. + "\nfollowAudioEditor=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor) ? 1 : 0)
  1679. + "\nscopeMode=" + juce::String (toolbar::OutputMonitor::mode)
  1680. + "\ntoolbarGroups=" + juce::String (toolbarLayout.orderToString())
  1681. + "\ntoolbarIcons=" + toolbarlayout::Layout::iconSizeId (toolbarLayout.iconSize)
  1682. + "\nuiScale=" + juce::String (toolbarLayout.uiScale)
  1683. + "\nmenuDensity=" + juce::String (theme::menus::compact() ? "compact" : "comfortable")
  1684. + "\ntoolbarSeparators=" + juce::String (toolbarLayout.separators ? 1 : 0)
  1685. + "\ntoolbarVisible=" + juce::String (toolbarLayout.visible ? 1 : 0)
  1686. + "\nautosaveMinutes=" + juce::String (autosaveMinutes) + "\nautosaveKeep=" + juce::String (autosaveKeep)
  1687. + "\naskUnusedRecordings=" + juce::String (askUnusedRecordings ? 1 : 0)
  1688. + "\nundoLevels=" + juce::String (engine.getUndoLevels())
  1689. + "\nmetronomeVolume=" + juce::String (engine.getTransport().metronomeVolume.load(), 2)
  1690. + "\nmetronomeSoundFl=" + juce::String (metronome::clampSound (engine.getTransport().metronomeSound.load()))
  1691. + "\nmetronomeTrack=" + juce::String (engine.getTransport().metronomeTrack.load())
  1692. + "\nplayTruncatedOnTransport=" + juce::String (engine.getTransport().playTruncatedOnTransport.load() ? 1 : 0)
  1693. + "\nresetPluginsOnTransport=" + juce::String (engine.getTransport().resetPluginsOnTransport.load() ? 1 : 0)
  1694. + "\npreviewVolume=" + juce::String (engine.getPreviewVolume(), 2)
  1695. + "\neditorVolume=" + juce::String (engine.getEditorVolume(), 2)
  1696. + "\nrackPianoRollView=" + juce::String (rack.isPianoRollView() ? 1 : 0)
  1697. + "\naskWhatToRecord=" + juce::String (engine.getRecordOptions().askWhatToRecord ? 1 : 0)
  1698. + "\nrecordNotes=" + juce::String (engine.getRecordOptions().recordNotes ? 1 : 0)
  1699. + "\nrecordAudio=" + juce::String (engine.getRecordOptions().recordAudio ? 1 : 0)
  1700. + "\nrecordStartsPlayback=" + juce::String (engine.getRecordOptions().startsPlayback ? 1 : 0)
  1701. + "\ndisarmOnStop=" + juce::String (engine.getRecordOptions().disarmOnStop ? 1 : 0)
  1702. + "\nrecordOffOnStop=" + juce::String (engine.getRecordOptions().recordOffOnStop ? 1 : 0)
  1703. + "\nunarmAfterRender=" + juce::String (engine.getRecordOptions().unarmAfterRender ? 1 : 0)
  1704. + "\nrenderAutoClip=" + juce::String (engine.getRecordOptions().autoCreateClip ? 1 : 0)
  1705. + "\nrecordQuantiseStarts=" + juce::String (recordQuantiseOn ? 1 : 0)
  1706. + "\nrecordNoteEnd=" + juce::String ((int) engine.getRecordOptions().noteEnd)
  1707. + "\nrecordToStepSequencer=" + juce::String (engine.getRecordOptions().toStepSequencer ? 1 : 0)
  1708. + "\nrecordingMarkers=" + juce::String (engine.getRecordOptions().recordingMarkers ? 1 : 0)
  1709. + "\nrecordAutomation=" + juce::String (engine.getRecordOptions().recordAutomation ? 1 : 0)
  1710. + "\nrecordClips=" + juce::String (engine.getRecordOptions().recordClips ? 1 : 0)
  1711. + "\nrecordQuantiseAutomation=" + juce::String (engine.getRecordOptions().quantiseAutomation ? 1 : 0)
  1712. + "\nrecordPunchLoop=" + juce::String (engine.getRecordOptions().punchLoopRegion ? 1 : 0)
  1713. + "\nrecordPreRoll=" + juce::String (engine.getRecordOptions().preRollBars)
  1714. + "\nrecordPostRoll=" + juce::String (engine.getRecordOptions().postRollBars) + "\nmixerUsedOnly=" + juce::String (MixerStrips::showUsedOnly ? 1 : 0) + "\nmixerLayout=" + juce::String ((int) MixerStrips::layout)
  1715. + "\nquantizeSongJumps=" + juce::String (engine.quantizeSongJumps.load()) + "\n"
  1716. + juce::String (newProjectDefaults().toText()));
  1717. }
  1718. // --- transport -----------------------------------------------------------------------------------
  1719. void MainComponent::playStop()
  1720. {
  1721. auto& transport = engine.getTransport();
  1722. if (engine.isWaitingForInput() || engine.isCountingIn()) // pressed again: cancel
  1723. {
  1724. engine.stop();
  1725. return;
  1726. }
  1727. if (transport.playing.load())
  1728. {
  1729. engine.stop();
  1730. engine.seek (playStartTicks); // back to where playback started
  1731. }
  1732. else
  1733. {
  1734. playStartTicks = transport.positionTicks.load();
  1735. engine.startPlayback();
  1736. }
  1737. }
  1738. void MainComponent::playPause()
  1739. {
  1740. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn())
  1741. engine.stop();
  1742. else
  1743. {
  1744. playStartTicks = engine.getTransport().positionTicks.load();
  1745. engine.startPlayback();
  1746. }
  1747. }
  1748. void MainComponent::playFromStart()
  1749. {
  1750. // FL 2026's Shift+Space (measured in FL, issue #11): playing, recording, waiting or counting in -> stop at the start
  1751. // of the time selection (Song mode) or else of the song / pattern; stopped -> play from the current position, as
  1752. // Space does (a later Space goes back there).
  1753. const auto wasPlaying = engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn();
  1754. if (! wasPlaying)
  1755. {
  1756. playStop();
  1757. return;
  1758. }
  1759. engine.stop();
  1760. const auto& song = engine.getSong();
  1761. const auto target = transportedit::shiftSpaceStopTarget (song.mode == PlayMode::song, song.hasLoop(), song.loopStart);
  1762. if (target > 0)
  1763. engine.seek ((double) target);
  1764. else
  1765. engine.rewind();
  1766. playStartTicks = (double) target;
  1767. }
  1768. void MainComponent::stopAndRewind (bool toStart)
  1769. {
  1770. // Stop while nothing plays (the second press, or a double click) goes back to the very start even when
  1771. // "Remember seek time" sends the first Stop to the ruler mark (round 162, issue #9)
  1772. const auto alreadyStopped = toStart || ! (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn());
  1773. engine.stop();
  1774. // FL: the transport's Stop also ends a Browser sample preview (issue #11)
  1775. browser.stopPreview(); // (the engine's one preview voice: the Sample browser window's preview stops too)
  1776. const auto& globals = EditorGlobals::get();
  1777. const auto back = transportedit::stopTarget (alreadyStopped, globals.rememberSeek && engine.getSong().mode == PlayMode::song, globals.seekMark);
  1778. if (back > 0) // "Remember seek time": back to the position clicked on the Playlist ruler
  1779. engine.seek ((double) back);
  1780. else
  1781. engine.rewind();
  1782. playStartTicks = (double) back;
  1783. }
  1784. void MainComponent::showStopMenu()
  1785. {
  1786. auto& globals = EditorGlobals::get();
  1787. juce::PopupMenu menu;
  1788. menu.addSectionHeader (tr ("Stop"));
  1789. menu.addItem (tr ("Remember seek time: Stop goes back to the position clicked on the Playlist ruler"), true, globals.rememberSeek, [this] {
  1790. EditorGlobals::get().rememberSeek = ! EditorGlobals::get().rememberSeek;
  1791. saveUiSettings();
  1792. });
  1793. menu.addSeparator();
  1794. menu.addItem (tr ("All notes off (panic)") + "\t" + tr ("double-click"), [this] { engine.panic(); });
  1795. menu.addItem (tr ("Back to the start"), [this] { stopAndRewind (true); });
  1796. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&stopButton));
  1797. }
  1798. void MainComponent::toggleMode()
  1799. {
  1800. engine.editSong ([] (Song& s) { s.mode = s.mode == PlayMode::song ? PlayMode::pattern : PlayMode::song; }, false);
  1801. }
  1802. // --- panels --------------------------------------------------------------------------------------
  1803. void MainComponent::togglePanel (Panel panel)
  1804. {
  1805. workspace.toggle (panel);
  1806. refreshPanelButtons();
  1807. }
  1808. void MainComponent::fitChannelRack (bool width)
  1809. {
  1810. rack.updateSize();
  1811. const auto scrollbar = rackViewport.getScrollBarThickness();
  1812. // compact like FL's rack: at most two bars of steps are shown, longer patterns scroll sideways, so the
  1813. // rack does not cover the Playlist after a project with long patterns is opened
  1814. // and never past the desktop's right edge from where the rack is (the default layout keeps the Playlist's track
  1815. // names uncovered on a small desktop, round 167v)
  1816. const auto maxWidth = juce::jmin (juce::jmax (300, workspace.getWidth() - 16 - workspace.getPanelBounds (Panel::channelRack).getX() - scrollbar - 8), rack.widthForSteps (32));
  1817. const auto contentWidth = juce::jmin (rack.naturalWidth(), maxWidth); // the ghost steps only fill a wider rack
  1818. const auto needsHorizontal = rack.naturalWidth() > contentWidth;
  1819. workspace.fitPanelContent (Panel::channelRack, width ? contentWidth + scrollbar : 0, rack.getHeight() + (needsHorizontal ? scrollbar : 0));
  1820. fittedChannelCount = (int) engine.getSong().channels.size();
  1821. }
  1822. void MainComponent::showPanel (Panel panel)
  1823. {
  1824. workspace.show (panel);
  1825. refreshPanelButtons();
  1826. }
  1827. void MainComponent::showWindowsTip()
  1828. {
  1829. const auto counter = PluginHost::settingsFolder().getChildFile ("windows-tip.txt");
  1830. const auto shown = counter.existsAsFile() ? counter.loadFileAsString().trim().getIntValue() : 0;
  1831. if (shown >= 3)
  1832. return;
  1833. counter.replaceWithText (juce::String (shown + 1));
  1834. auto key = [this] (Panel p) {
  1835. const auto chords = keyMap.chordsFor (panelAction (p));
  1836. return chords.empty() ? juce::String() : "[" + juce::String (keys::toString (chords.front())) + "] ";
  1837. };
  1838. ui::Hint hint;
  1839. 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)",
  1840. { key (Panel::playlist), key (Panel::channelRack), key (Panel::pianoRoll), key (Panel::mixer), key (Panel::browser) });
  1841. ui::postHint (hint, 15000);
  1842. }
  1843. void MainComponent::refreshPanelButtons()
  1844. {
  1845. for (int i = 0; i < workspace::panelCount; ++i)
  1846. panelButtons[(std::size_t) i].setToggleState (workspace.isPanelVisible ((Panel) i), juce::dontSendNotification);
  1847. }
  1848. void MainComponent::openPianoRoll()
  1849. {
  1850. showPanel (Panel::pianoRoll);
  1851. pianoRoll.scrollToNotes();
  1852. }
  1853. void MainComponent::saveLayoutAs()
  1854. {
  1855. auto* window = new juce::AlertWindow (tr ("Save layout as"), tr ("Name of the layout:"), juce::MessageBoxIconType::NoIcon);
  1856. window->addTextEditor ("name", tr ("My layout"));
  1857. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1858. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1859. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  1860. const auto name = window->getTextEditorContents ("name").trim();
  1861. if (result == 1 && name.isNotEmpty())
  1862. workspace.saveLayoutAs (name);
  1863. }),
  1864. true);
  1865. keepAboveMainWindow (*window);
  1866. }
  1867. juce::PopupMenu MainComponent::layoutsMenu()
  1868. {
  1869. juce::PopupMenu menu;
  1870. auto files = Workspace::layoutsFolder().findChildFiles (juce::File::findFiles, false, "*.txt");
  1871. files.sort();
  1872. for (const auto& file : files)
  1873. menu.addItem (file.getFileNameWithoutExtension(), [this, file] {
  1874. workspace.loadLayout (file);
  1875. refreshPanelButtons();
  1876. });
  1877. if (files.isEmpty())
  1878. menu.addItem (tr ("(none saved yet)"), false, false, [] {});
  1879. menu.addSeparator();
  1880. menu.addItem (tr ("Open layouts folder"), [] {
  1881. Workspace::layoutsFolder().createDirectory();
  1882. Workspace::layoutsFolder().startAsProcess();
  1883. });
  1884. return menu;
  1885. }
  1886. void MainComponent::selectTabForSnapshot (int tab)
  1887. {
  1888. const Panel panels[] = { Panel::channelRack, Panel::pianoRoll, Panel::playlist, Panel::mixer };
  1889. const auto panel = panels[juce::jlimit (0, 3, tab)];
  1890. if (panel == Panel::pianoRoll)
  1891. {
  1892. const auto& song = engine.getSong();
  1893. std::vector<int> counts (song.channels.size(), 0);
  1894. for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
  1895. if (n.channel >= 0 && n.channel < (int) counts.size())
  1896. ++counts[(std::size_t) n.channel];
  1897. if (! counts.empty())
  1898. engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
  1899. }
  1900. // each view on its own: the panel maximized over the workspace
  1901. workspace.resetLayout();
  1902. workspace.show (panel);
  1903. workspace.toggleMaximised (panel);
  1904. refreshPanelButtons();
  1905. if (panel == Panel::pianoRoll)
  1906. pianoRoll.scrollToNotes();
  1907. if (panel == Panel::playlist)
  1908. playlist.resized(); // update the scrollbars for the loaded song
  1909. if (panel == Panel::mixer)
  1910. mixer.selectFirstTrackWithEffects();
  1911. }
  1912. void MainComponent::showDesktopForSnapshot (bool extraPanels)
  1913. {
  1914. workspace.resetLayout();
  1915. if (auto* stage = dynamic_cast<DanceStage*> (danceStage.get()))
  1916. stage->update(); // (the project's dancers now: no timer runs before the picture)
  1917. if (extraPanels)
  1918. {
  1919. workspace.show (Panel::mixer);
  1920. workspace.show (Panel::pianoRoll);
  1921. pianoRoll.scrollToNotes();
  1922. workspace.show (Panel::channelRack);
  1923. }
  1924. refreshPanelButtons();
  1925. }
  1926. // --- patterns ------------------------------------------------------------------------------------
  1927. void MainComponent::selectPattern (int index)
  1928. {
  1929. if (index >= 0 && index < (int) engine.getSong().patterns.size() && index != engine.getSong().currentPattern)
  1930. engine.editSong ([index] (Song& s) { s.currentPattern = index; }, false);
  1931. }
  1932. void MainComponent::nextEmptyPattern()
  1933. {
  1934. engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  1935. showRenamePattern (engine.getSong().currentPattern);
  1936. }
  1937. void MainComponent::deleteCurrentPattern()
  1938. {
  1939. // FL's Patterns › Delete (Ctrl+Shift+Del); the last pattern stays
  1940. if (engine.getSong().patterns.size() > 1)
  1941. engine.editSong ([] (Song& s) { s.removePattern (s.currentPattern); });
  1942. }
  1943. void MainComponent::insertPatternHere()
  1944. {
  1945. engine.editSong ([] (Song& s) { insertPattern (s, s.currentPattern, newPatternName (s)); });
  1946. }
  1947. // --- window menus ------------------------------------------------------------------------------
  1948. // Each window's own items, at the top of the menu in its title bar (FL keeps an editor's options in the
  1949. // small menu at the left of its title bar). Items run the key map's actions, so they show their keys.
  1950. void MainComponent::addPanelMenuItems (Panel panel, juce::PopupMenu& menu)
  1951. {
  1952. auto action = [this] (juce::PopupMenu& m, const char* id, const juce::String& text, bool enabled = true, bool ticked = false) {
  1953. m.addItem (text + shortcutText (id), enabled, ticked, [this, id] { runAction (id); });
  1954. };
  1955. auto zoomMenu = [&action] (const juce::String& prefix) {
  1956. juce::PopupMenu zoom;
  1957. const std::pair<const char*, const char*> items[] = {
  1958. { "zoomIn", TR_NOOP ("Zoom in") }, { "zoomOut", TR_NOOP ("Zoom out") }, { "zoom1", TR_NOOP ("Zoom: one bar") },
  1959. { "zoom2", TR_NOOP ("Zoom: four bars") }, { "zoom3", TR_NOOP ("Zoom: sixteen bars") },
  1960. { "zoomAll", TR_NOOP ("Zoom to show everything") }, { "zoomSelection", TR_NOOP ("Zoom to the selection") },
  1961. { "centrePlayhead", TR_NOOP ("Centre the view on the playhead") }
  1962. };
  1963. for (const auto& [id, text] : items)
  1964. if (const auto* a = keys::findAction ((prefix + id).toStdString())) // the key map holds the id strings
  1965. action (zoom, a->id, tr (text));
  1966. return zoom;
  1967. };
  1968. switch (panel)
  1969. {
  1970. case Panel::channelRack:
  1971. {
  1972. menu.addSubMenu (tr ("Pattern"), makePatternMenu());
  1973. menu.addSeparator();
  1974. action (menu, "rack.graphEditor", tr ("Graph lanes (velocity, pan, pitch...)"), true, rack.areGraphLanesShown());
  1975. action (menu, "rack.pianoRollView", tr ("Piano-roll view of all channels"), true, rack.isPianoRollView());
  1976. action (menu, "rack.rotateLeft", tr ("Rotate the selected channels' steps left"));
  1977. action (menu, "rack.rotateRight", tr ("Rotate the selected channels' steps right"));
  1978. juce::PopupMenu sort;
  1979. sort.addItem (tr ("By name"), [this] { rack.sortChannels (ChannelSort::name); });
  1980. sort.addItem (tr ("By color"), [this] { rack.sortChannels (ChannelSort::colour); });
  1981. sort.addItem (tr ("By mixer insert"), [this] { rack.sortChannels (ChannelSort::insert); });
  1982. sort.addItem (tr ("By type"), [this] { rack.sortChannels (ChannelSort::type); });
  1983. menu.addSubMenu (tr ("Sort channels"), sort);
  1984. menu.addItem (tr ("Select unused channels"), [this] { rack.selectUnused(); });
  1985. action (menu, "rack.groupSelected", tr ("Group selected..."));
  1986. break;
  1987. }
  1988. case Panel::playlist:
  1989. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  1990. workspace.toggleMaximised (Panel::playlist);
  1991. refreshPanelButtons();
  1992. });
  1993. menu.addSeparator();
  1994. action (menu, "playlist.ripple", tr ("Ripple editing (resizing and deleting move the later clips)"), true, playlist.isRippleOn());
  1995. action (menu, "playlist.rippleDelete", tr ("Delete the selected clips and close the gaps"));
  1996. action (menu, "playlist.autoCrossfades", tr ("Automatic crossfades (current project)"), true, engine.getSong().autoCrossfades);
  1997. action (menu, "playlist.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (false));
  1998. action (menu, "playlist.pitchClipsDown", tr ("Pitch selected audio clips one semitone down"));
  1999. action (menu, "playlist.pitchClipsUp", tr ("Pitch selected audio clips one semitone up"));
  2000. action (menu, "playlist.reverseClips", tr ("Reverse selected audio clips"));
  2001. action (menu, "playlist.quantizeStarts", tr ("Quantize the clips' starts"));
  2002. action (menu, "playlist.quantizeHalf", tr ("Quantize the clips' starts 50% (halfway to the grid)"));
  2003. // round 168f: FL's Playlist Edit / Tools items ([DFM] EEMenu)
  2004. action (menu, "playlist.muteClips", tr ("Mute")); // FL's Alt+M / Shift+Alt+M (issue #53)
  2005. action (menu, "playlist.unmuteClips", tr ("Unmute"));
  2006. action (menu, "playlist.makeUnique", tr ("Make unique"));
  2007. action (menu, "playlist.mergePatternClips", tr ("Merge pattern clips"));
  2008. action (menu, "playlist.purgeUnusedAudio", tr ("Purge unused audio clips"));
  2009. action (menu, "playlist.stretchMode", tr ("Stretch audio when resizing audio clips"), true, EditorGlobals::get().stretchOnResize);
  2010. action (menu, "playlist.createVariants", tr ("Create variants when stretching audio clips"), true, EditorGlobals::get().createVariants);
  2011. {
  2012. juce::PopupMenu trackTools;
  2013. action (trackTools, "playlist.cloneTracks", tr ("Clone selected playlist track(s)"));
  2014. action (trackTools, "playlist.lockAllToContent", tr ("Lock all playlist tracks to content"));
  2015. action (trackTools, "playlist.unlockAllFromContent", tr ("Unlock all playlist tracks from content"));
  2016. action (trackTools, "playlist.resetEmptyTracks", tr ("Reset empty playlist tracks"));
  2017. action (trackTools, "playlist.collapseAllGroups", tr ("Collapse all grouped tracks"));
  2018. action (trackTools, "playlist.expandAllGroups", tr ("Expand all grouped tracks"));
  2019. menu.addSubMenu (tr ("Tools"), trackTools);
  2020. }
  2021. {
  2022. // FL's Playlist Tools › EERenderPLSelectionMenu, EEPLRenderAllTracksMenu, EEPLRenderAllTrackGroupsMenu (round 168e)
  2023. juce::PopupMenu consolidate;
  2024. action (consolidate, "tools.consolidateSelection", tr ("From selection start"));
  2025. action (consolidate, "tools.consolidateSelectionSongStart", tr ("From song start"));
  2026. menu.addSubMenu (tr ("Consolidate playlist selection"), consolidate);
  2027. menu.addSubMenu (tr ("Export all playlist tracks"), playlistTrackExportMenu (false));
  2028. menu.addSubMenu (tr ("Export all playlist track groups"), playlistTrackExportMenu (true));
  2029. }
  2030. menu.addSubMenu (tr ("Zoom"), zoomMenu ("playlist."));
  2031. menu.addSeparator();
  2032. // FL's Performance mode (round 165m)
  2033. action (menu, "playlist.performanceMode", tr ("Performance mode"), true, engine.getSong().performanceMode);
  2034. action (menu, "playlist.zoomPerformance", tr ("Zoom on performance clips"), engine.getSong().performanceZoneEnd() > 0);
  2035. action (menu, "playlist.perfClipProgress", tr ("Performance clip progress"), true, playlist.clipProgressShown());
  2036. action (menu, "playlist.perfTrackProgress", tr ("Performance track progress"), true, playlist.trackProgressShown());
  2037. break;
  2038. case Panel::pianoRoll:
  2039. {
  2040. juce::PopupMenu tools;
  2041. for (const auto* id : { "pianoRoll.riffMachine", "pianoRoll.chordProgression", "pianoRoll.articulate", "pianoRoll.quantize",
  2042. "pianoRoll.chop", "pianoRoll.arpeggiate", "pianoRoll.strum", "pianoRoll.flam", "pianoRoll.claw",
  2043. "pianoRoll.limit", "pianoRoll.flip", "pianoRoll.randomise", "pianoRoll.scaleLevels", "pianoRoll.lfo" })
  2044. if (const auto* a = keys::findAction (id))
  2045. action (tools, a->id, tr (a->description));
  2046. menu.addSubMenu (tr ("Tools"), tools);
  2047. action (menu, "pianoRoll.quickQuantize", tr ("Quick quantize (starts and lengths)"));
  2048. action (menu, "pianoRoll.quantizeStarts", tr ("Quantize starts"));
  2049. action (menu, "pianoRoll.quantizeHalf", tr ("Quantize starts 50% (halfway to the grid)"));
  2050. action (menu, "pianoRoll.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (true));
  2051. menu.addSubMenu (tr ("Zoom"), zoomMenu ("pianoRoll."));
  2052. menu.addItem (tr ("Snap notes to the scale"), pianoRoll.hasScale(), pianoRoll.isScaleSnapOn(),
  2053. [this] { pianoRoll.setScaleSnap (! pianoRoll.isScaleSnapOn()); });
  2054. break;
  2055. }
  2056. case Panel::mixer:
  2057. action (menu, "mixer.moveLeft", tr ("Move the selected inserts left"));
  2058. action (menu, "mixer.moveRight", tr ("Move the selected inserts right"));
  2059. menu.addSeparator();
  2060. action (menu, "mixer.linkChannels", tr ("Link the selected channels to the selected insert"));
  2061. action (menu, "mixer.linkChannelsFrom", tr ("Link the selected channels to inserts starting from the selected one"));
  2062. action (menu, "mixer.selectLinkedChannels", tr ("Select the channels linked to the selected insert"));
  2063. break;
  2064. case Panel::browser:
  2065. action (menu, "browser.search", tr ("Search the Browser"));
  2066. browser.addViewItems (menu); // what it lists, which folders it shows (round 163)
  2067. menu.addItem (tr ("Add folder..."), [this] { browser.addUserFolder(); });
  2068. action (menu, "view.sampleBrowser", tr ("Sample browser (separate window)"));
  2069. menu.addSeparator();
  2070. // the search index (round 162, issue #9): searches read it; it follows changed folders by itself
  2071. menu.addSectionHeader (browser.searchIndexStatus());
  2072. menu.addItem (tr ("Refresh search index"), [this] { browser.refreshSearchIndex (false); });
  2073. menu.addItem (tr ("Rebuild search index"), [this] { browser.refreshSearchIndex (true); });
  2074. break;
  2075. default:
  2076. break;
  2077. }
  2078. }
  2079. // --- quick-add palette and history -------------------------------------------------------------
  2080. void MainComponent::showQuickAdd()
  2081. {
  2082. QuickAddTargets targets;
  2083. targets.effectsFirst = workspace.getFocused() == Panel::mixer;
  2084. targets.addInstrument = [this] (ChannelDef c) {
  2085. rack.addChannel (std::move (c), true);
  2086. showPanel (Panel::channelRack);
  2087. };
  2088. targets.addEffect = [this] (EffectSlot slot) {
  2089. if (! mixer.addEffectToSelected (std::move (slot)))
  2090. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Quick-add palette"),
  2091. tr ("The selected insert has no free effect slot."));
  2092. else
  2093. showPanel (Panel::mixer);
  2094. };
  2095. openToolWindow (makeQuickAddPalette (engine, std::move (targets)), tr ("Quick-add palette"), "quickadd");
  2096. }
  2097. std::unique_ptr<juce::Component> MainComponent::makeQuickAddForSnapshot()
  2098. {
  2099. QuickAddTargets targets;
  2100. targets.addInstrument = [] (ChannelDef) {};
  2101. targets.addEffect = [] (EffectSlot) {};
  2102. return makeQuickAddPalette (engine, std::move (targets));
  2103. }
  2104. void MainComponent::showHistory()
  2105. {
  2106. if (auto* open = findToolWindow ("history"))
  2107. {
  2108. open->toFront (true);
  2109. return;
  2110. }
  2111. openToolWindow (makeHistoryPanel (engine), tr ("Undo history"), "history");
  2112. }
  2113. // --- recording options ---------------------------------------------------------------------------
  2114. void MainComponent::updateRecordQuantise()
  2115. {
  2116. // the global grid sets the record quantise; "none" and the zoom-dependent grids record as played
  2117. std::int64_t ticks = 0;
  2118. // (the grid is kept even with "Note start time" off: "Note end time" uses it too)
  2119. {
  2120. const auto& option = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  2121. if (option.kind == grid::Kind::ticks)
  2122. ticks = option.ticks;
  2123. else if (option.kind == grid::Kind::bar)
  2124. ticks = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  2125. }
  2126. if (engine.getRecordOptions().quantise != ticks || engine.getRecordOptions().quantiseStarts != recordQuantiseOn)
  2127. {
  2128. auto o = engine.getRecordOptions();
  2129. o.quantise = ticks;
  2130. o.quantiseStarts = recordQuantiseOn;
  2131. engine.setRecordOptions (o);
  2132. }
  2133. }
  2134. void MainComponent::addRecordQuantizeItems (juce::PopupMenu& menu)
  2135. {
  2136. const auto o = engine.getRecordOptions();
  2137. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  2138. auto options = engine.getRecordOptions();
  2139. change (options);
  2140. engine.setRecordOptions (options);
  2141. saveUiSettings();
  2142. };
  2143. // FL's record menu "Quantize" items (REA round 139), to the global snap
  2144. menu.addItem (tr ("Note start time"), ! o.toStepSequencer, recordQuantiseOn && ! o.toStepSequencer, [this] {
  2145. recordQuantiseOn = ! recordQuantiseOn;
  2146. updateRecordQuantise();
  2147. saveUiSettings();
  2148. });
  2149. menu.addItem (tr ("Note end time"), ! o.toStepSequencer, o.noteEnd == NoteEnd::quantize && ! o.toStepSequencer, [set] {
  2150. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::quantize ? NoteEnd::keepEnd : NoteEnd::quantize; });
  2151. });
  2152. menu.addItem (tr ("Leave note duration"), ! o.toStepSequencer, o.noteEnd == NoteEnd::keepLength && ! o.toStepSequencer, [set] {
  2153. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::keepLength ? NoteEnd::keepEnd : NoteEnd::keepLength; });
  2154. });
  2155. menu.addItem (tr ("Record to step sequencer"), true, o.toStepSequencer,
  2156. [set] { set ([] (AudioEngine::RecordOptions& r) { r.toStepSequencer = ! r.toStepSequencer; }); });
  2157. // FL's "Automations" (RecQuantizeAutomationsMenu, setting QuantizeAutomations; REA round 143): recorded automation
  2158. // points go to the snap
  2159. menu.addItem (tr ("Automations"), true, o.quantiseAutomation,
  2160. [set] { set ([] (AudioEngine::RecordOptions& r) { r.quantiseAutomation = ! r.quantiseAutomation; }); });
  2161. }
  2162. void MainComponent::addRecordOptions (juce::PopupMenu& menu)
  2163. {
  2164. const auto o = engine.getRecordOptions();
  2165. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  2166. auto options = engine.getRecordOptions();
  2167. change (options);
  2168. engine.setRecordOptions (options);
  2169. refreshRecordOptionButtons();
  2170. saveUiSettings();
  2171. };
  2172. juce::PopupMenu countIn;
  2173. countIn.addItem (tr ("Off"), true, o.countInBars == 0, [set] { set ([] (AudioEngine::RecordOptions& r) { r.countInBars = 0; }); });
  2174. for (int bars : { 1, 2, 4 })
  2175. countIn.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, o.countInBars == bars,
  2176. [set, bars] { set ([bars] (AudioEngine::RecordOptions& r) { r.countInBars = bars; }); });
  2177. menu.addSubMenu (tr ("Count-in") + shortcutText ("record.countIn"), countIn);
  2178. menu.addItem (tr ("Wait for the first note to start") + shortcutText ("record.waitForInput"), true, o.waitForInput,
  2179. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitForInput = ! r.waitForInput; }); });
  2180. // round 163: punch in/out on the loop region, pre-roll and post-roll (bars)
  2181. {
  2182. auto bars = [&set] (juce::PopupMenu& m, int now, std::function<void (AudioEngine::RecordOptions&, int)> apply) {
  2183. m.addItem (tr ("Off"), true, now == 0, [set, apply] { set ([apply] (AudioEngine::RecordOptions& r) { apply (r, 0); }); });
  2184. for (int n : { 1, 2, 4 })
  2185. m.addItem (n == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (n) }), true, now == n,
  2186. [set, apply, n] { set ([apply, n] (AudioEngine::RecordOptions& r) { apply (r, n); }); });
  2187. };
  2188. juce::PopupMenu pre, post;
  2189. bars (pre, o.preRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.preRollBars = n; });
  2190. bars (post, o.postRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.postRollBars = n; });
  2191. menu.addItem (tr ("Audio: punch in/out on the loop region (plays through it, keeps only the region)"), true, o.punchLoopRegion,
  2192. [set] { set ([] (AudioEngine::RecordOptions& r) { r.punchLoopRegion = ! r.punchLoopRegion; }); });
  2193. menu.addSubMenu (tr ("Audio: pre-roll (plays before the punch-in or the start position)"), pre);
  2194. menu.addSubMenu (tr ("Audio: post-roll (plays after the punch-out, then stops)"), post);
  2195. }
  2196. menu.addSeparator();
  2197. menu.addItem (tr ("Overdub: add to the pattern"), true, o.mode == RecordMode::overdub,
  2198. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::overdub; }); });
  2199. menu.addItem (tr ("Replace: a recorded channel's old notes are cleared"), true, o.mode == RecordMode::replace,
  2200. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::replace; }); });
  2201. menu.addSeparator();
  2202. {
  2203. juce::PopupMenu quantize;
  2204. addRecordQuantizeItems (quantize);
  2205. menu.addSubMenu (tr ("Quantize recorded notes to the global snap"), quantize);
  2206. }
  2207. menu.addItem (tr ("Song mode: place a pattern clip where recording starts"), true, o.placeSongClip,
  2208. [set] { set ([] (AudioEngine::RecordOptions& r) { r.placeSongClip = ! r.placeSongClip; }); });
  2209. }
  2210. void MainComponent::toggleRecording()
  2211. {
  2212. if (engine.isRecording())
  2213. {
  2214. engine.setRecording (false);
  2215. return;
  2216. }
  2217. if (! engine.getRecordOptions().askWhatToRecord || ! persistent)
  2218. {
  2219. engine.setRecording (true);
  2220. if (engine.getRecordOptions().startsPlayback && ! engine.getTransport().playing.load()) // FL's "Recording starts playback"
  2221. engine.startPlayback();
  2222. return;
  2223. }
  2224. juce::Component::SafePointer<MainComponent> safe (this);
  2225. showRecordChoiceDialog ([safe] (int choice, bool dontAsk) {
  2226. if (safe == nullptr)
  2227. return;
  2228. if (choice == recordChoiceAudioEditor)
  2229. {
  2230. openAudioEditorRecording (safe->engine);
  2231. if (! safe->engine.getTransport().playing.load())
  2232. safe->engine.play();
  2233. return;
  2234. }
  2235. auto o = safe->engine.getRecordOptions();
  2236. o.recordNotes = choice != recordChoiceAudio;
  2237. o.recordAudio = choice != recordChoiceNotes;
  2238. o.recordAutomation = choice != recordChoiceAudio;
  2239. if (dontAsk)
  2240. o.askWhatToRecord = false;
  2241. safe->engine.setRecordOptions (o);
  2242. if (dontAsk)
  2243. safe->saveUiSettings();
  2244. if (choice == recordChoiceAudio && safe->engine.getArmedInserts().empty())
  2245. safe->armSelectedInsertForAudio();
  2246. safe->engine.setRecording (true);
  2247. if (o.startsPlayback && ! safe->engine.getTransport().playing.load()) // FL's "Recording starts playback"
  2248. safe->engine.startPlayback();
  2249. });
  2250. }
  2251. // Round 163: the fastest way from "press record" to a clip on the Playlist — one key arms the selected insert (or the
  2252. // one with an input), records audio only (no question) and starts playback (count-in / pre-roll as set); pressed
  2253. // again it stops, and the take is on the Playlist.
  2254. void MainComponent::quickRecordAudio()
  2255. {
  2256. auto& transport = engine.getTransport();
  2257. if (engine.isRecording() && (transport.playing.load() || engine.isCountingIn() || engine.isWaitingForInput()))
  2258. {
  2259. engine.stop();
  2260. engine.setRecording (false);
  2261. return;
  2262. }
  2263. if (engine.getArmedInserts().empty())
  2264. armSelectedInsertForAudio();
  2265. if (engine.getArmedInserts().empty()) // no input yet: its menu is open, nothing to record
  2266. return;
  2267. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  2268. {
  2269. o.recordAudio = true;
  2270. engine.setRecordOptions (o);
  2271. }
  2272. engine.setRecording (true);
  2273. if (! transport.playing.load())
  2274. engine.startPlayback();
  2275. }
  2276. void MainComponent::armSelectedInsertForAudio()
  2277. {
  2278. const auto& mixer = engine.getSong().mixer;
  2279. // the selected insert, else the first one with an input, else a free one
  2280. auto target = this->mixer.getStripsForSnapshot().getSelectedTrack();
  2281. for (int t = 1; target <= 0 && t < (int) mixer.size(); ++t)
  2282. if (mixer[(std::size_t) t].inputChannel >= 0)
  2283. target = t;
  2284. if (target <= 0)
  2285. target = engine.getSong().nextFreeInsert();
  2286. if (target <= 0 || target >= (int) mixer.size())
  2287. return;
  2288. showPanel (Panel::mixer);
  2289. this->mixer.selectTrack (target);
  2290. if (engine.isInsertArmed (target))
  2291. return;
  2292. // this menu item says "(choose its input)": without one, the input menu comes first and arms after the choice
  2293. if (mixer[(std::size_t) target].inputChannel < 0)
  2294. mixerinput::showMenu (engine, target, &this->mixer, [this, target] { engine.setInsertArmed (target, true); });
  2295. else
  2296. mixerinput::toggleArm (engine, target, &this->mixer);
  2297. }
  2298. void MainComponent::showMetronomeMenu()
  2299. {
  2300. // FL 2026's right-click on the metronome button, as it is (REA round 165z-a2): the "Metronome sound" choice only,
  2301. // in FL's order. The volume trim is in Options, the count-in has its own button and the track the click plays
  2302. // through is in Settings › Audio › Mixer.
  2303. auto& transport = engine.getTransport();
  2304. juce::PopupMenu menu;
  2305. menu.addSectionHeader (tr ("Metronome sound"));
  2306. for (int i = 0; i < metronome::soundCount; ++i)
  2307. menu.addItem (tr (metronome::soundName (i)), true, metronome::clampSound (transport.metronomeSound.load()) == i, [this, i] {
  2308. engine.getTransport().metronomeSound.store (i);
  2309. saveUiSettings();
  2310. });
  2311. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&metronomeButton));
  2312. }
  2313. void MainComponent::showTypingPianoMenu()
  2314. {
  2315. // FL 2026's right-click on the typing keyboard button (KbToMIDIPopup, measured round 168t2): Root note C..B,
  2316. // Octave 2..6 (where the Z row starts), Options › Reset. FL's "Layout" list (FPC, Janko, Performance mode,
  2317. // Slicex, scales...) is not here yet: LYNX plays the Piano layout, FL's default.
  2318. static const char* const names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  2319. juce::PopupMenu menu;
  2320. menu.addSectionHeader (tr ("Root note"));
  2321. for (int r = 0; r < 12; ++r)
  2322. menu.addItem (names[r], true, typingRoot == r, [this, r] { typingRoot = r; saveUiSettings(); });
  2323. menu.addSectionHeader (tr ("Octave"));
  2324. for (int o = keys::typingpiano::minOctave; o <= keys::typingpiano::maxOctave; ++o)
  2325. menu.addItem (juce::String (o), true, typingOctave == o, [this, o] { typingOctave = o; saveUiSettings(); });
  2326. menu.addSectionHeader (tr ("Options"));
  2327. menu.addItem (tr ("Reset"), [this] {
  2328. typingOctave = keys::typingpiano::defaultOctave;
  2329. typingRoot = 0;
  2330. saveUiSettings();
  2331. });
  2332. menu.addSectionHeader (tr ("Layout"));
  2333. menu.addItem (tr ("Piano"), true, true, [] {});
  2334. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&typingPianoButton));
  2335. }
  2336. void MainComponent::dumpScoreLog (int minutes)
  2337. {
  2338. const auto& song = engine.getSong();
  2339. scorelog::DumpOptions options;
  2340. options.minutes = minutes;
  2341. options.bpm = song.bpm;
  2342. options.beatsPerBar = song.beatsPerBar;
  2343. auto notes = scorelog::dump (engine.scoreLogSnapshot(), options);
  2344. // (channels deleted since the notes were played are left out)
  2345. notes.erase (std::remove_if (notes.begin(), notes.end(), [&song] (const Note& n) { return n.channel < 0 || n.channel >= (int) song.channels.size(); }),
  2346. notes.end());
  2347. if (notes.empty())
  2348. {
  2349. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Score logger"),
  2350. tr ("The score log is empty: no notes were played on a MIDI keyboard or the typing keyboard in that time."));
  2351. return;
  2352. }
  2353. auto apply = [this] (std::vector<Note> logged, bool replace) {
  2354. const auto count = logged.size();
  2355. engine.editSong ([&logged, replace] (Song& s) {
  2356. if (s.patterns.empty())
  2357. s.patterns.emplace_back();
  2358. s.currentPattern = juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern);
  2359. auto& pattern = s.patterns[(std::size_t) s.currentPattern];
  2360. if (replace)
  2361. pattern.notes.clear();
  2362. pattern.notes.insert (pattern.notes.end(), logged.begin(), logged.end());
  2363. pattern.sortNotes();
  2364. });
  2365. ui::postHint ({ tr ("Score log: {0} notes put in the pattern", { juce::String ((int) count) }), {}, false, false }, 4000);
  2366. };
  2367. const auto& patterns = song.patterns;
  2368. const auto current = song.currentPattern;
  2369. if (current < 0 || current >= (int) patterns.size() || patterns[(std::size_t) current].notes.empty())
  2370. {
  2371. apply (std::move (notes), false);
  2372. return;
  2373. }
  2374. auto box = juce::MessageBoxOptions()
  2375. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  2376. .withTitle (tr ("Score logger"))
  2377. .withMessage (tr ("The current pattern isn't empty. Do you want the score log to be merged, or to replace the current content?"))
  2378. .withButton (tr ("Merge"))
  2379. .withButton (tr ("Replace"))
  2380. .withButton (tr ("Cancel"));
  2381. juce::AlertWindow::showAsync (box, [apply, notes] (int result) mutable {
  2382. if (result == 1 || result == 2)
  2383. apply (std::move (notes), result == 2);
  2384. });
  2385. }
  2386. void MainComponent::showMetronomeVolume()
  2387. {
  2388. // a callout with the volume knob; the click plays at the new level at once (Transport::metronomeVolume)
  2389. struct VolumePanel final : public juce::Component
  2390. {
  2391. VolumePanel (MainComponent& m) : owner (m)
  2392. {
  2393. title.setText (tr ("Metronome volume"), juce::dontSendNotification);
  2394. title.setJustificationType (juce::Justification::centred);
  2395. addAndMakeVisible (title);
  2396. knob.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  2397. knob.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 120, 18);
  2398. knob.setRange (0.0, controls::maxUtilityVolume, 0.01);
  2399. knob.setDoubleClickReturnValue (true, 1.0);
  2400. knob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  2401. knob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  2402. knob.setValue (owner.engine.getTransport().metronomeVolume.load(), juce::dontSendNotification);
  2403. knob.onValueChange = [this] { owner.engine.getTransport().metronomeVolume.store ((float) knob.getValue()); };
  2404. knob.onDragEnd = [this] { owner.saveUiSettings(); };
  2405. ui::setHint (knob, tr ("Metronome volume: 100% is the default click level, up to 125% [2xLMB] 100%"));
  2406. addAndMakeVisible (knob);
  2407. setSize (170, 150);
  2408. }
  2409. ~VolumePanel() override { owner.saveUiSettings(); }
  2410. void resized() override
  2411. {
  2412. auto r = getLocalBounds().reduced (8);
  2413. title.setBounds (r.removeFromTop (20));
  2414. knob.setBounds (r);
  2415. }
  2416. MainComponent& owner;
  2417. juce::Label title;
  2418. juce::Slider knob;
  2419. };
  2420. juce::CallOutBox::launchAsynchronously (std::make_unique<VolumePanel> (*this), metronomeButton.getScreenBounds(), nullptr);
  2421. }
  2422. void MainComponent::openAudioEditorForSelection()
  2423. {
  2424. const auto& song = engine.getSong();
  2425. const auto channel = engine.getSelectedChannel();
  2426. if (juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  2427. {
  2428. const auto& c = song.channels[(std::size_t) channel];
  2429. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && ! c.samplePath.empty())
  2430. {
  2431. openAudioEditorForChannel (engine, channel);
  2432. return;
  2433. }
  2434. }
  2435. openAudioEditor (engine);
  2436. }
  2437. void MainComponent::showRecordMenu()
  2438. {
  2439. const auto o = engine.getRecordOptions();
  2440. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  2441. auto options = engine.getRecordOptions();
  2442. change (options);
  2443. engine.setRecordOptions (options);
  2444. saveUiSettings();
  2445. };
  2446. juce::PopupMenu menu;
  2447. menu.addSectionHeader (tr ("Recording filter"));
  2448. // FL's filter order (RecMenu, REA round 143): Automation, Notes, Audio
  2449. menu.addItem (tr ("Automation (the controls you move: automation clips in song mode, pattern events in pattern mode)"), true,
  2450. o.recordAutomation, [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAutomation = ! r.recordAutomation; }); });
  2451. menu.addItem (tr ("Notes (MIDI and PC keyboard) into the current pattern"), true, o.recordNotes,
  2452. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordNotes = ! r.recordNotes; }); });
  2453. menu.addItem (tr ("Audio of the armed mixer inserts (becomes Playlist clips)"), true, o.recordAudio,
  2454. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAudio = ! r.recordAudio; }); });
  2455. menu.addItem (tr ("Clips (Performance mode: the launched clips are written into the arrangement)"), true, o.recordClips,
  2456. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordClips = ! r.recordClips; }); });
  2457. menu.addItem (tr ("Ask what to record when recording starts"), true, o.askWhatToRecord,
  2458. [set] { set ([] (AudioEngine::RecordOptions& r) { r.askWhatToRecord = ! r.askWhatToRecord; }); });
  2459. // FL's "Options" section (REA round 134)
  2460. menu.addSectionHeader (tr ("Options"));
  2461. menu.addItem (tr ("Recording starts playback"), true, o.startsPlayback,
  2462. [set] { set ([] (AudioEngine::RecordOptions& r) { r.startsPlayback = ! r.startsPlayback; }); });
  2463. menu.addItem (tr ("Disarm on stop (recording switches off when playback stops)"), true, o.recordOffOnStop,
  2464. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordOffOnStop = ! r.recordOffOnStop; }); });
  2465. // LYNX's own (issue #16; FL has no such option): also in Mixer › Disk recording
  2466. menu.addItem (tr ("Disarm the inserts when recording stops"), true, o.disarmOnStop,
  2467. [set] { set ([] (AudioEngine::RecordOptions& r) { r.disarmOnStop = ! r.disarmOnStop; }); });
  2468. menu.addItem (tr ("Enable recording markers (Start / Stop recording markers in the Playlist)"), true, o.recordingMarkers,
  2469. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordingMarkers = ! r.recordingMarkers; }); });
  2470. // FL's "Quantize" section (REA round 139): to the global snap
  2471. menu.addSectionHeader (tr ("Quantize"));
  2472. addRecordQuantizeItems (menu);
  2473. menu.addItem (tr ("Record into the audio editor..."), [this] { openAudioEditor (engine); });
  2474. menu.addSeparator();
  2475. menu.addItem (tr ("Arm the selected mixer insert for audio (choose its input)..."), [this] { armSelectedInsertForAudio(); });
  2476. menu.addItem (tr ("Audio settings (input device)..."), [this] { openSettings ((int) SettingsPage::audio); });
  2477. menu.addItem (tr ("Open recordings folder"), [this] {
  2478. const auto folder = engine.getRecordingFolder();
  2479. folder.createDirectory();
  2480. folder.startAsProcess();
  2481. });
  2482. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  2483. menu.addSeparator();
  2484. addRecordOptions (menu);
  2485. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (recordMenuButton.isVisible() ? (juce::Component*) &recordMenuButton
  2486. : (juce::Component*) &recordButton));
  2487. }
  2488. void MainComponent::refreshRecordOptionButtons()
  2489. {
  2490. auto withKey = [this] (const juce::String& text, const char* id) {
  2491. const auto key = shortcutText (id).trim();
  2492. return key.isEmpty() ? text : text + " (" + key + ")";
  2493. };
  2494. const auto o = engine.getRecordOptions();
  2495. countInButton.setToggleState (o.countInBars > 0, juce::dontSendNotification);
  2496. countInButton.setTooltip (withKey (o.countInBars > 0 ? tr ("Count-in before recording: {0} bar(s)", { juce::String (o.countInBars) })
  2497. : tr ("Count-in before recording: off"),
  2498. "record.countIn"));
  2499. waitInputButton.setToggleState (o.waitForInput, juce::dontSendNotification);
  2500. waitInputButton.setTooltip (withKey (o.waitForInput ? tr ("Recording waits for the first note: on") : tr ("Recording waits for the first note: off"),
  2501. "record.waitForInput"));
  2502. }
  2503. void MainComponent::clonePatternNow()
  2504. {
  2505. engine.editSong ([] (Song& s) { clonePattern (s, s.currentPattern); });
  2506. }
  2507. void MainComponent::movePatternNow (int delta)
  2508. {
  2509. engine.editSong ([delta] (Song& s) { movePattern (s, s.currentPattern, delta); });
  2510. }
  2511. void MainComponent::splitPatternByChannelNow()
  2512. {
  2513. int created = 0;
  2514. engine.editSong ([&created] (Song& s) { created = splitPatternByChannel (s, s.currentPattern); });
  2515. if (created == 0)
  2516. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Split by channel"), tr ("This pattern has no notes."));
  2517. }
  2518. void MainComponent::showRenamePattern (int index)
  2519. {
  2520. if (index < 0 || index >= (int) engine.getSong().patterns.size())
  2521. return;
  2522. const auto& p = engine.getSong().patterns[(std::size_t) index];
  2523. showNameAndColourDialog (tr ("Rename pattern"), juce::String::fromUTF8 (p.name.c_str()), p.colour,
  2524. [this, index] (const juce::String& name, std::uint32_t colour) {
  2525. if (index < (int) engine.getSong().patterns.size())
  2526. engine.editSong ([index, n = name.toStdString(), colour] (Song& s) {
  2527. s.patterns[(std::size_t) index].name = n;
  2528. s.patterns[(std::size_t) index].colour = colour;
  2529. });
  2530. });
  2531. }
  2532. void MainComponent::refreshToolbar()
  2533. {
  2534. const auto& song = engine.getSong();
  2535. patternBox.clear (juce::dontSendNotification);
  2536. for (std::size_t i = 0; i < song.patterns.size(); ++i)
  2537. patternBox.addItem (juce::String::fromUTF8 (song.patterns[i].name.c_str()), (int) i + 1);
  2538. patternBox.setSelectedItemIndex (song.currentPattern, juce::dontSendNotification);
  2539. swingSlider.setValue (song.swing, juce::dontSendNotification);
  2540. tempoDisplay.repaint();
  2541. refreshModeButton();
  2542. refreshRackPatternSelector();
  2543. refreshRackLengthBox();
  2544. }
  2545. void MainComponent::refreshRackPatternSelector()
  2546. {
  2547. const auto& song = engine.getSong();
  2548. const auto valid = song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size();
  2549. const auto text = valid ? juce::String::fromUTF8 (song.patterns[(std::size_t) song.currentPattern].name.c_str()) : juce::String();
  2550. const auto colour = valid ? PlaylistComponent::patternColour (song, song.currentPattern) : juce::Colour();
  2551. if (text != rackPatternSelector.text || colour != rackPatternSelector.colour)
  2552. {
  2553. rackPatternSelector.text = text;
  2554. rackPatternSelector.colour = colour;
  2555. rackPatternSelector.repaint();
  2556. }
  2557. }
  2558. void MainComponent::showRackPatternList()
  2559. {
  2560. const auto& song = engine.getSong();
  2561. juce::PopupMenu menu;
  2562. for (int i = 0; i < (int) song.patterns.size(); ++i)
  2563. menu.addItem (juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()), true, i == song.currentPattern, [this, i] { selectPattern (i); });
  2564. menu.addSeparator();
  2565. menu.addItem (tr ("New pattern"), [this] { newPatternButton.onClick(); });
  2566. menu.addItem (tr ("Rename and color the pattern") + shortcutText ("pattern.rename"), [this] { runAction ("pattern.rename"); });
  2567. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackPatternSelector));
  2568. }
  2569. // --- the Channel Rack's pattern length box (issue #12) ---------------------------------------------------------
  2570. int MainComponent::PatternLengthBox::stepBars (int value, int delta)
  2571. {
  2572. static const int steps[] = { 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 };
  2573. constexpr int count = (int) (sizeof (steps) / sizeof (steps[0]));
  2574. int i = 0;
  2575. while (i + 1 < count && steps[i + 1] <= value)
  2576. ++i;
  2577. if (delta < 0 && steps[i] < value) // between two steps: going down lands on the lower one
  2578. ++delta;
  2579. return steps[juce::jlimit (0, count - 1, i + delta)];
  2580. }
  2581. void MainComponent::PatternLengthBox::paint (juce::Graphics& g)
  2582. {
  2583. using namespace theme;
  2584. const auto area = getLocalBounds().toFloat();
  2585. g.setColour (hovered ? colour::bg3 : colour::bg1);
  2586. g.fillRoundedRectangle (area, radius::sm);
  2587. g.setColour (hovered ? colour::borderStrong : colour::border);
  2588. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  2589. auto r = getLocalBounds().reduced (3, 0);
  2590. g.setFont (font (type::caption - 1.0f, true));
  2591. g.setColour (colour::textSecondary);
  2592. g.drawText (automatic ? "A" : "L", r.removeFromLeft (9), juce::Justification::centred, false);
  2593. g.setFont (font (type::small, true));
  2594. g.setColour (automatic ? colour::textSecondary : colour::textPrimary);
  2595. g.drawText (juce::String (bars), r, juce::Justification::centred, false);
  2596. }
  2597. void MainComponent::PatternLengthBox::mouseDown (const juce::MouseEvent& e)
  2598. {
  2599. dragStartBars = bars;
  2600. if (e.mods.isPopupMenu() && onMenu)
  2601. onMenu();
  2602. }
  2603. void MainComponent::PatternLengthBox::mouseDrag (const juce::MouseEvent& e)
  2604. {
  2605. if (e.mods.isPopupMenu() || onSet == nullptr)
  2606. return;
  2607. // one step of the list per 14 px up (as the rack's insert number box: drag up = more)
  2608. const auto delta = -e.getDistanceFromDragStartY() / 14;
  2609. const auto value = delta == 0 ? dragStartBars : stepBars (dragStartBars, delta);
  2610. if (value != bars || automatic)
  2611. if (delta != 0)
  2612. onSet (value);
  2613. }
  2614. void MainComponent::PatternLengthBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  2615. {
  2616. if (onSet != nullptr && wheel.deltaY != 0.0f)
  2617. onSet (stepBars (bars, wheel.deltaY > 0.0f ? 1 : -1));
  2618. }
  2619. void MainComponent::refreshRackLengthBox()
  2620. {
  2621. const auto& song = engine.getSong();
  2622. if (song.currentPattern < 0 || song.currentPattern >= (int) song.patterns.size())
  2623. return;
  2624. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  2625. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  2626. const auto bars = (int) juce::jmax<std::int64_t> (1, (pattern.effectiveLength (song.beatsPerBar) + bar - 1) / bar);
  2627. const auto automatic = pattern.lengthTicks == 0;
  2628. if (bars != rackLengthBox.bars || automatic != rackLengthBox.automatic)
  2629. {
  2630. rackLengthBox.bars = bars;
  2631. rackLengthBox.automatic = automatic;
  2632. rackLengthBox.setTooltip (automatic ? tr ("Pattern length: {0} (automatic, from the notes)", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) })
  2633. : tr ("Pattern length: {0}", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) }));
  2634. rackLengthBox.repaint();
  2635. }
  2636. }
  2637. void MainComponent::showPatternLengthMenu()
  2638. {
  2639. const auto& song = engine.getSong();
  2640. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  2641. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  2642. juce::PopupMenu menu;
  2643. menu.addSectionHeader (tr ("Pattern length"));
  2644. menu.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0, [this] { rackLengthBox.onSet (0); });
  2645. for (int bars : { 1, 2, 4, 8, 16, 32 })
  2646. menu.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == bars * bar,
  2647. [this, bars] { rackLengthBox.onSet (bars); });
  2648. menu.addSeparator();
  2649. menu.addItem (tr ("Type value..."), [this] {
  2650. ui::ValueSpec spec;
  2651. spec.name = tr ("Pattern length (bars, 0 = automatic)");
  2652. spec.minimum = 0.0;
  2653. spec.maximum = 999.0;
  2654. spec.interval = 1.0;
  2655. ui::typeValue (rackLengthBox, spec, rackLengthBox.automatic ? 0.0 : (double) rackLengthBox.bars,
  2656. [this] (double v) { rackLengthBox.onSet (juce::roundToInt (v)); });
  2657. });
  2658. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackLengthBox));
  2659. }
  2660. void MainComponent::PatternSelector::paint (juce::Graphics& g)
  2661. {
  2662. using namespace theme;
  2663. auto area = getLocalBounds().toFloat();
  2664. g.setColour (hoveredPart >= 0 ? colour::bg3 : colour::bg1);
  2665. g.fillRoundedRectangle (area, radius::sm);
  2666. g.setColour (hoveredPart >= 0 ? colour::borderStrong : colour::border);
  2667. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  2668. // the pattern's colour as a thin stripe at the left of the name
  2669. if (! colour.isTransparent())
  2670. {
  2671. g.setColour (colour);
  2672. g.fillRect (juce::Rectangle<float> ((float) arrowWidth + 1.0f, 4.0f, 3.0f, (float) getHeight() - 8.0f));
  2673. }
  2674. auto arrow = [&g, this] (int part, bool left) {
  2675. const auto box = juce::Rectangle<float> (left ? 0.0f : (float) (getWidth() - arrowWidth), 0.0f, (float) arrowWidth, (float) getHeight());
  2676. const auto c = box.getCentre();
  2677. juce::Path p;
  2678. if (left)
  2679. p.addTriangle (c.x + 2.5f, c.y - 4.0f, c.x + 2.5f, c.y + 4.0f, c.x - 2.5f, c.y);
  2680. else
  2681. p.addTriangle (c.x - 2.5f, c.y - 4.0f, c.x - 2.5f, c.y + 4.0f, c.x + 2.5f, c.y);
  2682. g.setColour (hoveredPart == part ? colour::textPrimary : colour::textSecondary);
  2683. g.fillPath (p);
  2684. };
  2685. arrow (0, true);
  2686. arrow (2, false);
  2687. g.setColour (colour::textPrimary);
  2688. g.setFont (font (type::small, true));
  2689. const auto name = getLocalBounds().withTrimmedLeft (arrowWidth + 7).withTrimmedRight (arrowWidth + 14);
  2690. g.drawText (text, name, juce::Justification::centredLeft, true);
  2691. icons::draw (g, Icon::chevronDown, juce::Rectangle<float> ((float) (getWidth() - arrowWidth - 14), 0.0f, 12.0f, (float) getHeight()).reduced (1.0f, 4.0f),
  2692. hoveredPart == 1 ? colour::textPrimary : colour::textSecondary);
  2693. g.setColour (colour::border);
  2694. g.fillRect (arrowWidth, 3, 1, getHeight() - 6);
  2695. g.fillRect (getWidth() - arrowWidth - 1, 3, 1, getHeight() - 6);
  2696. }
  2697. void MainComponent::PatternSelector::mouseDown (const juce::MouseEvent& e)
  2698. {
  2699. const auto part = partAt (e.x);
  2700. if (part == 1 || e.mods.isPopupMenu())
  2701. {
  2702. if (onMenu)
  2703. onMenu();
  2704. }
  2705. else if (onStep)
  2706. onStep (part == 0 ? -1 : 1);
  2707. }
  2708. void MainComponent::PatternSelector::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  2709. {
  2710. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  2711. if (delta != 0.0f && onStep)
  2712. onStep (delta > 0.0f ? -1 : 1);
  2713. }
  2714. juce::PopupMenu MainComponent::playlistTrackExportMenu (bool groups)
  2715. {
  2716. // FL: From song start... / From track start... / Time selection... (the last does nothing without a time selection)
  2717. juce::PopupMenu menu;
  2718. auto add = [&] (const juce::String& text, quickrender::Start start, bool enabled) {
  2719. menu.addItem (text, enabled, false, [this, start, groups] { exportAllPlaylistTracks (engine, projectName, start, groups); });
  2720. };
  2721. add (tr ("From song start..."), quickrender::Start::songStart, true);
  2722. add (tr ("From track start..."), quickrender::Start::clipStart, true);
  2723. add (tr ("Time selection..."), quickrender::Start::timeSelection, engine.getSong().hasLoop());
  2724. return menu;
  2725. }
  2726. juce::PopupMenu MainComponent::makePatternMenu()
  2727. {
  2728. const auto& song = engine.getSong();
  2729. const auto index = song.currentPattern;
  2730. const auto& pattern = song.patterns[(std::size_t) index];
  2731. auto colours = ui::colourMenu (pattern.colour, [this, index] (std::uint32_t c) {
  2732. if (index < (int) engine.getSong().patterns.size())
  2733. engine.editSong ([index, c] (Song& s) { s.patterns[(std::size_t) index].colour = c; });
  2734. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1));
  2735. juce::PopupMenu lengths;
  2736. lengths.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0,
  2737. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = 0; }); });
  2738. for (int bars : { 1, 2, 4, 8, 16, 32 })
  2739. {
  2740. const auto ticks = (std::int64_t) bars * ppq * juce::jmax (1, song.beatsPerBar);
  2741. lengths.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == ticks,
  2742. [this, index, ticks] { engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; }); });
  2743. }
  2744. juce::PopupMenu menu;
  2745. // a double-click on the title renames the pattern (issue #12)
  2746. ui::addItemHeader (menu, tr ("Pattern"), juce::String::fromUTF8 (pattern.name.c_str()), PlaylistComponent::patternColour (song, index),
  2747. [this, index] { showRenamePattern (index); });
  2748. menu.addItem (tr ("Next pattern") + shortcutText ("pattern.next"), index + 1 < (int) song.patterns.size(), false,
  2749. [this] { selectPattern (stepPattern (engine.getSong(), 1)); });
  2750. menu.addItem (tr ("Previous pattern") + shortcutText ("pattern.previous"), index > 0, false,
  2751. [this] { selectPattern (stepPattern (engine.getSong(), -1)); });
  2752. menu.addItem (tr ("First empty pattern (and name it)") + shortcutText ("pattern.firstEmpty"), [this] { runAction ("pattern.firstEmpty"); });
  2753. menu.addItem (tr ("Next empty pattern (and name it)") + shortcutText ("pattern.nextEmpty"), [this] { nextEmptyPattern(); });
  2754. menu.addItem (tr ("Next empty pattern (no naming)") + shortcutText ("pattern.nextEmptyNoName"), [this] { runAction ("pattern.nextEmptyNoName"); });
  2755. menu.addSeparator();
  2756. menu.addItem (tr ("Rename and color...") + shortcutText ("pattern.rename"), [this, index] { showRenamePattern (index); });
  2757. menu.addSubMenu (tr ("Color"), colours);
  2758. menu.addSubMenu (tr ("Length"), lengths);
  2759. menu.addItem (tr ("Insert an empty pattern before this one") + shortcutText ("pattern.insert"), [this] { insertPatternHere(); });
  2760. menu.addItem (tr ("Clone") + shortcutText ("pattern.clone"), [this] { clonePatternNow(); });
  2761. menu.addItem (tr ("Move up") + shortcutText ("pattern.moveUp"), index > 0, false, [this] { movePatternNow (-1); });
  2762. menu.addItem (tr ("Move down") + shortcutText ("pattern.moveDown"), index + 1 < (int) song.patterns.size(), false, [this] { movePatternNow (1); });
  2763. menu.addItem (tr ("Split by channel (one new pattern per channel)"), ! pattern.notes.empty(), false, [this] { splitPatternByChannelNow(); });
  2764. // FL's Patterns › PSPatQuickRenderMenu / PSPatRenderMenu / PSPatRenderReplaceMenu (PSPatQuickRenderMenuClick, tags 1 / 0 / 2;
  2765. // REA round 168e)
  2766. menu.addItem (tr ("Quick render as audio clip"), [this, index] { renderPatternAsAudioClip (engine, index, 1); });
  2767. menu.addItem (tr ("Render as audio clip..."), [this, index] { renderPatternAsAudioClip (engine, index, 0); });
  2768. menu.addItem (tr ("Render and replace..."), [this, index] { renderPatternAsAudioClip (engine, index, 2); });
  2769. juce::PopupMenu signatures;
  2770. for (int beats : { 2, 3, 4, 5, 6, 7, 8, 9, 12 })
  2771. signatures.addItem (juce::String (beats) + "/4", true, song.beatsPerBar == beats,
  2772. [this, beats] { engine.editSong ([beats] (Song& s) { s.beatsPerBar = beats; }); });
  2773. menu.addSubMenu (tr ("Song time signature"), signatures);
  2774. menu.addSeparator();
  2775. menu.addItem (tr ("Delete pattern") + shortcutText ("pattern.delete"), song.patterns.size() > 1, false,
  2776. [this, index] { engine.editSong ([index] (Song& s) { s.removePattern (index); }); });
  2777. return menu;
  2778. }
  2779. void MainComponent::showPatternMenu()
  2780. {
  2781. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patternMenuButton));
  2782. }
  2783. void MainComponent::refreshModeButton()
  2784. {
  2785. const auto recording = engine.isRecording();
  2786. recordButton.setToggleState (recording, juce::dontSendNotification);
  2787. const auto inputs = engine.getActiveMidiInputs();
  2788. recordButton.setTooltip ((engine.isAudioRecordingArmed() ? tr ("Record while playing: notes (PC keyboard and MIDI) and input audio")
  2789. : tr ("Record while playing: notes (PC keyboard and MIDI)"))
  2790. + "\n" + tr ("MIDI inputs: {0}", { inputs.isEmpty() ? tr ("none") : inputs.joinIntoString (", ") }));
  2791. recordMenuButton.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  2792. recordMenuButton.setOnColour (theme::colour::accentMuted);
  2793. const auto songMode = engine.getSong().mode == PlayMode::song;
  2794. patternModeButton.setToggleState (! songMode, juce::dontSendNotification);
  2795. songModeButton.setToggleState (songMode, juce::dontSendNotification);
  2796. metronomeButton.setToggleState (engine.getTransport().metronome.load(), juce::dontSendNotification);
  2797. }
  2798. void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  2799. {
  2800. if (const auto notice = engine.takeRecordingNotice(); notice.issue != AudioEngine::InputIssue::none && persistent)
  2801. mixerinput::explain (notice);
  2802. // round 165c: hardware inserts measured for another device setup (the device or its buffer size changed, or the project
  2803. // was measured elsewhere): a prompt that pings them on request, nothing pinged by itself (pings make clicks)
  2804. if (auto stale = engine.takeHardwareInsertNotice(); ! stale.empty() && persistent)
  2805. {
  2806. const auto count = (int) stale.size();
  2807. auto options = juce::MessageBoxOptions()
  2808. .withIconType (juce::MessageBoxIconType::InfoIcon)
  2809. .withTitle (tr ("Hardware Insert"))
  2810. .withMessage ((count == 1 ? tr ("The round trip of a hardware insert was measured for another audio setup (the device or its "
  2811. "buffer size changed), so its return is no longer lined up with the rest of the mix.")
  2812. : tr ("The round trip of {0} hardware inserts was measured for another audio setup (the device or its "
  2813. "buffer size changed), so their returns are no longer lined up with the rest of the mix.",
  2814. { juce::String (count) }))
  2815. + "\n\n" + tr ("Ping now? Each one sends a few clicks out to its gear and listens for them on its return."))
  2816. .withButton (tr ("Ping now"))
  2817. .withButton (tr ("Later"));
  2818. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), stale = std::move (stale)] (int result) {
  2819. if (result == 1 && safe != nullptr)
  2820. safe->engine.pingHardwareInserts (stale);
  2821. });
  2822. }
  2823. const auto& song = engine.getSong();
  2824. // FL's "Select first channel with notes when the pattern changes" (Settings › General, REA round 167j §5)
  2825. if (song.currentPattern != lastCurrentPattern)
  2826. {
  2827. const auto changedPattern = lastCurrentPattern >= 0;
  2828. lastCurrentPattern = song.currentPattern;
  2829. if (changedPattern && ChannelRackComponent::selectFirstChannelWithNotes)
  2830. if (const auto first = firstChannelWithNotes (song, song.currentPattern); first >= 0 && first != engine.getSelectedChannel())
  2831. engine.setSelectedChannel (first);
  2832. }
  2833. bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
  2834. for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
  2835. namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
  2836. refreshModeButton();
  2837. tempoDisplay.repaint();
  2838. // a project with other filter groups (or none): the rack's filter falls back to "All"
  2839. if (rack.getFilterGroup() >= (int) song.channelGroups.size())
  2840. rack.setFilterGroup (-1);
  2841. if (rackFilterBox.text != rack.filterName())
  2842. {
  2843. rackFilterBox.text = rack.filterName();
  2844. rackFilterBox.repaint();
  2845. }
  2846. if (rackLoopButton.getToggleState() != rack.isLoopingOn()) // (another pattern, undo)
  2847. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  2848. if ((int) song.channels.size() != fittedChannelCount && fittedChannelCount >= 0) // a row was added or removed
  2849. fitChannelRack (false);
  2850. if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (swingSlider.getValue() - song.swing) > 1e-6)
  2851. refreshToolbar();
  2852. else
  2853. {
  2854. refreshRackPatternSelector(); // a new pattern colour
  2855. refreshRackLengthBox(); // (notes added: the automatic length grows)
  2856. }
  2857. }
  2858. // --- tempo display -------------------------------------------------------------------------------
  2859. ui::ValueSpec MainComponent::TempoDisplay::spec() const
  2860. {
  2861. ui::ValueSpec s;
  2862. s.name = tr ("Tempo");
  2863. s.minimum = minTempo;
  2864. s.maximum = maxTempo;
  2865. s.defaultValue = 130.0;
  2866. s.toText = [] (double v) { return juce::String (v, 3) + " BPM"; };
  2867. s.target = AutomationTarget { AutomationTargetKind::tempo, 0 };
  2868. return s;
  2869. }
  2870. void MainComponent::TempoDisplay::setBpm (double bpm)
  2871. {
  2872. bpm = controls::clampTempo (bpm);
  2873. if (std::abs (bpm - engine.getSong().bpm) > 1e-9)
  2874. engine.editSong ([bpm] (Song& s) { s.bpm = bpm; });
  2875. repaint();
  2876. }
  2877. bool MainComponent::TempoDisplay::isOnDecimals (int x) const
  2878. {
  2879. return decimalX > 0 && x > decimalX;
  2880. }
  2881. void MainComponent::TempoDisplay::paint (juce::Graphics& g)
  2882. {
  2883. using namespace theme;
  2884. const auto area = getLocalBounds().toFloat();
  2885. g.setColour (colour::bg1);
  2886. g.fillRoundedRectangle (area, radius::md);
  2887. if (dragging)
  2888. {
  2889. g.setColour (colour::accent.withAlpha (0.6f));
  2890. g.drawRoundedRectangle (area.reduced (0.5f), radius::md, 1.0f);
  2891. }
  2892. const auto bpm = engine.getSong().bpm;
  2893. const auto whole = juce::String ((int) std::floor (bpm + 1e-9));
  2894. const auto fraction = juce::String (bpm - std::floor (bpm + 1e-9), 3).fromFirstOccurrenceOf (".", false, false).paddedRight ('0', 3).substring (0, 3);
  2895. const juce::Font big (monoFont (18.0f)), small (monoFont (11.0f)), caption (font (type::caption - 1.0f));
  2896. const auto wholeWidth = juce::GlyphArrangement::getStringWidth (big, whole);
  2897. const auto fracWidth = juce::GlyphArrangement::getStringWidth (small, "." + fraction);
  2898. const auto unitWidth = juce::GlyphArrangement::getStringWidth (caption, "BPM");
  2899. auto x = area.getCentreX() - (wholeWidth + fracWidth + 6.0f + unitWidth) / 2.0f;
  2900. const auto baseline = area.getCentreY() + 5.0f;
  2901. g.setColour (colour::textPrimary);
  2902. g.setFont (big);
  2903. g.drawSingleLineText (whole, juce::roundToInt (x), juce::roundToInt (baseline));
  2904. x += wholeWidth;
  2905. decimalX = juce::roundToInt (x);
  2906. g.setColour (dragOnDecimals && dragging ? colour::textPrimary : colour::textSecondary);
  2907. g.setFont (small);
  2908. g.drawSingleLineText ("." + fraction, juce::roundToInt (x), juce::roundToInt (baseline));
  2909. x += fracWidth + 6.0f;
  2910. g.setColour (colour::textDisabled);
  2911. g.setFont (caption);
  2912. g.drawSingleLineText ("BPM", juce::roundToInt (x), juce::roundToInt (baseline));
  2913. }
  2914. void MainComponent::TempoDisplay::mouseDown (const juce::MouseEvent& e)
  2915. {
  2916. if (e.mods.isPopupMenu())
  2917. {
  2918. showMenu();
  2919. return;
  2920. }
  2921. if (ui::isResetClick (e))
  2922. {
  2923. setBpm (spec().defaultValue);
  2924. return;
  2925. }
  2926. startBpm = engine.getSong().bpm;
  2927. dragOnDecimals = isOnDecimals (e.x);
  2928. dragging = true;
  2929. repaint();
  2930. }
  2931. void MainComponent::TempoDisplay::mouseDrag (const juce::MouseEvent& e)
  2932. {
  2933. if (dragging)
  2934. {
  2935. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  2936. setBpm (controls::tempoDrag (startBpm, -e.getDistanceFromDragStartY(), dragOnDecimals, e.mods.isCtrlDown()));
  2937. }
  2938. }
  2939. void MainComponent::TempoDisplay::mouseUp (const juce::MouseEvent&)
  2940. {
  2941. dragging = false;
  2942. repaint();
  2943. }
  2944. void MainComponent::TempoDisplay::mouseDoubleClick (const juce::MouseEvent& e)
  2945. {
  2946. if (! e.mods.isPopupMenu())
  2947. ui::typeValue (*this, spec(), engine.getSong().bpm, [this] (double v) { setBpm (v); });
  2948. }
  2949. void MainComponent::TempoDisplay::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  2950. {
  2951. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  2952. if (delta == 0.0f)
  2953. return;
  2954. const auto step = isOnDecimals (e.x) ? 0.01 : 1.0;
  2955. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  2956. setBpm (engine.getSong().bpm + (delta > 0.0f ? 1.0 : -1.0) * step * (e.mods.isCtrlDown() ? 0.1 : 1.0));
  2957. }
  2958. ui::Hint MainComponent::TempoDisplay::hintAt (juce::Point<int> p)
  2959. {
  2960. return ui::valueHint (spec(), engine.getSong().bpm,
  2961. isOnDecimals (p.x) ? tr ("[LMB] drag the decimals for fine changes [Wheel] 0.01 [2xLMB] type [RMB] tap tempo, half, double")
  2962. : tr ("[LMB] drag the whole number [Ctrl] fine [Wheel] 1 BPM [2xLMB] type [RMB] tap tempo, half, double"));
  2963. }
  2964. void MainComponent::TempoDisplay::showMenu()
  2965. {
  2966. const auto bpm = engine.getSong().bpm;
  2967. juce::PopupMenu menu;
  2968. menu.addSectionHeader (tr ("Tempo") + ": " + juce::String (bpm, 3) + " BPM");
  2969. menu.addItem (tr ("Type value..."), [this, bpm] { ui::typeValue (*this, spec(), bpm, [this] (double v) { setBpm (v); }); });
  2970. menu.addItem (tr ("Tempo tapper..."), [this] { showTap(); });
  2971. menu.addItem (tr ("Half ({0} BPM)", { juce::String (controls::halfTempo (bpm), 2) }), [this, bpm] { setBpm (controls::halfTempo (bpm)); });
  2972. menu.addItem (tr ("Double ({0} BPM)", { juce::String (controls::doubleTempo (bpm), 2) }), [this, bpm] { setBpm (controls::doubleTempo (bpm)); });
  2973. menu.addItem (tr ("Reset ({0})", { "130 BPM" }), [this] { setBpm (130.0); });
  2974. menu.addSeparator();
  2975. addAutomationItem (menu, engine, { AutomationTargetKind::tempo, 0 });
  2976. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  2977. }
  2978. void MainComponent::TempoDisplay::showTap()
  2979. {
  2980. openTempoTapper (engine); // FL's tempo menu opens its tempo tapper too
  2981. }
  2982. // --- hint bar ------------------------------------------------------------------------------------
  2983. juce::String MainComponent::idleHint() const
  2984. {
  2985. if (engine.isWaitingForInput())
  2986. return tr ("Recording: waiting for the first note ([Space] cancels)");
  2987. if (engine.isCountingIn())
  2988. return tr ("Recording: count-in...");
  2989. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.running)
  2990. return tr ("Scanning for plugins in the background: {0}% {1}", { juce::String (juce::roundToInt (scan.progress * 100.0f)), scan.file });
  2991. return tr ("Point at anything to see what it does here. [F1] shortcuts [F5]-[F9] windows [Space] play/stop "
  2992. "[Ctrl][T] typing piano: {0}", { typingPiano ? tr ("on") : tr ("off") });
  2993. }
  2994. juce::String MainComponent::keyMarkup (const char* actionId) const
  2995. {
  2996. const auto& chords = keyMap.chordsFor (actionId);
  2997. if (chords.empty())
  2998. return {};
  2999. // "Ctrl+Shift+S" -> "[Ctrl][Shift][S]"; a key name that is not markup stays as text
  3000. const auto text = juce::String (keys::displayString (chords.front()));
  3001. juce::String out;
  3002. for (const auto& part : juce::StringArray::fromTokens (text, "+", ""))
  3003. {
  3004. if (! hintmarkup::isToken (part.toStdString()))
  3005. return "(" + text + ")";
  3006. out << "[" << part << "]";
  3007. }
  3008. return out;
  3009. }
  3010. void MainComponent::setControlHints()
  3011. {
  3012. auto with = [this] (const juce::String& text, const char* actionId) {
  3013. const auto key = keyMarkup (actionId);
  3014. return key.isEmpty() ? text : text + " " + key;
  3015. };
  3016. ui::setHint (newButton, with (tr ("New project"), "file.new"));
  3017. ui::setHint (openButton, with (tr ("Open a project (.lynx, FL Studio .flp, MIDI)"), "file.open"));
  3018. ui::setHint (saveButton, with (tr ("Save the project"), "file.save") + " " + tr ("save as:") + " " + keyMarkup ("file.saveAs"));
  3019. ui::setHint (exportButton, with (tr ("Export audio: WAV, FLAC or OGG"), "file.export"));
  3020. ui::setHint (undoButton, with (tr ("Undo the last edit"), "edit.undo") + " " + tr ("[RMB] undo history"), true);
  3021. ui::setHint (redoButton, with (tr ("Redo"), "edit.redo") + " " + tr ("[RMB] undo history"), true);
  3022. ui::setHint (pluginPickerButton, with (tr ("Plugin picker: add an instrument or an effect by name"), "panel.quickAdd"));
  3023. ui::setHint (playButton, with (tr ("Play: [LMB] play; again: stop and go back to where it started"), "transport.playStop")
  3024. + " " + keyMarkup ("transport.pause") + " " + tr ("pause"));
  3025. ui::setHint (stopButton, tr ("Stop: [LMB] stop and go back to the start (or the remembered position; again: the start) "
  3026. "[2xLMB] back to the start and all notes off (panic) [RMB] remember seek time"),
  3027. true);
  3028. ui::setHint (recordButton, with (tr ("Record: [LMB] arm, then play to record notes (and audio, when armed) [RMB] what to record"), "transport.record"),
  3029. true);
  3030. ui::setHint (recordMenuButton, tr ("What to record: notes, input audio, count-in, overdub or replace, quantise [LMB] menu"), true);
  3031. ui::setHint (patternModeButton, with (tr ("Pattern mode: plays the current pattern in a loop [RMB] show the Channel Rack"), "transport.toggleMode"));
  3032. ui::setHint (songModeButton, with (tr ("Song mode: plays the Playlist arrangement [RMB] show the Playlist"), "transport.toggleMode"));
  3033. ui::setHint (metronomeButton, with (tr ("Metronome: clicks on every beat while playing [RMB] volume and options"), "transport.metronome"), true);
  3034. ui::setHint (countInButton, with (tr ("Count-in: one bar of clicks before recording starts (the menu has more lengths)"), "record.countIn"));
  3035. ui::setHint (waitInputButton, with (tr ("Wait for input: recording starts with the first note you play"), "record.waitForInput"));
  3036. ui::setHint (typingPianoButton, with (tr ("Typing keyboard to piano: Z..M and Q..P play the selected channels; letter shortcuts pause"),
  3037. "view.typingPiano"));
  3038. ui::setHint (gridBox, tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  3039. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"),
  3040. true);
  3041. ui::setHint (patternBox, tr ("Current pattern: what the Channel Rack and Piano Roll edit and Pattern mode plays [LMB] choose [Wheel] step "
  3042. "[F4] next empty [F2] rename"));
  3043. ui::setHint (newPatternButton, tr ("New pattern: an empty pattern after the last one"));
  3044. ui::setHint (patternMenuButton, tr ("Pattern menu: rename, color, length, clone, insert, split by channel, delete"), true);
  3045. const char* panelHelp[] = { TR_NOOP ("the arrangement: clips of patterns, audio and automation on tracks"),
  3046. TR_NOOP ("the instruments and their step sequencer"),
  3047. TR_NOOP ("the notes of the selected channel in the current pattern"),
  3048. TR_NOOP ("inserts, effects and routing"),
  3049. TR_NOOP ("samples, presets, plugins and projects to drag in") };
  3050. for (int i = 0; i < workspace::panelCount; ++i)
  3051. ui::setHint (panelButtons[(std::size_t) i],
  3052. with (panelName ((Panel) i) + ": " + tr (panelHelp[i]) + " " + tr ("[LMB] show, focus or hide [RMB] maximized"),
  3053. panelAction ((Panel) i)));
  3054. setQuickTips();
  3055. }
  3056. std::vector<std::pair<juce::Rectangle<int>, juce::String>> MainComponent::getQuickTipsForSnapshot()
  3057. {
  3058. std::vector<std::pair<juce::Rectangle<int>, juce::String>> tips;
  3059. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  3060. for (auto* child : c.getChildren())
  3061. {
  3062. if (! child->isVisible())
  3063. continue;
  3064. if (const auto tip = ui::quickTipOf (*child); tip.isNotEmpty() && ! child->getBounds().isEmpty())
  3065. tips.emplace_back (getLocalArea (child->getParentComponent(), child->getBounds()), tip);
  3066. visit (*child);
  3067. }
  3068. };
  3069. visit (*this);
  3070. return tips;
  3071. }
  3072. // the small name bubble of every toolbar control (the hint bar keeps the full description)
  3073. void MainComponent::setQuickTips()
  3074. {
  3075. auto tip = [this] (juce::Component& c, const juce::String& name, const char* actionId = nullptr) {
  3076. ui::setQuickTip (c, name, actionId != nullptr ? shortcutText (actionId).trim() : juce::String());
  3077. };
  3078. tip (newButton, tr ("New project"), "file.new");
  3079. tip (openButton, tr ("Open project"), "file.open");
  3080. tip (saveButton, tr ("Save project"), "file.save");
  3081. tip (exportButton, tr ("Export audio"), "file.export");
  3082. tip (undoButton, tr ("Undo"), "edit.undo");
  3083. tip (redoButton, tr ("Redo"), "edit.redo");
  3084. tip (pluginPickerButton, tr ("Plugin picker"), "panel.quickAdd");
  3085. tip (playButton, tr ("Play"), "transport.playStop");
  3086. tip (stopButton, tr ("Stop"));
  3087. tip (recordButton, tr ("Record"), "transport.record");
  3088. tip (recordMenuButton, tr ("Recording options"));
  3089. tip (patternModeButton, tr ("Pattern mode"), "transport.toggleMode");
  3090. tip (songModeButton, tr ("Song mode"), "transport.toggleMode");
  3091. tip (metronomeButton, tr ("Metronome"), "transport.metronome");
  3092. tip (countInButton, tr ("Count-in"), "record.countIn");
  3093. tip (waitInputButton, tr ("Wait for input"), "record.waitForInput");
  3094. tip (typingPianoButton, tr ("Typing keyboard to piano"), "view.typingPiano");
  3095. tip (tempoDisplay, tr ("Tempo (BPM)"));
  3096. tip (timeDisplay, tr ("Song time"));
  3097. tip (songPosition, tr ("Song position"));
  3098. tip (masterVolume, tr ("Master volume"));
  3099. tip (masterPitch, tr ("Master pitch"));
  3100. tip (gridBox, tr ("Snap"));
  3101. tip (patternBox, tr ("Pattern"));
  3102. tip (newPatternButton, tr ("New pattern"));
  3103. tip (patternMenuButton, tr ("Pattern options"));
  3104. tip (perfMeter, tr ("CPU, memory and polyphony"));
  3105. tip (output, tr ("Output monitor"));
  3106. tip (swingSlider, tr ("Swing"));
  3107. tip (rackFilterBox, tr ("Channel filter group"));
  3108. tip (rackGraphButton, tr ("Graph editor"));
  3109. tip (rackPianoRollButton, tr ("Piano-roll view"), "rack.pianoRollView");
  3110. tip (rackLoopButton, tr ("Channel looping"));
  3111. tip (rackLoopStarterButton, tr ("Loop Starter"));
  3112. for (int i = 0; i < workspace::panelCount; ++i)
  3113. tip (panelButtons[(std::size_t) i], tr (panelName ((Panel) i)), panelAction ((Panel) i));
  3114. }
  3115. void MainComponent::timerCallback()
  3116. {
  3117. const uitrace::Scope trace ("MainComponent timer", false);
  3118. {
  3119. const uitrace::Scope part ("timer: toolbar displays", false);
  3120. output.update();
  3121. timeDisplay.update();
  3122. songPosition.update();
  3123. masterVolume.update();
  3124. masterPitch.update();
  3125. updateRecordQuantise();
  3126. }
  3127. if (engine.isModified() != lastModified)
  3128. {
  3129. const uitrace::Scope part ("timer: title", false);
  3130. lastModified = engine.isModified();
  3131. updateTitle();
  3132. }
  3133. // the Browser's "Project folder" follows the project's file (.lynx, or the .flp it was imported from)
  3134. const uitrace::Scope partFolders ("timer: project folder / recording target", false);
  3135. browser.setProjectFile (currentFile != juce::File() ? currentFile : importedFlpFile);
  3136. // and so does where audio is recorded ("<project folder>/Audio/Recorded", FL-like take names)
  3137. engine.setRecordingTarget (recordingFolderFor (currentFile != juce::File() ? currentFile : importedFlpFile),
  3138. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String());
  3139. // a backup copy every few minutes (Settings › General) when there are changes
  3140. // (not in the middle of a recording: FL also postpones the timed backup until the transport is free)
  3141. if (autosaveMinutes > 0 && ++autosaveTicks >= 30 * 60 * autosaveMinutes && ! engine.isRecording())
  3142. {
  3143. autosaveTicks = 0;
  3144. if (engine.isModified())
  3145. autosave();
  3146. }
  3147. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.finished != scansSeen)
  3148. {
  3149. scansSeen = scan.finished;
  3150. ui::postHint ({ scan.found == 1 ? tr ("Plugin scan finished: 1 new plugin.")
  3151. : tr ("Plugin scan finished: {0} new plugins.", { juce::String (scan.found) }), {}, false, false },
  3152. 6000);
  3153. }
  3154. // a hosted plugin crashed inside a call: it was switched off (bypassed / silent) and LYNX kept running
  3155. if (const auto crashes = pluginCrashCount(); crashes != pluginCrashesSeen)
  3156. {
  3157. pluginCrashesSeen = crashes;
  3158. juce::StringArray names, lines;
  3159. for (const auto& c : pluginCrashes())
  3160. {
  3161. const auto name = juce::String::fromUTF8 (c.plugin.c_str());
  3162. names.addIfNotAlreadyThere (name);
  3163. lines.add (juce::Time::getCurrentTime().toISO8601 (true) + " " + name + " " + crashguard::describe (c.code) + " 0x"
  3164. + juce::String::toHexString ((juce::int64) c.code));
  3165. }
  3166. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (lines[lines.size() - 1] + "\n");
  3167. juce::AlertWindow::showMessageBoxAsync (
  3168. juce::MessageBoxIconType::WarningIcon, tr ("Plugin crashed"),
  3169. tr ("The plugin \"{0}\" crashed and was switched off, so LYNX SHARE and your project kept running (the effect is bypassed, an "
  3170. "instrument stays silent). Save your project; the plugin loads again the next time you open it.",
  3171. { names[names.size() - 1] }));
  3172. }
  3173. auto& transport = engine.getTransport();
  3174. if (! heldKeys.empty())
  3175. {
  3176. if (! juce::Process::isForegroundProcess()) // switched to another app with keys down: no key-up will come
  3177. heldKeys.releaseAll();
  3178. else // keys released while another window (a detached panel, a dialog) had the focus
  3179. keyStateChanged (false);
  3180. }
  3181. // hint bar: a gesture's own posted hint, else the control under the mouse (while it is dragged, the
  3182. // control that was pressed, at the point it was pressed, so its value updates live); MIDI learn and
  3183. // recording states first
  3184. if (! hintsFrozen)
  3185. {
  3186. const uitrace::Scope part ("timer: hint", false);
  3187. ui::Hint hint;
  3188. bool live = false;
  3189. if (engine.isLearningMidi())
  3190. hint.text = tr ("Move a knob/fader on the MIDI controller to link it to the parameter...");
  3191. else if (engine.isWaitingForInput() || engine.isCountingIn())
  3192. hint.text = idleHint();
  3193. else if (auto posted = ui::postedHint())
  3194. {
  3195. hint = *posted;
  3196. live = true;
  3197. }
  3198. else if (isShowing())
  3199. {
  3200. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  3201. if (auto* under = source.getComponentUnderMouse())
  3202. {
  3203. live = source.isDragging();
  3204. const auto at = live ? source.getLastMouseDownPosition() : source.getScreenPosition();
  3205. hint = ui::hintFor (under, under->getLocalPoint (nullptr, at).roundToInt());
  3206. }
  3207. }
  3208. if (hint.isEmpty())
  3209. {
  3210. hint.text = idleHint();
  3211. live = false;
  3212. }
  3213. hintBar.setHint (hint, live && hint.value.isNotEmpty());
  3214. if (++tweakTicks >= 3) // 10 times a second
  3215. {
  3216. tweakTicks = 0;
  3217. refreshTweakReadout();
  3218. }
  3219. }
  3220. const auto playing = transport.playing.load();
  3221. playButton.setToggleState (playing, juce::dontSendNotification);
  3222. // CPU / memory / polyphony, a few times a second
  3223. if (++meterTicks >= 8 && perfMeter.isVisible() && ! hintsFrozen)
  3224. {
  3225. const uitrace::Scope part ("timer: performance meter", false);
  3226. meterTicks = 0;
  3227. const auto held = (int) heldKeys.size();
  3228. const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
  3229. perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
  3230. const auto rt = engine.getRtStats().snapshot();
  3231. juce::StringArray heaviest;
  3232. for (const auto& u : engine.getHeaviestUnits())
  3233. if (heaviest.size() < 3 && u.load >= 0.01)
  3234. heaviest.add (u.name + " " + juce::String (juce::roundToInt (u.load * 100.0)) + "%");
  3235. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  3236. perfMeter.setRealtime (rt.overBudget, rt.lateCalls, engine.getRtStats().takeWindowMaxLoad(), heaviest,
  3237. device != nullptr ? device->getXRunCount() : -1);
  3238. // dropouts on Windows shared mode: suggest the interface's ASIO driver (round 160), worked out once per device type
  3239. if (device != nullptr && (rt.overBudget > 0 || rt.lateCalls > 0) && device->getTypeName() != driverTipType)
  3240. {
  3241. driverTipType = device->getTypeName();
  3242. std::vector<std::string> asio;
  3243. for (auto* type : engine.getDeviceManager().getAvailableDeviceTypes())
  3244. if (type->getTypeName() == "ASIO")
  3245. for (const auto& name : type->getDeviceNames())
  3246. asio.push_back (name.toStdString());
  3247. perfMeter.setDriverTip (juce::String::fromUTF8 (prefs::suggestedAsioDriver (driverTipType.toStdString(), asio).c_str()));
  3248. }
  3249. // Linux: the first dropouts without real-time priority explain how to get it, once per installation (round 161)
  3250. if (device != nullptr && ! realtimeHintChecked && (rt.overBudget > 0 || device->getXRunCount() > 0)
  3251. && lynx::rt::status() == lynx::rt::Status::denied)
  3252. {
  3253. realtimeHintChecked = true;
  3254. if (lynx::rt::shouldShowHint (PluginHost::settingsFolder().getChildFile ("realtime-hint-shown")))
  3255. juce::AlertWindow::showMessageBoxAsync (
  3256. juce::MessageBoxIconType::InfoIcon, tr ("Real-time priority"),
  3257. 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"
  3258. "- install rtkit (package \"rtkit\"; most desktops already have it), or\n"
  3259. "- add yourself to the \"audio\" group with an rtprio limit in /etc/security/limits.d (as for JACK),\n\n"
  3260. "then log out and in again. LYNX SHARE never needs root. Options > Audio settings shows the current state."));
  3261. }
  3262. }
  3263. if (++midiInputTicks % 30 == 1) // the open MIDI inputs, once a second
  3264. midiLightInputs = engine.getActiveMidiInputs();
  3265. midiLight.update (engine.getMidiActivity(), midiLightInputs);
  3266. // If a closed dialog left the main window without a focused component, take it back so the PC keyboard
  3267. // keeps playing. Only while the main window itself is the active one: another LYNX window (Audio editor,
  3268. // Quick-add palette, a plugin's editor, a detached panel) keeps its focus (issue #4: grabbing it here, 30
  3269. // times a second, pulled the main window to the front and closed the plugins' drop-down menus).
  3270. if (shouldReclaimKeyboardFocus())
  3271. grabKeyboardFocus();
  3272. }
  3273. bool MainComponent::shouldReclaimKeyboardFocus()
  3274. {
  3275. auto* peer = getPeer();
  3276. return ! hasKeyboardFocus (true) && isShowing() && peer != nullptr && peer->isFocused() && juce::Process::isForegroundProcess()
  3277. && juce::Component::getCurrentlyModalComponent() == nullptr && ! workspace.isDetachedWindowActive();
  3278. }
  3279. void MainComponent::updateTitle()
  3280. {
  3281. repaint (titleArea); // the project name in the toolbar
  3282. if (! engine.isModified()) // what is on disk now: the reference for "unused recordings" after a Discard
  3283. savedSamples = safety::referencedSamples (engine.getSong());
  3284. if (auto* window = getTopLevelComponent())
  3285. window->setName ((engine.isModified() ? "* " : "")
  3286. + (projectName.isNotEmpty() ? "LYNX SHARE - " + projectName : juce::String ("LYNX SHARE")) + importedSuffix);
  3287. }
  3288. std::unique_ptr<juce::AlertWindow> MainComponent::makeConfirmDiscardWindow()
  3289. {
  3290. auto window = std::make_unique<juce::AlertWindow> (tr ("Save changes?"), tr ("The project has unsaved changes."),
  3291. juce::MessageBoxIconType::QuestionIcon);
  3292. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3293. window->addButton (tr ("Discard"), 2);
  3294. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3295. return window;
  3296. }
  3297. void MainComponent::confirmDiscard (std::function<void()> then)
  3298. {
  3299. if (! engine.isModified())
  3300. {
  3301. offerToDeleteUnusedRecordings (true, std::move (then));
  3302. return;
  3303. }
  3304. auto* window = makeConfirmDiscardWindow().release();
  3305. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
  3306. if (result == 1)
  3307. {
  3308. save (false);
  3309. if (! engine.isModified()) // saved (did not cancel "save as")
  3310. offerToDeleteUnusedRecordings (true, then);
  3311. }
  3312. else if (result == 2)
  3313. offerToDeleteUnusedRecordings (false, then);
  3314. }),
  3315. true);
  3316. }
  3317. juce::File MainComponent::recordingFolderFor (const juce::File& projectFile) const
  3318. {
  3319. // FL records into the project data folder's "Audio\Recorded" (REA round 134); LYNX's data folder is the folder of
  3320. // the project file. Unsaved projects record into the global recordings folder.
  3321. return projectFile == juce::File() ? AudioEngine::defaultRecordingFolder()
  3322. : projectFile.getParentDirectory().getChildFile (safety::recordedSubfolder);
  3323. }
  3324. namespace
  3325. {
  3326. // FL's Keep / Delete question about recorded files nothing uses (FLEngine FUN_00ed1380, REA round 134)
  3327. void askKeepOrDelete (const juce::String& message, const std::vector<juce::File>& files, std::function<void (bool)> done)
  3328. {
  3329. juce::String list;
  3330. for (std::size_t i = 0; i < files.size() && i < 8; ++i)
  3331. list << "\n " << files[i].getFileName();
  3332. if (files.size() > 8)
  3333. list << "\n " << tr ("...and {0} more", { juce::String ((int) files.size() - 8) });
  3334. auto* w = new juce::AlertWindow (tr ("Unused recordings"), message + list, juce::MessageBoxIconType::QuestionIcon);
  3335. w->addButton (tr ("Keep"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3336. w->addButton (tr ("Delete"), 1);
  3337. w->enterModalState (true, juce::ModalCallbackFunction::create ([done] (int result) { done (result == 1); }), true);
  3338. }
  3339. // to the recycle bin when the system has one (FL's "Delete recorded files to recycle bin")
  3340. int removeFiles (const std::vector<juce::File>& files)
  3341. {
  3342. int removed = 0;
  3343. for (const auto& f : files)
  3344. removed += f.existsAsFile() && (f.moveToTrash() || f.deleteFile());
  3345. return removed;
  3346. }
  3347. } // namespace
  3348. void MainComponent::offerToDeleteUnusedRecordings (bool keepsCurrentState, std::function<void()> then)
  3349. {
  3350. // the takes of this session the project on disk will not use: deleted takes, undone recordings, a project closed
  3351. // without saving (FL: "You created ... sample file(s) that are no longer used if the project isn't saved")
  3352. std::vector<std::string> recorded;
  3353. for (const auto& f : engine.getSessionRecordings())
  3354. if (f.existsAsFile())
  3355. recorded.push_back (f.getFullPathName().toStdString());
  3356. const auto referenced = keepsCurrentState ? safety::referencedSamples (engine.getSong()) : savedSamples;
  3357. std::vector<juce::File> unused;
  3358. for (const auto& path : safety::unusedRecordings (recorded, referenced))
  3359. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  3360. if (unused.empty() || ! askUnusedRecordings || ! persistent)
  3361. {
  3362. then();
  3363. return;
  3364. }
  3365. askKeepOrDelete (unused.size() == 1 ? tr ("You recorded 1 audio file that this project will not use.")
  3366. : tr ("You recorded {0} audio files that this project will not use.", { juce::String ((int) unused.size()) }),
  3367. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused, then] (bool remove) {
  3368. if (safe == nullptr)
  3369. return;
  3370. if (remove)
  3371. removeFiles (unused);
  3372. safe->engine.forgetRecordings (unused); // asked once per file
  3373. then();
  3374. });
  3375. }
  3376. void MainComponent::deleteUnusedRecordingsAndSave()
  3377. {
  3378. // FL's Tools › Macros "Delete unused files and save project", for the files this project recorded: every take in
  3379. // its recording folder (and this session's takes elsewhere) that no channel or clip uses
  3380. if (currentFile == juce::File())
  3381. {
  3382. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Delete unused recordings"),
  3383. tr ("Save the project first: its recordings are kept next to it, in {0}.", { juce::String (safety::recordedSubfolder) }));
  3384. return;
  3385. }
  3386. std::vector<std::string> recorded;
  3387. const auto stem = currentFile.getFileNameWithoutExtension() + "_";
  3388. for (const auto& f : recordingFolderFor (currentFile).findChildFiles (juce::File::findFiles, false, "*.wav"))
  3389. if (f.getFileName().startsWithIgnoreCase (stem)) // other projects in the same folder record there too
  3390. recorded.push_back (f.getFullPathName().toStdString());
  3391. for (const auto& f : engine.getSessionRecordings())
  3392. if (f.existsAsFile())
  3393. recorded.push_back (f.getFullPathName().toStdString());
  3394. std::vector<juce::File> unused;
  3395. for (const auto& path : safety::unusedRecordings (recorded, safety::referencedSamples (engine.getSong())))
  3396. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  3397. if (unused.empty())
  3398. {
  3399. save (false);
  3400. ui::postHint ({ tr ("No unused recordings. Project saved."), {}, false, false }, 4000);
  3401. return;
  3402. }
  3403. askKeepOrDelete (tr ("This project has {0} unused recording(s). Deleting them cannot be undone (they go to the recycle bin).",
  3404. { juce::String ((int) unused.size()) }),
  3405. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused] (bool remove) {
  3406. if (safe == nullptr)
  3407. return;
  3408. if (remove)
  3409. {
  3410. const auto n = removeFiles (unused);
  3411. safe->engine.forgetRecordings (unused);
  3412. ui::postHint ({ tr ("Deleted {0} unused recording(s).", { juce::String (n) }), {}, false, false }, 4000);
  3413. }
  3414. safe->save (false);
  3415. });
  3416. }
  3417. namespace
  3418. {
  3419. juce::String projectStem (const juce::String& projectName)
  3420. {
  3421. return projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled");
  3422. }
  3423. // the backup folder's projects with their modification times (for rotation and "revert to last backup")
  3424. std::vector<safety::BackupFile> backupFiles (const juce::File& folder)
  3425. {
  3426. std::vector<safety::BackupFile> files;
  3427. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, juce::String ("*") + ProjectFile::extension))
  3428. files.push_back ({ f.getFileNameWithoutExtension().toStdString(), f.getLastModificationTime().toMilliseconds() });
  3429. return files;
  3430. }
  3431. // "Song (autosaved on 2026-10-20 at 14h19)" in `folder`, "_2"... when that minute is taken (FL's naming, REA round 118)
  3432. juce::File newBackupFile (const juce::File& folder, const juce::String& stem, safety::BackupKind kind)
  3433. {
  3434. const auto now = juce::Time::getCurrentTime();
  3435. const auto name = safety::backupName (stem.toStdString(), kind, now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(), now.getMinutes());
  3436. const auto unique = safety::uniqueName (name, [&folder] (const std::string& n) {
  3437. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  3438. });
  3439. return folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ProjectFile::extension);
  3440. }
  3441. } // namespace
  3442. void MainComponent::autosave()
  3443. {
  3444. // backup copy of the open project, so work isn't lost if something crashes ("Song (autosaved on 2026-10-20 at
  3445. // 14h19).lynx" in the backup folder, like FL's Backup folder); only the newest few of each project are kept
  3446. // The plugins' settings are read here (they answer on the message thread); writing the file (the big part:
  3447. // every plugin's state, encoded) runs on a thread of its own, so the timed backup no longer freezes the screen
  3448. // (round 151: 180 ms every two minutes on a project with 71 plugins). One at a time.
  3449. if (autosaveRunning->load())
  3450. return;
  3451. const auto folder = autosaveFolder();
  3452. folder.createDirectory();
  3453. const auto stem = projectStem (projectName);
  3454. {
  3455. const uitrace::Scope trace ("autosave: plugin states", false);
  3456. engine.capturePluginStates();
  3457. }
  3458. auto copy = std::make_shared<Song> (engine.getSong());
  3459. const auto file = newBackupFile (folder, stem, safety::BackupKind::autosaved);
  3460. autosaveRunning->store (true);
  3461. juce::Thread::launch ([copy, file, running = autosaveRunning, safe = juce::Component::SafePointer<MainComponent> (this), stem] {
  3462. juce::String error;
  3463. const auto ok = ProjectFile::save (*copy, file, error);
  3464. running->store (false);
  3465. juce::MessageManager::callAsync ([safe, ok, error, stem] {
  3466. if (safe == nullptr)
  3467. return;
  3468. if (! ok)
  3469. ui::postHint ({ tr ("Autosave failed: {0}", { error }), {}, false, false }, 6000);
  3470. else
  3471. safe->rotateBackups (stem);
  3472. });
  3473. });
  3474. }
  3475. void MainComponent::rotateBackups (const juce::String& stem)
  3476. {
  3477. const auto folder = autosaveFolder();
  3478. for (const auto& old : safety::backupsToRemove (backupFiles (folder), stem.toStdString(), autosaveKeep))
  3479. {
  3480. const auto f = folder.getChildFile (juce::String::fromUTF8 (old.c_str()) + ProjectFile::extension);
  3481. f.setReadOnly (false); // (FL clears the read-only flag before deleting an old backup too)
  3482. f.deleteFile();
  3483. }
  3484. }
  3485. void MainComponent::keepOverwrittenCopy (const juce::File& file)
  3486. {
  3487. // FL moves the file a save replaces into its Backup folder as "Song (overwritten on ... at ...)"; LYNX copies it
  3488. // (the save itself still goes through a temporary file and a rename)
  3489. const auto folder = autosaveFolder();
  3490. if (! file.existsAsFile() || file.isAChildOf (folder))
  3491. return;
  3492. folder.createDirectory();
  3493. const auto stem = projectStem (file.getFileNameWithoutExtension());
  3494. if (file.copyFileTo (newBackupFile (folder, stem, safety::BackupKind::overwritten)))
  3495. rotateBackups (stem);
  3496. }
  3497. void MainComponent::saveNewVersion()
  3498. {
  3499. // FL's "Save new version": Song.flp -> Song_2.flp -> Song_3.flp, next to the current file
  3500. if (currentFile == juce::File())
  3501. {
  3502. save (true);
  3503. return;
  3504. }
  3505. const auto folder = currentFile.getParentDirectory();
  3506. const auto name = safety::nextVersionName (currentFile.getFileNameWithoutExtension().toStdString(), [&folder] (const std::string& n) {
  3507. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  3508. });
  3509. const auto file = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  3510. juce::String error;
  3511. engine.capturePluginStates();
  3512. if (! ProjectFile::save (engine.getSong(), file, error))
  3513. {
  3514. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3515. return;
  3516. }
  3517. engine.markSaved();
  3518. rememberRecent (file);
  3519. currentFile = file;
  3520. projectName = file.getFileNameWithoutExtension();
  3521. importedSuffix = {};
  3522. updateTitle();
  3523. ui::postHint ({ tr ("Saved as a new version: {0}", { file.getFileName() }), {}, false, false }, 5000);
  3524. }
  3525. void MainComponent::revertToLastBackup()
  3526. {
  3527. const auto stem = projectStem (projectName);
  3528. const auto name = safety::newestBackup (backupFiles (autosaveFolder()), stem.toStdString());
  3529. if (name.empty())
  3530. {
  3531. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Revert to last backup"),
  3532. tr ("There is no backup of this project yet."));
  3533. return;
  3534. }
  3535. const auto backup = autosaveFolder().getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  3536. const auto when = backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M");
  3537. auto* w = new juce::AlertWindow (tr ("Revert to last backup"),
  3538. tr ("Replace the open project with its backup from {0}?\n{1}\n\nThe project file itself only changes when you save.",
  3539. { when, backup.getFileName() }),
  3540. juce::MessageBoxIconType::QuestionIcon);
  3541. w->addButton (tr ("Revert"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3542. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3543. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup] (int result) {
  3544. if (safe == nullptr || result != 1)
  3545. return;
  3546. juce::String error;
  3547. auto song = ProjectFile::load (backup, error);
  3548. if (! song)
  3549. {
  3550. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3551. return;
  3552. }
  3553. safe->engine.getPluginHost().applySubstitutes (*song);
  3554. safe->engine.stop();
  3555. safe->engine.rewind();
  3556. safe->engine.setSong (std::move (*song));
  3557. safe->engine.markModified(); // Save writes it back to the project's own file
  3558. safe->updateTitle();
  3559. safe->playlist.showSongAfterOpen();
  3560. }),
  3561. true);
  3562. }
  3563. sessionui::Context MainComponent::sessionContext()
  3564. {
  3565. return { engine, currentFile, projectName, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::File& project) {
  3566. if (safe != nullptr)
  3567. safe->openLynxProject (project);
  3568. } };
  3569. }
  3570. liveui::Context MainComponent::liveContext()
  3571. {
  3572. return { engine, *live, currentFile, [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  3573. if (safe != nullptr)
  3574. safe->confirmDiscard (std::move (then));
  3575. } };
  3576. }
  3577. void MainComponent::startLiveFromCommandLine()
  3578. {
  3579. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  3580. auto value = [&] (const char* flag) {
  3581. const auto at = cli.indexOf (flag);
  3582. return at >= 0 && at + 1 < cli.size() ? cli[at + 1].unquoted() : juce::String();
  3583. };
  3584. auto o = LiveSessionManager::Options();
  3585. o.name = value ("--live-name").isNotEmpty() ? value ("--live-name") : liveui::myName();
  3586. o.projectFile = currentFile;
  3587. if (const auto relay = value ("--live-relay"); relay.isNotEmpty())
  3588. o.relay = relay;
  3589. // round 169j: --live-chat "text" (sent once in), --live-follow (follow the host's transport), --live-resume (the
  3590. // host resumes its interrupted session without asking)
  3591. if (const auto text = value ("--live-chat"); text.isNotEmpty())
  3592. juce::Timer::callAfterDelay (9000, [safe = juce::Component::SafePointer<MainComponent> (this), text] {
  3593. if (safe != nullptr)
  3594. {
  3595. safe->live->sendChat (text);
  3596. liveui::showChat (*safe->live);
  3597. }
  3598. });
  3599. if (cli.contains ("--live-follow"))
  3600. juce::Timer::callAfterDelay (8500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  3601. if (safe != nullptr)
  3602. safe->live->setFollowTransport (true);
  3603. });
  3604. if (cli.contains ("--live-resume"))
  3605. {
  3606. o.projectFile = juce::File();
  3607. o.autoAccept = true;
  3608. if (! live->resumeHost (LiveSessionManager::defaultJournal(), o))
  3609. platform::testModeLog ("live session: nothing to resume");
  3610. return;
  3611. }
  3612. if (! cli.contains ("--live-host") && ! cli.contains ("--live-join"))
  3613. {
  3614. if (! platform::testMode())
  3615. liveui::offerResume (liveContext());
  3616. return;
  3617. }
  3618. if (const auto codeFile = value ("--live-host"); codeFile.isNotEmpty())
  3619. {
  3620. o.autoAccept = true; // (scripted: nobody to click "Let them in")
  3621. live->start (o);
  3622. auto poll = std::make_shared<std::function<void (int)>>();
  3623. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), codeFile, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  3624. if (safe == nullptr)
  3625. return;
  3626. if (safe->live->getState() == LiveSessionManager::State::live)
  3627. return (void) juce::File (codeFile).replaceWithText (safe->live->getInviteCode());
  3628. if (safe->live->isActive() && left > 0)
  3629. juce::Timer::callAfterDelay (200, [poll = weak.lock(), left] {
  3630. if (poll != nullptr)
  3631. (*poll) (left - 1);
  3632. });
  3633. else
  3634. juce::File (codeFile).replaceWithText ("ERROR " + safe->live->getStatus());
  3635. };
  3636. (*poll) (150);
  3637. }
  3638. else if (auto code = value ("--live-join"); code.isNotEmpty())
  3639. {
  3640. if (code.startsWith ("@"))
  3641. code = juce::File (code.substring (1)).loadFileAsString().trim();
  3642. live->join (code, o);
  3643. // --live-edit: once in, add a channel of one's own (the GUI check sees it arrive on the host)
  3644. if (cli.contains ("--live-edit"))
  3645. juce::Timer::callAfterDelay (8000, [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name] {
  3646. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  3647. return;
  3648. safe->engine.editSong ([&] (Song& s) {
  3649. ChannelDef c;
  3650. c.name = (name + " synth").toStdString();
  3651. c.instrument = InstrumentKind::synth;
  3652. s.channels.push_back (c);
  3653. });
  3654. });
  3655. }
  3656. }
  3657. void MainComponent::exportPackage()
  3658. {
  3659. // FL's zipped loop package: the project and every sample it uses in one .zip
  3660. const auto stem = projectStem (projectName);
  3661. const auto start = (currentFile != juce::File() ? currentFile.getParentDirectory()
  3662. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory))
  3663. .getChildFile (stem + ".zip");
  3664. fileChooser = std::make_unique<juce::FileChooser> (tr ("Export project with samples"), start, "*.zip");
  3665. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  3666. [safe = juce::Component::SafePointer<MainComponent> (this), stem] (const juce::FileChooser& chooser) {
  3667. auto zip = chooser.getResult();
  3668. if (safe == nullptr || zip == juce::File())
  3669. return;
  3670. zip = zip.withFileExtension (".zip");
  3671. safe->engine.capturePluginStates();
  3672. ProjectPackage::Result result;
  3673. juce::String error;
  3674. if (! ProjectPackage::exportZip (safe->engine.getSong(), stem, zip, result, error))
  3675. {
  3676. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3677. return;
  3678. }
  3679. auto text = tr ("{0} saved with {1} samples.", { zip.getFileName(), juce::String (result.files) });
  3680. if (! result.missing.isEmpty())
  3681. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  3682. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Export project with samples"), text);
  3683. });
  3684. }
  3685. void MainComponent::collectSamples()
  3686. {
  3687. // FL's "Export project data files": copy the samples the project uses into one folder (and use the copies)
  3688. fileChooser = std::make_unique<juce::FileChooser> (tr ("Copy the project's samples to..."),
  3689. currentFile != juce::File() ? currentFile.getParentDirectory()
  3690. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  3691. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  3692. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  3693. const auto folder = chooser.getResult();
  3694. if (safe == nullptr || folder == juce::File())
  3695. return;
  3696. std::map<std::string, std::string> relink;
  3697. ProjectPackage::Result result;
  3698. juce::String error;
  3699. if (! ProjectPackage::collectSamples (safe->engine.getSong(), folder, relink, result, error))
  3700. {
  3701. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not copy"), error);
  3702. return;
  3703. }
  3704. safe->engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  3705. auto text = tr ("{0} samples copied to {1}. The project now uses the copies.", { juce::String (result.files), folder.getFullPathName() });
  3706. if (! result.missing.isEmpty())
  3707. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  3708. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Collect project samples"), text);
  3709. });
  3710. }
  3711. void MainComponent::saveToNewProjectFolder()
  3712. {
  3713. // FL's "Save to new project folder...": <chosen name>/<name>.lynx, so the project gets its own data folder (its
  3714. // recordings go to <name>/Audio/Recorded). This session's takes still in the global recordings folder move along
  3715. // (copied there, the project uses the copies; the originals are then offered for deletion as unused).
  3716. const auto start = currentFile != juce::File() ? currentFile.getParentDirectory()
  3717. : lynx::platform::documentsFolder().getChildFile ("LYNX/Projects");
  3718. start.createDirectory();
  3719. fileChooser = std::make_unique<juce::FileChooser> (tr ("Save to new project folder"),
  3720. start.getChildFile (projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled")),
  3721. juce::String ("*") + ProjectFile::extension);
  3722. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  3723. const auto chosen = chooser.getResult();
  3724. if (safe == nullptr || chosen == juce::File())
  3725. return;
  3726. const auto name = chosen.getFileNameWithoutExtension();
  3727. auto folder = chosen.getParentDirectory().getChildFile (name);
  3728. if (folder.exists() && ! folder.findChildFiles (juce::File::findFilesAndDirectories, false).isEmpty())
  3729. folder = folder.getNonexistentSibling (false);
  3730. if (! folder.createDirectory())
  3731. {
  3732. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  3733. tr ("Could not create the folder {0}", { folder.getFullPathName() }));
  3734. return;
  3735. }
  3736. auto& self = *safe;
  3737. const auto recorded = folder.getChildFile (safety::recordedSubfolder);
  3738. std::map<std::string, std::string> relink;
  3739. const auto used = safety::referencedSamples (self.engine.getSong());
  3740. for (const auto& take : self.engine.getSessionRecordings())
  3741. if (take.existsAsFile() && take.isAChildOf (AudioEngine::defaultRecordingFolder())
  3742. && std::any_of (used.begin(), used.end(), [&take] (const std::string& p) { return safety::samePath (p, take.getFullPathName().toStdString()); }))
  3743. {
  3744. recorded.createDirectory();
  3745. const auto copy = recorded.getNonexistentChildFile (take.getFileNameWithoutExtension(), take.getFileExtension(), false);
  3746. if (take.copyFileTo (copy))
  3747. relink[take.getFullPathName().toStdString()] = copy.getFullPathName().toStdString();
  3748. }
  3749. if (! relink.empty())
  3750. self.engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  3751. const auto file = folder.getChildFile (name + ProjectFile::extension);
  3752. juce::String error;
  3753. self.engine.capturePluginStates();
  3754. if (! ProjectFile::save (self.engine.getSong(), file, error))
  3755. {
  3756. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3757. return;
  3758. }
  3759. self.engine.markSaved();
  3760. self.rememberRecent (file);
  3761. self.currentFile = file;
  3762. self.projectName = name;
  3763. self.importedSuffix = {};
  3764. self.updateTitle();
  3765. ui::postHint ({ tr ("Saved in its own folder: {0}", { folder.getFullPathName() }), {}, false, false }, 5000);
  3766. });
  3767. }
  3768. void MainComponent::startSession()
  3769. {
  3770. // Like FL's backup on crash: a marker exists while LYNX runs; finding one at start means the last session
  3771. // ended without closing (crash, power loss), so the newest backup written during it is offered.
  3772. sessionLock = std::make_unique<juce::InterProcessLock> ("LYNX-ui-session");
  3773. if (! sessionLock->enter (0))
  3774. {
  3775. sessionLock.reset(); // another LYNX window is running: it owns the marker
  3776. return;
  3777. }
  3778. sessionMarker = lynx::platform::settingsFile ("session-running.txt");
  3779. if (sessionMarker.existsAsFile())
  3780. {
  3781. const auto previousStart = juce::Time (sessionMarker.loadFileAsString().trim().getLargeIntValue());
  3782. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this), previousStart] {
  3783. if (safe != nullptr)
  3784. safe->checkPreviousSession (previousStart);
  3785. });
  3786. }
  3787. sessionMarker.getParentDirectory().createDirectory();
  3788. sessionMarker.replaceWithText (juce::String (juce::Time::getCurrentTime().toMilliseconds()));
  3789. // takes that were recording when LYNX stopped (crash, power loss, closed while recording): after the backup offer
  3790. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  3791. if (safe != nullptr)
  3792. safe->checkInterruptedTakes();
  3793. });
  3794. }
  3795. void MainComponent::checkInterruptedTakes()
  3796. {
  3797. if (juce::Component::getCurrentlyModalComponent() != nullptr) // a dialog is open (the backup offer): ask later
  3798. {
  3799. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  3800. if (safe != nullptr)
  3801. safe->checkInterruptedTakes();
  3802. });
  3803. return;
  3804. }
  3805. std::vector<juce::File> folders { engine.getRecordingFolder() };
  3806. const auto takes = engine.recoverInterruptedTakes (folders);
  3807. if (takes.empty())
  3808. return;
  3809. juce::StringArray names;
  3810. for (const auto& j : takes)
  3811. names.add (juce::File (juce::String::fromUTF8 (j.wav.c_str())).getFileName());
  3812. const auto folder = juce::File (juce::String::fromUTF8 (takes.front().wav.c_str())).getParentDirectory();
  3813. auto* w = new juce::AlertWindow (tr ("Recordings recovered"),
  3814. tr ("LYNX SHARE was recording when it stopped. These takes were saved and repaired:\n{0}\n\nPut them on the Playlist "
  3815. "where they were recorded?", { names.joinIntoString ("\n") }),
  3816. juce::MessageBoxIconType::InfoIcon);
  3817. w->addButton (tr ("Put them on the Playlist"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3818. w->addButton (tr ("Show the folder"), 2);
  3819. w->addButton (tr ("Keep the files only"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3820. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), takes, folder] (int result) {
  3821. if (safe == nullptr)
  3822. return;
  3823. if (result == 1)
  3824. {
  3825. const auto placed = safe->engine.placeRecoveredTakes (takes);
  3826. ui::postHint ({ tr ("{0} recovered take(s) placed on the Playlist", { juce::String (placed) }), {}, false, false }, 5000);
  3827. }
  3828. else
  3829. {
  3830. if (result == 2)
  3831. folder.startAsProcess();
  3832. safe->engine.forgetInterruptedTakes (takes);
  3833. }
  3834. }),
  3835. true);
  3836. }
  3837. void MainComponent::checkPreviousSession (juce::Time sessionStart)
  3838. {
  3839. if (juce::Component::getCurrentlyModalComponent() != nullptr) // the setup wizard or another dialog: ask later
  3840. {
  3841. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this), sessionStart] {
  3842. if (safe != nullptr)
  3843. safe->checkPreviousSession (sessionStart);
  3844. });
  3845. return;
  3846. }
  3847. const auto folder = autosaveFolder();
  3848. const auto name = safety::crashRecoveryCandidate (backupFiles (folder), sessionStart.toMilliseconds());
  3849. if (name.empty())
  3850. return; // nothing was saved in that session
  3851. const auto backup = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  3852. auto* w = new juce::AlertWindow (tr ("LYNX SHARE did not close properly"),
  3853. tr ("The last session ended unexpectedly. Open the newest backup it saved?\n{0} ({1})",
  3854. { backup.getFileName(), backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M") }),
  3855. juce::MessageBoxIconType::WarningIcon);
  3856. w->addButton (tr ("Open backup"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3857. w->addButton (tr ("Open backup folder"), 2);
  3858. w->addButton (tr ("Ignore"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3859. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup, folder] (int result) {
  3860. if (safe == nullptr)
  3861. return;
  3862. if (result == 1)
  3863. safe->confirmDiscard ([safe, backup] {
  3864. if (safe != nullptr)
  3865. safe->openLynxProject (backup);
  3866. });
  3867. else if (result == 2)
  3868. folder.startAsProcess();
  3869. }),
  3870. true);
  3871. }
  3872. void MainComponent::newProject (bool askAlways)
  3873. {
  3874. confirmDiscard ([this, askAlways] {
  3875. if (! askAlways && ! newProjectDialogEnabled())
  3876. {
  3877. startNewProject (makeNewProject(), {});
  3878. return;
  3879. }
  3880. showNewProjectDialog ([safe = juce::Component::SafePointer<MainComponent> (this)] (Song song, juce::File file) {
  3881. if (safe != nullptr)
  3882. safe->startNewProject (std::move (song), file);
  3883. });
  3884. });
  3885. }
  3886. void MainComponent::startNewProject (Song song, const juce::File& file)
  3887. {
  3888. engine.stop();
  3889. engine.rewind();
  3890. engine.setSong (std::move (song));
  3891. engine.markCreatedNow(); // Project info › created (a template's own date is kept, as FL does)
  3892. currentFile = juce::File();
  3893. projectName = {};
  3894. importedSuffix = {};
  3895. if (file != juce::File())
  3896. {
  3897. juce::String error;
  3898. file.getParentDirectory().createDirectory();
  3899. if (ProjectFile::save (engine.getSong(), file, error))
  3900. {
  3901. engine.markSaved();
  3902. rememberRecent (file);
  3903. currentFile = file;
  3904. projectName = file.getFileNameWithoutExtension();
  3905. }
  3906. else
  3907. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3908. }
  3909. updateTitle();
  3910. }
  3911. void MainComponent::saveAsTemplate()
  3912. {
  3913. auto* w = new juce::AlertWindow (tr ("Save as template"), tr ("The template appears in File › New project... (saved in {0})", { userTemplatesFolder().getFullPathName() }),
  3914. juce::MessageBoxIconType::NoIcon);
  3915. w->addTextEditor ("name", projectName.isNotEmpty() ? projectName : tr ("My template"));
  3916. w->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3917. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3918. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, safe = juce::Component::SafePointer<MainComponent> (this)] (int result) {
  3919. if (result != 1 || safe == nullptr)
  3920. return;
  3921. safe->engine.capturePluginStates();
  3922. juce::String error;
  3923. if (! saveUserTemplate (safe->engine.getSong(), w->getTextEditorContents ("name"), error))
  3924. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3925. }), true);
  3926. }
  3927. void MainComponent::chooseFileToOpen()
  3928. {
  3929. confirmDiscard ([this] { chooseFileToOpenNow(); });
  3930. }
  3931. void MainComponent::chooseFileToOpenNow()
  3932. {
  3933. fileChooser = std::make_unique<juce::FileChooser> (tr ("Open project"), currentFile.getParentDirectory(),
  3934. juce::String ("*") + ProjectFile::extension + ";*.dawproj;*.flp;*.zip;*.lynxpack;*.mid;*.midi");
  3935. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  3936. [this] (const juce::FileChooser& chooser) {
  3937. if (chooser.getResult().existsAsFile())
  3938. openFile (chooser.getResult());
  3939. });
  3940. }
  3941. void MainComponent::openFile (const juce::File& file)
  3942. {
  3943. juce::String error;
  3944. crashguard::note (("opening project " + file.getFileName()).toStdString()); // session breadcrumb (round 111)
  3945. if (file.hasFileExtension ("zip"))
  3946. {
  3947. // a project package (File › Export project with samples, or FL's zipped loop package): extracted into a
  3948. // folder of its own, then the project inside is opened (its samples are found next to it)
  3949. const auto project = ProjectPackage::extractZip (file, ProjectPackage::defaultExtractRoot(), error);
  3950. if (project == juce::File())
  3951. {
  3952. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3953. return;
  3954. }
  3955. openFile (project);
  3956. return;
  3957. }
  3958. if (file.hasFileExtension (sessionpack::extension))
  3959. {
  3960. // Online Sessions (round 168a): a project a friend sent (opened after a summary) or a part sent back (merged)
  3961. sessionui::openPackage (sessionContext(), file);
  3962. return;
  3963. }
  3964. if (file.hasFileExtension ("mid;midi"))
  3965. {
  3966. auto song = MidiFileIo::loadSong (file, error);
  3967. if (! song)
  3968. {
  3969. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3970. return;
  3971. }
  3972. engine.stop();
  3973. engine.rewind();
  3974. engine.setSong (std::move (*song));
  3975. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  3976. projectName = file.getFileNameWithoutExtension();
  3977. rememberRecent (file);
  3978. importedSuffix = " " + tr ("(imported from MIDI)");
  3979. updateTitle();
  3980. return;
  3981. }
  3982. if (file.hasFileExtension ("flp"))
  3983. {
  3984. if (! persistent) // (command-line modes open synchronously, without scanning)
  3985. {
  3986. importFlp (file);
  3987. return;
  3988. }
  3989. // behind a progress panel (round 112): the project's unknown plugins get a targeted scan of just their files,
  3990. // the samples are decoded off the message thread, the hosted plugins are created one by one with their names
  3991. // shown; the panel's bar never sits still at 0 %
  3992. if (projectLoadRunning())
  3993. return;
  3994. openFlpWithProgress (*this, engine, file, [safe = juce::Component::SafePointer<MainComponent> (this), file] (bool ok, const juce::String& error) {
  3995. if (safe == nullptr)
  3996. return;
  3997. if (! ok)
  3998. {
  3999. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  4000. return;
  4001. }
  4002. safe->flpImported (file);
  4003. });
  4004. return;
  4005. }
  4006. openLynxProject (file);
  4007. }
  4008. void MainComponent::importFlp (const juce::File& file)
  4009. {
  4010. juce::String error;
  4011. loadtrace::begin (file.getFullPathName().toStdString());
  4012. const auto ok = engine.importFlpFile (file, error);
  4013. loadtrace::end();
  4014. if (! ok)
  4015. {
  4016. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  4017. return;
  4018. }
  4019. flpImported (file);
  4020. }
  4021. void MainComponent::flpImported (const juce::File& file)
  4022. {
  4023. {
  4024. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  4025. importedFlpFile = file;
  4026. projectName = file.getFileNameWithoutExtension();
  4027. rememberRecent (file);
  4028. importedSuffix = " " + tr ("(imported from FL Studio)");
  4029. updateTitle();
  4030. playlist.showSongAfterOpen();
  4031. showMissingFiles (true);
  4032. // FL opens Project info when the project's "Show on opening" box is on (event 0x0A, REA round 167g)
  4033. if (engine.getSong().info.showOnOpen && platform::testMode())
  4034. platform::testModeLog ("project info shown on open");
  4035. else if (engine.getSong().info.showOnOpen)
  4036. openSettings ((int) SettingsPage::info);
  4037. }
  4038. }
  4039. void MainComponent::openLynxProject (const juce::File& file)
  4040. {
  4041. juce::String error;
  4042. auto song = ProjectFile::load (file, error);
  4043. if (! song)
  4044. {
  4045. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  4046. return;
  4047. }
  4048. // missing plugins get their LYNX substitute; substitutes whose original is installed now go back to it
  4049. engine.getPluginHost().applySubstitutes (*song);
  4050. engine.stop();
  4051. engine.rewind();
  4052. engine.setSong (std::move (*song));
  4053. currentFile = file;
  4054. importedFlpFile = juce::File();
  4055. projectName = file.getFileNameWithoutExtension();
  4056. importedSuffix = {};
  4057. rememberRecent (file);
  4058. updateTitle();
  4059. playlist.showSongAfterOpen();
  4060. if (persistent)
  4061. {
  4062. showMissingFiles (true);
  4063. if (engine.getSong().info.showOnOpen && platform::testMode())
  4064. platform::testModeLog ("project info shown on open");
  4065. else if (engine.getSong().info.showOnOpen)
  4066. openSettings (1);
  4067. }
  4068. }
  4069. void MainComponent::openSettings (int page)
  4070. {
  4071. const juce::Component::SafePointer<MainComponent> safe (this);
  4072. SettingsHooks hooks;
  4073. hooks.browserFoldersChanged = [safe] {
  4074. if (safe != nullptr)
  4075. safe->browser.reloadUserFolders();
  4076. };
  4077. hooks.getGeneral = [safe] {
  4078. GeneralOptions o;
  4079. if (safe == nullptr)
  4080. return o;
  4081. o.language = i18n::saved();
  4082. o.uiScale = safe->toolbarLayout.uiScale;
  4083. o.compactMenus = theme::menus::compact();
  4084. o.waveSpectral = ui::WaveformCache::spectral;
  4085. o.waveStereo = ui::WaveformCache::stereo;
  4086. o.noteNames = notenames::currentStyle.load();
  4087. o.noteFlats = notenames::currentFlats.load();
  4088. o.reducedEffects = skin::reducedEffects();
  4089. o.gpuRendering = gpuRenderingEnabled();
  4090. o.pluginStyle = skin::forcedStyle();
  4091. o.splash = safe->startup.splash;
  4092. o.startupSound = safe->startup.sound;
  4093. o.scanAtStart = backgroundScanAtStart();
  4094. o.typingPiano = safe->typingPiano;
  4095. o.keepEditorsOpen = ChannelRackComponent::keepEditorsOpen;
  4096. o.selectFirstChannelWithNotes = ChannelRackComponent::selectFirstChannelWithNotes;
  4097. o.alternateUndo = safe->alternateUndo;
  4098. o.rememberSeek = EditorGlobals::get().rememberSeek;
  4099. o.stretchedClipsLoop = stretchedClipsLoop();
  4100. o.editPatternsIn = PlaylistComponent::editPatternsIn;
  4101. o.undoLevels = safe->engine.getUndoLevels();
  4102. o.autosaveMinutes = safe->autosaveMinutes;
  4103. o.autosaveKeep = safe->autosaveKeep;
  4104. o.askUnusedRecordings = safe->askUnusedRecordings;
  4105. o.crossfadesInNewProjects = newProjectDefaults().autoCrossfades;
  4106. o.pluginSandbox = pluginSandboxEnabled();
  4107. o.menuEntry = appImageMenuEntryInstalled();
  4108. o.pluginSubstitutes = pluginSubstitutesEnabled();
  4109. o.crashReports = (int) crashreporter::consent();
  4110. o.checkUpdates = updater::automatic();
  4111. return o;
  4112. };
  4113. hooks.setGeneral = [safe] (const GeneralOptions& o) {
  4114. if (safe == nullptr)
  4115. return;
  4116. auto& self = *safe;
  4117. if (o.uiScale != self.toolbarLayout.uiScale)
  4118. {
  4119. auto layout = self.toolbarLayout;
  4120. layout.uiScale = toolbarlayout::clampScale (o.uiScale);
  4121. self.setToolbarLayout (layout, true);
  4122. }
  4123. theme::menus::setCompact (o.compactMenus);
  4124. if (o.reducedEffects != skin::reducedEffects() || o.pluginStyle != skin::forcedStyle())
  4125. {
  4126. skin::setReducedEffects (o.reducedEffects);
  4127. skin::setForcedStyle (o.pluginStyle);
  4128. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // open editors redraw at once
  4129. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  4130. }
  4131. if (o.noteNames != notenames::currentStyle.load() || o.noteFlats != notenames::currentFlats.load())
  4132. {
  4133. notenames::currentStyle.store (juce::jlimit (0, 2, o.noteNames));
  4134. notenames::currentFlats.store (o.noteFlats);
  4135. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // the keyboards redraw with the new names
  4136. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  4137. }
  4138. if (o.gpuRendering != gpuRenderingEnabled())
  4139. setGpuRenderingEnabled (o.gpuRendering);
  4140. if (o.waveSpectral != ui::WaveformCache::spectral || o.waveStereo != ui::WaveformCache::stereo)
  4141. {
  4142. ui::WaveformCache::spectral = o.waveSpectral;
  4143. ui::WaveformCache::stereo = o.waveStereo;
  4144. ui::WaveformCache::getInstance()->settingsChanged();
  4145. }
  4146. if (o.typingPiano != self.typingPiano)
  4147. self.setTypingPiano (o.typingPiano);
  4148. if (o.scanAtStart != backgroundScanAtStart())
  4149. setBackgroundScanAtStart (o.scanAtStart);
  4150. if (o.pluginSandbox != pluginSandboxEnabled())
  4151. setPluginSandboxEnabled (o.pluginSandbox);
  4152. if (runningAsAppImage() && o.menuEntry != appImageMenuEntryInstalled())
  4153. setAppImageMenuEntry (o.menuEntry);
  4154. if (o.pluginSubstitutes != pluginSubstitutesEnabled())
  4155. setPluginSubstitutesEnabled (o.pluginSubstitutes);
  4156. if (o.crashReports != (int) crashreporter::consent())
  4157. crashreporter::setConsent ((crashreport::Consent) juce::jlimit (0, 2, o.crashReports));
  4158. updater::setAutomatic (o.checkUpdates);
  4159. ChannelRackComponent::keepEditorsOpen = o.keepEditorsOpen;
  4160. ChannelRackComponent::selectFirstChannelWithNotes = o.selectFirstChannelWithNotes;
  4161. self.alternateUndo = o.alternateUndo;
  4162. EditorGlobals::get().rememberSeek = o.rememberSeek;
  4163. if (o.stretchedClipsLoop != stretchedClipsLoop())
  4164. {
  4165. setStretchedClipsLoop (o.stretchedClipsLoop);
  4166. self.repaint(); // the Playlist draws what plays
  4167. }
  4168. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, o.editPatternsIn);
  4169. self.startup.splash = o.splash;
  4170. self.startup.sound = o.startupSound;
  4171. self.engine.setUndoLevels (o.undoLevels);
  4172. self.autosaveMinutes = prefs::clampAutosaveMinutes (o.autosaveMinutes);
  4173. self.autosaveKeep = prefs::clampAutosaveKeep (o.autosaveKeep);
  4174. self.askUnusedRecordings = o.askUnusedRecordings;
  4175. newProjectDefaults().autoCrossfades = o.crossfadesInNewProjects;
  4176. self.autosaveTicks = 0;
  4177. self.saveUiSettings();
  4178. if (o.language != i18n::saved())
  4179. self.showLanguageChoice (o.language);
  4180. };
  4181. hooks.manageShortcuts = [safe] {
  4182. if (safe != nullptr)
  4183. safe->showShortcutManager();
  4184. };
  4185. hooks.managePlugins = [safe] {
  4186. if (safe != nullptr)
  4187. safe->showPluginManager();
  4188. };
  4189. showSettings (engine, (SettingsPage) juce::jlimit (0, (int) SettingsPage::theme, page), std::move (hooks)); // (Theme was clamped to MIDI)
  4190. }
  4191. void MainComponent::showPluginManager()
  4192. {
  4193. lynx::showPluginManager (engine, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  4194. if (safe != nullptr)
  4195. safe->openSettings ((int) SettingsPage::files);
  4196. });
  4197. }
  4198. void MainComponent::showShortcutManager()
  4199. {
  4200. lynx::showShortcutManager ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  4201. if (safe == nullptr)
  4202. return;
  4203. safe->loadKeyMap();
  4204. safe->setControlHints();
  4205. safe->menuItemsChanged();
  4206. });
  4207. }
  4208. void MainComponent::showMissingFiles (bool afterOpening)
  4209. {
  4210. if (afterOpening && platform::testMode()) // (LYNX_TEST_MODE: nothing waits for a click)
  4211. {
  4212. platform::testModeLog ("Missing files dialog after opening " + projectName);
  4213. return;
  4214. }
  4215. MissingFilesInfo info;
  4216. info.projectName = projectName;
  4217. const auto fromFlp = importedFlpFile.existsAsFile() && currentFile == juce::File();
  4218. 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(); };
  4219. if (fromFlp)
  4220. {
  4221. // the import dropped the samples it couldn't find: its report keeps them (minus the ones located since)
  4222. const auto& report = engine.getImportReport();
  4223. for (const auto& m : report.missingFiles)
  4224. info.files.push_back (m);
  4225. info.plugins = engine.getMissingPluginDetails();
  4226. info.autoRelocated = report.relocatedFiles;
  4227. info.searchFolders.add (importedFlpFile.getParentDirectory().getFullPathName());
  4228. }
  4229. else
  4230. {
  4231. const auto& song = engine.getSong();
  4232. info.files = findMissingSamples (song, exists);
  4233. auto& host = engine.getPluginHost();
  4234. auto addPlugin = [&info] (const PluginRef& ref, const std::string& user, const char* replacement) {
  4235. const auto name = ref.name.empty() ? ref.id : ref.name;
  4236. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  4237. if (it == info.plugins.end())
  4238. it = info.plugins.insert (info.plugins.end(), MissingPlugin { name, {}, replacement });
  4239. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  4240. it->usedBy.push_back (user);
  4241. };
  4242. for (const auto& c : song.channels)
  4243. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty() && host.find (juce::String::fromUTF8 (c.plugin.id.c_str())) == nullptr)
  4244. addPlugin (c.plugin, c.name, "Silence: the channel keeps the plugin's settings until it is installed");
  4245. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4246. for (const auto& fx : song.mixer[t].effects)
  4247. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty() && host.find (juce::String::fromUTF8 (fx.plugin.id.c_str())) == nullptr)
  4248. addPlugin (fx.plugin, song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name,
  4249. "Bypassed: the slot keeps the plugin's settings until it is installed");
  4250. // played by a LYNX substitute until the original is installed
  4251. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  4252. for (const auto& fx : song.mixer[t].effects)
  4253. if (fx.isSubstitute())
  4254. {
  4255. const auto name = substituteOriginalName (fx);
  4256. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  4257. if (it == info.plugins.end())
  4258. it = info.plugins.insert (info.plugins.end(),
  4259. 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"),
  4260. effectInfo (fx.kind).name });
  4261. const auto user = song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name;
  4262. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  4263. it->usedBy.push_back (user);
  4264. }
  4265. // installed, but failed to load: they play silence / are bypassed
  4266. for (const auto& line : host.getLoadFailures())
  4267. if (std::none_of (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == line.toStdString(); }))
  4268. info.plugins.push_back ({ line.toStdString(), {}, "Silence: the plugin is installed but did not load" });
  4269. if (currentFile.existsAsFile())
  4270. info.searchFolders.add (currentFile.getParentDirectory().getFullPathName());
  4271. }
  4272. if (afterOpening && info.files.empty() && info.plugins.empty())
  4273. {
  4274. if (fromFlp)
  4275. showImportReport();
  4276. return;
  4277. }
  4278. auto safe = juce::Component::SafePointer<MainComponent> (this);
  4279. const auto flp = fromFlp ? importedFlpFile : juce::File();
  4280. showMissingFilesDialog (
  4281. std::move (info),
  4282. [safe, flp] (const std::map<std::string, std::string>& relocations) {
  4283. if (safe == nullptr)
  4284. return;
  4285. if (flp != juce::File())
  4286. {
  4287. // FL import: imported again with the located samples (the channels become samplers, slices are read...)
  4288. juce::String error;
  4289. if (! safe->engine.importFlpFile (flp, error, relocations, true))
  4290. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  4291. }
  4292. else
  4293. safe->engine.editSong ([&relocations] (Song& s) { applyRelocations (s, relocations); });
  4294. safe->updateTitle();
  4295. },
  4296. [safe, afterOpening, fromFlp] {
  4297. if (safe != nullptr && afterOpening && fromFlp)
  4298. safe->showImportReport();
  4299. });
  4300. }
  4301. void MainComponent::switchSmartDisableForAll()
  4302. {
  4303. // FL's Tools › Macros › "Switch smart disable for all plugins" (FLEngine FUN_0124d430, REA round 139): every
  4304. // effect slot of every insert is set to smart disable
  4305. engine.editSong ([] (Song& s) {
  4306. for (auto& track : s.mixer)
  4307. for (auto& slot : track.effects)
  4308. slot.smartDisable = true;
  4309. });
  4310. }
  4311. void MainComponent::exportAudio (int format)
  4312. {
  4313. showExportDialog (engine, currentFile.getParentDirectory(), projectName, format);
  4314. }
  4315. void MainComponent::importMidiFile()
  4316. {
  4317. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  4318. fileChooser = std::make_unique<juce::FileChooser> (tr ("Import MIDI file"), folder, "*.mid;*.midi");
  4319. juce::Component::SafePointer<MainComponent> safe (this);
  4320. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe] (const juce::FileChooser& fc) {
  4321. const auto file = fc.getResult();
  4322. if (safe == nullptr || file == juce::File())
  4323. return;
  4324. juce::String error;
  4325. const auto midi = MidiFileIo::parseFile (file, error);
  4326. if (! midi)
  4327. {
  4328. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  4329. return;
  4330. }
  4331. static MidiFileIo::ImportOptions remembered; // FL keeps the window's choices
  4332. showMidiImportDialog (file.getFileName(), *midi, remembered, false, [safe, file] (const MidiFileIo::ImportOptions& o) {
  4333. remembered = o;
  4334. if (safe != nullptr)
  4335. safe->importMidiFile (file, o);
  4336. });
  4337. });
  4338. }
  4339. void MainComponent::importMidiFile (const juce::File& file, const MidiFileIo::ImportOptions& o)
  4340. {
  4341. juce::String error;
  4342. if (o.newProject)
  4343. {
  4344. confirmDiscard ([this, file, o] {
  4345. Song song;
  4346. juce::String err;
  4347. if (! MidiFileIo::importInto (song, file, o, err))
  4348. {
  4349. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), err);
  4350. return;
  4351. }
  4352. engine.stop();
  4353. engine.rewind();
  4354. engine.setSong (std::move (song));
  4355. currentFile = juce::File();
  4356. projectName = file.getFileNameWithoutExtension();
  4357. importedSuffix = " " + tr ("(imported from MIDI)");
  4358. updateTitle();
  4359. });
  4360. return;
  4361. }
  4362. auto song = engine.getSong();
  4363. if (! MidiFileIo::importInto (song, file, o, error))
  4364. {
  4365. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  4366. return;
  4367. }
  4368. engine.editSong ([&song] (Song& s) { s = std::move (song); });
  4369. showPanel (Panel::channelRack);
  4370. }
  4371. void MainComponent::exportMidiFile()
  4372. {
  4373. // FL's File › Export › "MIDI file...": the arrangement's notes (or the current pattern's) as a Standard MIDI File
  4374. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  4375. const auto name = projectName.isNotEmpty() ? projectName : juce::String ("LYNX SHARE");
  4376. fileChooser = std::make_unique<juce::FileChooser> (tr ("Export MIDI file"), folder.getChildFile (name + ".mid"), "*.mid");
  4377. juce::Component::SafePointer<MainComponent> safe (this);
  4378. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  4379. [safe] (const juce::FileChooser& fc) {
  4380. auto file = fc.getResult();
  4381. if (safe == nullptr || file == juce::File())
  4382. return;
  4383. if (! file.hasFileExtension (".mid;.midi"))
  4384. file = file.withFileExtension (".mid");
  4385. juce::String error;
  4386. if (! MidiFileIo::saveSong (safe->engine.getSong(), file, error))
  4387. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not export"), error);
  4388. else
  4389. file.revealToUser();
  4390. });
  4391. }
  4392. void MainComponent::save (bool askForFile)
  4393. {
  4394. auto write = [this] (juce::File file) {
  4395. if (! file.hasFileExtension (ProjectFile::extension))
  4396. file = file.withFileExtension (ProjectFile::extension);
  4397. juce::String error;
  4398. engine.capturePluginStates(); // plugin state lives in the plugins; copy it before saving
  4399. keepOverwrittenCopy (file); // the version this save replaces goes to the backup folder (like FL)
  4400. if (ProjectFile::save (engine.getSong(), file, error))
  4401. {
  4402. engine.markSaved();
  4403. rememberRecent (file);
  4404. currentFile = file;
  4405. projectName = file.getFileNameWithoutExtension();
  4406. importedSuffix = {};
  4407. updateTitle();
  4408. }
  4409. else
  4410. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  4411. };
  4412. // a project opened from the backup folder is saved somewhere else (old backups there are deleted)
  4413. if (! askForFile && currentFile != juce::File() && ! currentFile.isAChildOf (autosaveFolder()))
  4414. {
  4415. write (currentFile);
  4416. return;
  4417. }
  4418. const auto startFolder = currentFile.isAChildOf (autosaveFolder()) ? juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
  4419. : currentFile.getParentDirectory();
  4420. fileChooser = std::make_unique<juce::FileChooser> (tr ("Save project"), startFolder, juce::String ("*") + ProjectFile::extension);
  4421. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  4422. [write] (const juce::FileChooser& chooser) {
  4423. const auto file = chooser.getResult();
  4424. if (file == juce::File())
  4425. return;
  4426. if (! file.isAChildOf (autosaveFolder()))
  4427. {
  4428. write (file);
  4429. return;
  4430. }
  4431. // FL warns the same way: the backup folder is cleaned up as new backups arrive
  4432. auto* w = new juce::AlertWindow (tr ("Save in the backup folder?"),
  4433. tr ("This folder keeps LYNX SHARE's automatic backups and old ones are deleted as new "
  4434. "ones arrive, so a project saved here can be lost. If you opened a backup, save it "
  4435. "somewhere else."),
  4436. juce::MessageBoxIconType::WarningIcon);
  4437. w->addButton (tr ("Save anyway"), 1);
  4438. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4439. w->enterModalState (true, juce::ModalCallbackFunction::create ([write, file] (int r) {
  4440. if (r == 1)
  4441. write (file);
  4442. }),
  4443. true);
  4444. });
  4445. }
  4446. void MainComponent::placeHintBar (juce::Rectangle<int> row)
  4447. {
  4448. // the read-out takes the right part of the hint row once something was tweaked (2/5 of it, 170..280 px), and
  4449. // only when the hint keeps at least 220 px
  4450. const auto readoutWidth = juce::jlimit (170, 280, row.getWidth() * 2 / 5);
  4451. if (tweakReadout.hasContent() && row.getWidth() - readoutWidth - 6 >= 220)
  4452. {
  4453. tweakReadout.setBounds (row.removeFromRight (readoutWidth));
  4454. tweakReadout.setVisible (true);
  4455. row.removeFromRight (6);
  4456. }
  4457. else
  4458. {
  4459. tweakReadout.setVisible (false);
  4460. tweakReadout.setBounds ({});
  4461. }
  4462. hintBar.setVisible (true);
  4463. hintBar.setBounds (row);
  4464. }
  4465. void MainComponent::refreshTweakReadout()
  4466. {
  4467. const auto had = tweakReadout.hasContent();
  4468. if (const auto t = engine.getLastTweaked (0))
  4469. tweakReadout.setContent (describeAutomationTarget (engine, *t), describeTargetValue (engine, *t));
  4470. else
  4471. tweakReadout.setContent ({}, {});
  4472. if (had != tweakReadout.hasContent())
  4473. resized(); // the read-out appears (or goes, with its target)
  4474. }
  4475. juce::PopupMenu MainComponent::makeLastTweakedMenu (int which)
  4476. {
  4477. juce::PopupMenu menu;
  4478. const auto target = engine.getLastTweaked (which);
  4479. if (! target)
  4480. {
  4481. menu.addItem (tr ("No parameter"), false, false, [] {});
  4482. return menu;
  4483. }
  4484. // as FL: the parameter's name, then the items of its own menu (events, automation clip, remote control, value)
  4485. const auto valueNow = describeTargetValue (engine, *target); // (round 162d: with its value, as the read-out shows it)
  4486. ui::addItemHeader (menu, tr ("Parameter"), describeAutomationTarget (engine, *target) + (valueNow.isNotEmpty() ? ": " + valueNow : juce::String()),
  4487. juce::Colours::transparentBlack);
  4488. const auto& song = engine.getSong();
  4489. int clip = -1;
  4490. for (int a = 0; a < (int) song.automations.size(); ++a)
  4491. if (song.automations[(std::size_t) a].target == *target)
  4492. clip = a;
  4493. juce::ignoreUnused (clip);
  4494. addAutomationItem (menu, engine, *target, true);
  4495. menu.addSectionHeader (tr ("Value"));
  4496. const auto value = engine.currentTargetValue (*target);
  4497. menu.addItem (tr ("Copy value"), value >= 0.0f, false, [value] { lastTweakedClipboard() = value; });
  4498. menu.addItem (tr ("Paste value"), lastTweakedClipboard() >= 0.0f, false, [this, t = *target] { setTweakedValue (t, lastTweakedClipboard()); });
  4499. menu.addItem (tr ("Type in value..."), value >= 0.0f, false, [this, t = *target, value] {
  4500. auto spec = ui::percentSpec (describeAutomationTarget (engine, t), value);
  4501. ui::typeValue (*this, spec, value, [this, t] (double v) { setTweakedValue (t, (float) v); });
  4502. });
  4503. return menu;
  4504. }
  4505. float& MainComponent::lastTweakedClipboard()
  4506. {
  4507. static float copied = -1.0f;
  4508. return copied;
  4509. }
  4510. void MainComponent::setTweakedValue (const AutomationTarget& target, float value)
  4511. {
  4512. value = juce::jlimit (0.0f, 1.0f, value);
  4513. auto plugin = false;
  4514. engine.editSong ([&] (Song& s) { plugin = ! s.setTargetValue (target, value); });
  4515. if (plugin)
  4516. {
  4517. if (target.kind == AutomationTargetKind::channelParam)
  4518. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (target.index).get()))
  4519. p->setParameterFromUi (target.param, value);
  4520. if (target.kind == AutomationTargetKind::effectParam)
  4521. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (target.index, target.slot).get()))
  4522. p->setParameterFromUi (target.param, value);
  4523. }
  4524. engine.noteTweaked (target);
  4525. }
  4526. juce::StringArray MainComponent::getMenuBarNames()
  4527. {
  4528. // FL's menu bar order (REA round 139): FILE EDIT ADD PATTERNS VIEW OPTIONS TOOLS HELP
  4529. return { tr ("File"), tr ("Edit"), tr ("Add"), tr ("Patterns"), tr ("View"), tr ("Options"), tr ("Tools"), tr ("Help") };
  4530. }
  4531. juce::PopupMenu MainComponent::getMenuForIndex (int barIndex, const juce::String&)
  4532. {
  4533. juce::PopupMenu menu;
  4534. // the bar's position → the menu built below (0 File, 1 Edit, 2 View, 3 Patterns, 4 Options, 5 Help, 10 Add, 11 Tools)
  4535. static constexpr int menus[] = { 0, 1, 10, 3, 2, 4, 11, 5 };
  4536. const auto index = juce::isPositiveAndBelow (barIndex, (int) std::size (menus)) ? menus[barIndex] : 5;
  4537. if (index == 10)
  4538. {
  4539. // FL's ADD menu: a channel (LYNX's instruments and the installed plugins), a pattern, the plugin tools
  4540. menu.addSectionHeader (tr ("Channel"));
  4541. rack.addInstrumentItems (menu, -1);
  4542. menu.addSectionHeader (tr ("Other"));
  4543. // FL's "Automation for last tweaked parameter" (Add_AutoLastMenu → FUN_01231100, REA round 143)
  4544. const auto last = engine.getLastTweaked (0);
  4545. menu.addItem (last ? tr ("Automation for last tweaked parameter ({0})", { describeAutomationTarget (engine, *last) })
  4546. : tr ("Automation for last tweaked parameter"),
  4547. last.has_value(), false, [this] {
  4548. if (const auto t = engine.getLastTweaked (0))
  4549. createAutomationClip (engine, *t);
  4550. });
  4551. menu.addItem (tr ("Pattern"), [this] { newPatternButton.onClick(); });
  4552. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  4553. return menu;
  4554. }
  4555. if (index == 11)
  4556. {
  4557. // FL's TOOLS menu, with the tools LYNX has (REA round 139)
  4558. menu.addItem (tr ("Browser find") + shortcutText ("browser.search"), [this] {
  4559. showPanel (Panel::browser);
  4560. browser.focusSearch();
  4561. });
  4562. menu.addItem (tr ("One-click audio recording: arm the selected insert..."), [this] { armSelectedInsertForAudio(); });
  4563. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  4564. // FL's "Last tweaked parameters" section (LastTweaked1Menu / LastTweaked2Menu → FUN_0123d1d0, REA round 143):
  4565. // the parameter's own menu for the last two moved controls
  4566. menu.addSectionHeader (tr ("Last tweaked parameters"));
  4567. menu.addSubMenu (tr ("Last tweaked"), makeLastTweakedMenu (0), engine.getLastTweaked (0).has_value());
  4568. menu.addSubMenu (tr ("Next to last tweaked"), makeLastTweakedMenu (1), engine.getLastTweaked (1).has_value());
  4569. menu.addSectionHeader (tr ("Macros"));
  4570. menu.addItem (tr ("Stop sound (all notes off)"), [this] { engine.panic(); });
  4571. menu.addItem (tr ("Select unused channels"), [this] {
  4572. showPanel (Panel::channelRack);
  4573. rack.selectUnused();
  4574. });
  4575. menu.addItem (tr ("Switch smart disable for all plugins"), [this] { switchSmartDisableForAll(); });
  4576. menu.addItem (tr ("Prepare for performance mode..."), [this] { prepareForPerformance(); });
  4577. // FL's Macros order ([DFM] mainmenu): ... Purge unused audio clips ... Lock / Unlock all playlist tracks, Reset
  4578. // empty playlist tracks (round 168f)
  4579. menu.addItem (tr ("Purge unused audio clips"), [this] { playlist.runAction ("playlist.purgeUnusedAudio"); });
  4580. menu.addItem (tr ("Lock all playlist tracks to content"), [this] { playlist.runAction ("playlist.lockAllToContent"); });
  4581. menu.addItem (tr ("Unlock all playlist tracks from content"), [this] { playlist.runAction ("playlist.unlockAllFromContent"); });
  4582. menu.addItem (tr ("Reset empty playlist tracks"), [this] { playlist.runAction ("playlist.resetEmptyTracks"); });
  4583. menu.addItem (tr ("Delete unused recordings and save project..."), [this] { deleteUnusedRecordingsAndSave(); });
  4584. menu.addItem (tr ("Collect project samples into a folder..."), [this] { collectSamples(); });
  4585. return menu;
  4586. }
  4587. if (index == 0)
  4588. {
  4589. menu.addItem (tr ("New") + shortcutText ("file.new"), [this] { newProject(); });
  4590. menu.addItem (tr ("New project..."), [this] { newProject (true); });
  4591. juce::PopupMenu templates;
  4592. const auto names = templateNames();
  4593. for (int i = 0; i < (int) names.size(); ++i)
  4594. templates.addItem (juce::String::fromUTF8 (names[(std::size_t) i].c_str()), [this, i] {
  4595. confirmDiscard ([this, i] {
  4596. engine.stop();
  4597. engine.rewind();
  4598. engine.setSong (makeNewProject (i));
  4599. currentFile = juce::File();
  4600. projectName = {};
  4601. importedSuffix = {};
  4602. updateTitle();
  4603. });
  4604. });
  4605. menu.addSubMenu (tr ("New from template"), templates);
  4606. menu.addItem (tr ("Open...") + shortcutText ("file.open"), [this] { chooseFileToOpen(); });
  4607. menu.addSeparator();
  4608. // FL's order (REA round 139): saving, then Export, then the recent projects listed in the menu itself
  4609. menu.addItem (tr ("Save") + shortcutText ("file.save"), [this] { save (false); });
  4610. menu.addItem (tr ("Save as...") + shortcutText ("file.saveAs"), [this] { save (true); });
  4611. menu.addItem (tr ("Save new version") + shortcutText ("file.saveNewVersion"), [this] { saveNewVersion(); });
  4612. menu.addItem (tr ("Save to new project folder..."), [this] { saveToNewProjectFolder(); });
  4613. menu.addItem (tr ("Save as template..."), [this] { saveAsTemplate(); });
  4614. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  4615. menu.addSeparator();
  4616. {
  4617. // FL's File › Import (ImportMenu › ImportMIDIMenu → FileImportMIDIFileAction, REA round 143)
  4618. juce::PopupMenu imports;
  4619. imports.addItem (tr ("MIDI file..."), [this] { importMidiFile(); });
  4620. menu.addSubMenu (tr ("Import"), imports);
  4621. }
  4622. {
  4623. // FL's File › Export (REA round 139): one entry per format, then the formats of the last export
  4624. juce::PopupMenu exports;
  4625. exports.addItem (tr ("Wave file..."), [this] { exportAudio (0); });
  4626. exports.addItem (tr ("MP3 file...") + shortcutText ("file.exportMp3"), [this] { exportAudio (1); });
  4627. exports.addItem (tr ("OGG file..."), [this] { exportAudio (2); });
  4628. exports.addItem (tr ("FLAC file..."), [this] { exportAudio (3); });
  4629. exports.addItem (tr ("MIDI file...") + shortcutText ("file.exportMidi"), [this] { exportMidiFile(); });
  4630. exports.addItem (tr ("Last exported format(s)...") + shortcutText ("file.export"), [this] { exportAudio(); });
  4631. exports.addSeparator();
  4632. // FL's FileExportMasterAction ("Render the project to a file and master it"; FL Cloud there, on the computer here)
  4633. exports.addItem (tr ("Master...") + shortcutText ("file.exportMaster"), [this] { showMasterDialog (engine, currentFile.getParentDirectory(), projectName); });
  4634. exports.addSeparator();
  4635. // FL's ExportAllPLTracksMenu / ExportAllPLTrackGroupsMenu (FileExportPLTracks… / FileExportPLGroups…, REA round 168e)
  4636. exports.addSubMenu (tr ("All playlist tracks"), playlistTrackExportMenu (false));
  4637. exports.addSubMenu (tr ("All playlist track groups"), playlistTrackExportMenu (true));
  4638. exports.addSeparator();
  4639. exports.addItem (tr ("Project with samples (.zip)..."), [this] { exportPackage(); });
  4640. // FL's "Project bones..." (FileExportProjectBonesAction; REA round 168e)
  4641. exports.addItem (tr ("Project bones..."), [this] { exportProjectBones (engine, currentFile.getParentDirectory(), projectName); });
  4642. exports.addItem (tr ("Project data files (collect the samples into a folder)..."), [this] { collectSamples(); });
  4643. menu.addSubMenu (tr ("Export"), exports);
  4644. }
  4645. {
  4646. // Online Sessions, phase 1 (docs/design/ONLINE_SESSIONS.md, round 168a): a project goes to a friend as a
  4647. // .lynxpack, his part comes back the same way
  4648. const auto guestCopy = engine.getSong().session.isGuestCopy();
  4649. juce::PopupMenu online;
  4650. online.addItem (tr ("Send project..."), ! guestCopy, false, [this] { sessionui::sendProject (sessionContext()); });
  4651. online.addItem (tr ("Send my part back..."), guestCopy, false, [this] { sessionui::sendPartBack (sessionContext()); });
  4652. online.addItem (tr ("Merge a part..."), ! guestCopy, false, [this] { sessionui::mergePart (sessionContext()); });
  4653. online.addSeparator();
  4654. liveui::addMenuItems (online, liveContext());
  4655. menu.addSubMenu (tr ("Online session"), online);
  4656. }
  4657. menu.addSectionHeader (tr ("Recent projects"));
  4658. const auto shown = juce::jmin (recent.getNumFiles(), 10);
  4659. for (int i = 0; i < shown; ++i)
  4660. {
  4661. const auto file = recent.getFile (i);
  4662. juce::PopupMenu::Item item (file.getFileName());
  4663. item.shortcutKeyDescription = file.getParentDirectory().getFileName(); // its folder on the right
  4664. item.setEnabled (file.existsAsFile()).setAction ([this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  4665. menu.addItem (std::move (item));
  4666. }
  4667. if (recent.getNumFiles() > shown)
  4668. {
  4669. juce::PopupMenu more;
  4670. for (int i = shown; i < recent.getNumFiles(); ++i)
  4671. {
  4672. const auto file = recent.getFile (i);
  4673. more.addItem (file.getFileName() + " (" + file.getParentDirectory().getFullPathName() + ")", file.existsAsFile(),
  4674. false, [this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  4675. }
  4676. menu.addSubMenu (tr ("More recent projects"), more);
  4677. }
  4678. if (recent.getNumFiles() == 0)
  4679. menu.addItem (tr ("(none)"), false, false, [] {});
  4680. menu.addSeparator();
  4681. menu.addItem (tr ("Revert to last backup..."), [this] { revertToLastBackup(); });
  4682. menu.addItem (tr ("Open autosave folder"), [] {
  4683. autosaveFolder().createDirectory();
  4684. autosaveFolder().startAsProcess();
  4685. });
  4686. menu.addSeparator();
  4687. menu.addItem (tr ("Exit"), [] { juce::JUCEApplication::getInstance()->systemRequestedQuit(); });
  4688. }
  4689. else if (index == 1)
  4690. {
  4691. // FL's Edit menu: "Undo backwards" (Ctrl+Alt+Z) above "Undo" (Ctrl+Z: undo, or redo after an undo)
  4692. menu.addItem (tr ("Undo backwards") + shortcutText ("edit.undoBackwards"), engine.canUndo(), false, [this] { undoRedo (false); });
  4693. menu.addItem ((alternateUndo || ! engine.canRedo() ? tr ("Undo") : tr ("Undo (redo)")) + shortcutText ("edit.undo"),
  4694. engine.canUndo() || engine.canRedo(), false, [this] { flUndo(); });
  4695. menu.addItem (tr ("Redo") + shortcutText ("edit.redo"), engine.canRedo(), false, [this] { undoRedo (true); });
  4696. menu.addItem (tr ("Undo history...") + shortcutText ("edit.history"), [this] { showHistory(); });
  4697. menu.addItem (tr ("Audio editor..."), [this] { openAudioEditor (engine); });
  4698. menu.addSeparator();
  4699. menu.addItem (tr ("Quick-add palette...") + shortcutText ("panel.quickAdd"), [this] { showQuickAdd(); });
  4700. menu.addItem (tr ("Search the Browser") + shortcutText ("browser.search"), [this] {
  4701. showPanel (Panel::browser);
  4702. browser.focusSearch();
  4703. });
  4704. }
  4705. else if (index == 2)
  4706. {
  4707. for (auto panel : panelOrder)
  4708. menu.addItem (panelName (panel) + shortcutText (panelAction (panel)), true, workspace.isPanelVisible (panel), [this, panel] { togglePanel (panel); });
  4709. menu.addSeparator();
  4710. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  4711. workspace.toggleMaximised (Panel::playlist);
  4712. refreshPanelButtons();
  4713. });
  4714. {
  4715. juce::PopupMenu detach;
  4716. for (auto panel : panelOrder)
  4717. detach.addItem (panelName (panel), true, workspace.isDetached (panel), [this, panel] {
  4718. workspace.setDetached (panel, ! workspace.isDetached (panel));
  4719. refreshPanelButtons();
  4720. });
  4721. menu.addSubMenu (tr ("Detached panels (own window)"), detach);
  4722. }
  4723. menu.addSeparator();
  4724. menu.addItem (tr ("Reset layout"), [this] {
  4725. workspace.resetLayout();
  4726. refreshPanelButtons();
  4727. });
  4728. menu.addItem (tr ("Save layout as..."), [this] { saveLayoutAs(); });
  4729. menu.addSubMenu (tr ("Load layout"), layoutsMenu());
  4730. menu.addItem (tr ("Bring back off-screen panels"), [this] { workspace.bringBackOffscreen(); });
  4731. menu.addItem (tr ("Close all windows (plugins, channel settings, tools)") + shortcutText ("view.closeWindows"), [this] { runAction ("view.closeWindows"); });
  4732. menu.addItem (tr ("Close all plugin windows") + shortcutText ("view.closePluginWindows"), [this] { runAction ("view.closePluginWindows"); });
  4733. menu.addItem (tr ("Close all windows except the focused one") + shortcutText ("view.closeUnfocusedWindows"), [this] { runAction ("view.closeUnfocusedWindows"); });
  4734. menu.addSeparator();
  4735. menu.addItem (tr ("Plugin database (in the Browser)") + shortcutText ("view.pluginDatabase"), [this] { runAction ("view.pluginDatabase"); });
  4736. menu.addItem (tr ("Audio editor") + shortcutText ("view.audioEditor"), [this] { openAudioEditorForSelection(); });
  4737. menu.addItem (tr ("Tempo tapper") + shortcutText ("view.tempoTapper"), [this] { openTempoTapper (engine); });
  4738. menu.addItem (tr ("Sample browser (separate window)") + shortcutText ("view.sampleBrowser"), true, findToolWindow ("sampleBrowser") != nullptr,
  4739. [this] { toggleSampleBrowser(); });
  4740. menu.addSeparator();
  4741. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  4742. menu.addItem (tr ("Touch keyboard") + shortcutText ("view.touchKeyboard"), true, isTouchKeyboardOpen(), [this] { toggleTouchKeyboard (engine); });
  4743. {
  4744. // FL's View › Background (audit round 165z-a): the workspace image and colour of Options › Theme
  4745. juce::PopupMenu background;
  4746. background.addItem (tr ("Set image wallpaper..."), [] { themeui::setImageWallpaper(); });
  4747. background.addItem (tr ("Remove image wallpaper"), ! themeui::current().image.empty(), false, [] { themeui::removeImageWallpaper(); });
  4748. background.addItem (tr ("Set background color..."), [this] { openSettings ((int) SettingsPage::theme); });
  4749. menu.addSubMenu (tr ("Background"), background);
  4750. }
  4751. menu.addSeparator();
  4752. // FL's "Auto scrolling" (round 162, issue #9)
  4753. menu.addItem (tr ("Playlist follows the playhead (auto scrolling)") + shortcutText ("playlist.follow"), true,
  4754. EditorGlobals::get().isFollowing (false), [this] { runAction ("playlist.follow"); });
  4755. menu.addItem (tr ("Piano Roll follows the playhead (auto scrolling)") + shortcutText ("pianoRoll.follow"), true,
  4756. EditorGlobals::get().isFollowing (true), [this] { runAction ("pianoRoll.follow"); });
  4757. }
  4758. else if (index == 3)
  4759. {
  4760. menu = makePatternMenu();
  4761. }
  4762. else if (index == 4)
  4763. {
  4764. // the Settings window's pages (Settings › General gathers the app options that were menu items here)
  4765. menu.addItem (tr ("Audio settings..."), [this] { openSettings ((int) SettingsPage::audio); });
  4766. menu.addItem (tr ("MIDI settings...") + shortcutText ("view.midiSettings"), [this] { openSettings ((int) SettingsPage::midi); });
  4767. menu.addItem (tr ("General settings..."), [this] { openSettings ((int) SettingsPage::general); });
  4768. menu.addItem (tr ("Theme (colors, background)..."), [this] { openSettings ((int) SettingsPage::theme); });
  4769. menu.addItem (tr ("File settings (search folders)..."), [this] { openSettings ((int) SettingsPage::files); });
  4770. menu.addItem (tr ("Project settings (tempo, time signature)..."), [this] { openSettings ((int) SettingsPage::project); });
  4771. menu.addItem (tr ("Project info...") + shortcutText ("view.projectInfo"), [this] { openSettings ((int) SettingsPage::info); });
  4772. {
  4773. juce::PopupMenu mixerMenu; // round 163: clean mixer, inserts and Master chain of new projects
  4774. mixeroptions::addItems (mixerMenu, engine, true);
  4775. menu.addSubMenu (tr ("Mixer"), mixerMenu);
  4776. }
  4777. menu.addSeparator();
  4778. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  4779. const auto scanning = engine.getPluginHost().backgroundScan().running;
  4780. menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins ({0})", { platform::pluginFormatNames() }), [this, scanning] {
  4781. if (scanning)
  4782. engine.getPluginHost().cancelBackgroundScan();
  4783. else
  4784. engine.getPluginHost().startBackgroundScan(); // progress in the hint bar; LYNX stays usable
  4785. });
  4786. menu.addItem (tr ("Manage shortcuts..."), [this] { showShortcutManager(); });
  4787. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  4788. menu.addSeparator();
  4789. menu.addItem (tr ("Record input audio"), true, engine.isAudioRecordingArmed(), [this] {
  4790. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  4791. });
  4792. // FL's Options menu, "Switches" section (TFruityLoopsMainForm DFM: KBToMIDIMenu = OptionsTypingKbToPianoAction,
  4793. // "Typing keyboard to piano", Ctrl+T, checkable, right before Metronome; round 168t, issue #34)
  4794. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  4795. menu.addItem (tr ("Metronome") + shortcutText ("transport.metronome"), true, engine.getTransport().metronome.load(), [this] {
  4796. metronomeButton.setToggleState (! metronomeButton.getToggleState(), juce::sendNotification);
  4797. });
  4798. menu.addItem (tr ("Metronome volume ({0})...", { ui::utilityVolumeText (engine.getTransport().metronomeVolume.load()) }),
  4799. [this] { showMetronomeVolume(); });
  4800. {
  4801. // FL's Options › "Auto scrolling" (audit round 165z-a): one switch for every editor's Follow (Playlist,
  4802. // Piano roll, Channel rack, Audio editor); each window's own Follow button still sets just that window
  4803. auto& globals = EditorGlobals::get();
  4804. const auto on = globals.isFollowing (false) && globals.isFollowing (true);
  4805. menu.addItem (tr ("Auto scrolling"), true, on, [on] {
  4806. auto& g = EditorGlobals::get();
  4807. for (auto v : { EditorGlobals::FollowView::playlist, EditorGlobals::FollowView::pianoRoll,
  4808. EditorGlobals::FollowView::channelRack, EditorGlobals::FollowView::audioEditor })
  4809. g.setFollowingView (v, ! on);
  4810. });
  4811. }
  4812. {
  4813. juce::PopupMenu recording;
  4814. addRecordOptions (recording);
  4815. menu.addSubMenu (tr ("Recording"), recording);
  4816. }
  4817. {
  4818. // FL 2026's Audio Logger (REA round 153): everything the Master plays goes to a WAV in the background
  4819. auto& logger = engine.getAudioLogger();
  4820. menu.addItem (tr ("Audio logger (record everything the Master plays)"), true, logger.isLogging(), [this] {
  4821. auto& log = engine.getAudioLogger();
  4822. if (log.isLogging())
  4823. {
  4824. const auto file = log.currentFile();
  4825. const auto seconds = log.secondsWritten();
  4826. log.stop();
  4827. ui::postHint ({ tr ("Audio logger: saved {0} ({1} s)", { file.getFileName(), juce::String (seconds, 1) }), {}, false, false }, 5000);
  4828. }
  4829. else if (! log.start (AudioLogger::defaultFolder(), engine.getTransport().sampleRate.load()))
  4830. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Audio logger"),
  4831. tr ("Could not create a file in {0}", { AudioLogger::defaultFolder().getFullPathName() }));
  4832. else
  4833. ui::postHint ({ tr ("Audio logger: recording the Master to {0}", { log.currentFile().getFileName() }), {}, false, false }, 5000);
  4834. });
  4835. menu.addItem (tr ("Show the audio logger's files"), [] {
  4836. const auto folder = AudioLogger::defaultFolder();
  4837. folder.createDirectory();
  4838. folder.startAsProcess();
  4839. });
  4840. }
  4841. {
  4842. // FL's score logger (REA round 165f): the notes played lately, recording or not, into the current pattern
  4843. juce::PopupMenu dumpMenu;
  4844. for (const auto minutes : { 2, 5, 10, 20, 30 })
  4845. dumpMenu.addItem (tr ("Last {0} minutes", { juce::String (minutes) }), [this, minutes] { dumpScoreLog (minutes); });
  4846. menu.addSubMenu (tr ("Dump score log to selected pattern"), dumpMenu);
  4847. menu.addItem (tr ("Clear score log"), ! engine.scoreLogEmpty(), false, [this] {
  4848. auto options = juce::MessageBoxOptions()
  4849. .withIconType (juce::MessageBoxIconType::WarningIcon)
  4850. .withTitle (tr ("Score logger"))
  4851. .withMessage (tr ("This will clear all logged notes!"))
  4852. .withButton (tr ("Clear log"))
  4853. .withButton (tr ("Cancel"));
  4854. juce::AlertWindow::showAsync (options, [this] (int result) {
  4855. if (result == 1)
  4856. engine.clearScoreLog();
  4857. });
  4858. });
  4859. }
  4860. menu.addSubMenu (tr ("Toolbar"), makeToolbarMenu());
  4861. menu.addSeparator();
  4862. menu.addItem (tr ("Setup wizard (language, audio, plugin folders)..."), [this] { showSetupWizard(); });
  4863. }
  4864. else
  4865. {
  4866. menu.addItem (tr ("Shortcuts") + shortcutText ("help.shortcuts"), [this] { showHelp(); });
  4867. menu.addItem (tr ("Missing files..."), [this] { showMissingFiles (false); });
  4868. menu.addItem (tr ("Last FL Studio import report"), [this] {
  4869. const auto& r = engine.getImportReport();
  4870. if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.droppedEffects.empty() && r.partialEffects.empty() && r.missingSamples == 0
  4871. && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty() && engine.getPluginsWithoutState().isEmpty()
  4872. && engine.getPluginHost().getLoadFailures().isEmpty())
  4873. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"),
  4874. tr ("Nothing to report (no .flp imported in this session, or everything was converted)."));
  4875. else
  4876. showImportReport();
  4877. });
  4878. menu.addItem (tr ("Built-in plugins (online list)..."), [] {
  4879. juce::URL ("https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/PLUGINS.md").launchInDefaultBrowser();
  4880. });
  4881. menu.addItem (tr ("Report a problem..."), [this] { crashreporter::showManualReport (&engine.getDeviceManager()); });
  4882. if (updater::offered()) // (not in the Store build: the Store updates it)
  4883. menu.addItem (tr ("Check for updates..."), [] { updater::checkNow(); });
  4884. menu.addItem (tr ("About LYNX SHARE"), [] {
  4885. auto* window = makeAboutWindow().release();
  4886. window->enterModalState (true, nullptr, true);
  4887. keepAboveMainWindow (*window);
  4888. });
  4889. }
  4890. return menu;
  4891. }
  4892. std::unique_ptr<juce::AlertWindow> MainComponent::makeAboutWindow()
  4893. {
  4894. struct Logo final : juce::Component
  4895. {
  4896. Logo() { setSize (300, 150); }
  4897. void paint (juce::Graphics& g) override
  4898. {
  4899. g.drawImageWithin (logoImage(), 0, 0, getWidth(), getHeight(), juce::RectanglePlacement::centred);
  4900. }
  4901. };
  4902. struct About final : juce::AlertWindow
  4903. {
  4904. About()
  4905. : juce::AlertWindow ("LYNX SHARE " JUCE_APPLICATION_VERSION_STRING,
  4906. tr ("Lightweight C++/JUCE DAW with the FL Studio workflow.\n"
  4907. "Independent implementation: no Image-Line code was copied."),
  4908. juce::MessageBoxIconType::NoIcon)
  4909. {
  4910. addCustomComponent (&logo);
  4911. }
  4912. Logo logo;
  4913. };
  4914. auto window = std::make_unique<About>();
  4915. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4916. return std::unique_ptr<juce::AlertWindow> (window.release());
  4917. }
  4918. void MainComponent::showLanguageChoice (const juce::String& id)
  4919. {
  4920. if (id == i18n::saved())
  4921. return;
  4922. i18n::save (id);
  4923. const auto restart = [this] {
  4924. confirmDiscard ([] {
  4925. lynx::platform::relaunchApp(); // through the package in the Store build (platform/Package.h)
  4926. juce::JUCEApplication::quit();
  4927. });
  4928. };
  4929. // the message is shown in the language just chosen
  4930. const auto table = i18n::tableText (id);
  4931. const juce::LocalisedStrings strings (table, false);
  4932. auto say = [&] (const char* text) { return table.isEmpty() ? juce::String::fromUTF8 (text) : strings.translate (juce::String::fromUTF8 (text)); };
  4933. auto* window = new juce::AlertWindow (say (TR_NOOP ("Language")), say (TR_NOOP ("The new language is applied when LYNX SHARE restarts.")),
  4934. juce::MessageBoxIconType::InfoIcon);
  4935. window->addButton (say (TR_NOOP ("Restart now")), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4936. window->addButton (say (TR_NOOP ("Later")), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4937. window->enterModalState (true, juce::ModalCallbackFunction::create ([restart] (int result) {
  4938. if (result == 1)
  4939. restart();
  4940. }),
  4941. true);
  4942. }
  4943. void MainComponent::rememberRecent (const juce::File& file)
  4944. {
  4945. recent.addFile (file);
  4946. PluginHost::settingsFolder().getChildFile ("recentes.txt").replaceWithText (recent.toString());
  4947. menuItemsChanged();
  4948. }
  4949. std::unique_ptr<juce::Component> MainComponent::makeHelpContent (const keys::KeyMap* keyMapIn)
  4950. {
  4951. // shortcut sheet: sections of "keys - action" rows, in two columns
  4952. struct Row
  4953. {
  4954. const char* keys;
  4955. const char* action;
  4956. };
  4957. struct Section
  4958. {
  4959. const char* title;
  4960. std::vector<Row> rows;
  4961. };
  4962. static const std::vector<Section> sections {
  4963. { TR_NOOP ("General"),
  4964. { { TR_NOOP ("Space"), TR_NOOP ("Play / stop (back to where playback started)") },
  4965. { "Ctrl+Space", TR_NOOP ("Play / pause") },
  4966. { "Ctrl+Z / Ctrl+Y", TR_NOOP ("Undo / redo") },
  4967. { "Ctrl+N / Ctrl+O", TR_NOOP ("New project / open") },
  4968. { "Ctrl+S / Ctrl+Shift+S", TR_NOOP ("Save / save as") },
  4969. { "Ctrl+R", TR_NOOP ("Export audio") },
  4970. { "Enter", TR_NOOP ("Maximize or restore the Playlist") },
  4971. { "L", TR_NOOP ("Pattern / song mode") },
  4972. { "Ctrl+T", TR_NOOP ("Typing keyboard to piano on/off") },
  4973. { "Z..M Q..P", TR_NOOP ("PC keyboard as a piano (selected channels)") },
  4974. { "Numpad +/-", TR_NOOP ("Next / previous pattern") },
  4975. { "Ctrl+Shift+Ins", TR_NOOP ("Insert an empty pattern before the current one") } } },
  4976. { TR_NOOP ("Workspace"),
  4977. { { TR_NOOP ("Drag a panel title"), TR_NOOP ("Move (snaps; Alt: free)") },
  4978. { TR_NOOP ("Double-click a title"), TR_NOOP ("Maximize / restore") },
  4979. { TR_NOOP ("Title buttons"), TR_NOOP ("Detach into a window, maximize, close") },
  4980. { TR_NOOP ("View menu"), TR_NOOP ("Reset, save and load layouts") } } },
  4981. { TR_NOOP ("Channel Rack and Mixer"),
  4982. { { TR_NOOP ("Click the name"), TR_NOOP ("Open/close the editor (Alt keeps others open)") },
  4983. { TR_NOOP ("Ctrl+click the name"), TR_NOOP ("Audition the channel") },
  4984. { TR_NOOP ("Selector / Up, Down"), TR_NOOP ("Select (Ctrl: add, Shift: range)") },
  4985. { "Alt+Up / Alt+Down", TR_NOOP ("Move the selected channels") },
  4986. { "Alt+C / Alt+Del", TR_NOOP ("Clone / delete the selected channels") },
  4987. { "Ctrl+L", TR_NOOP ("Send the selected channels to free mixer inserts") },
  4988. { TR_NOOP ("1..0 / Ctrl+1..0"), TR_NOOP ("Mute / solo channels 1-10 (typing piano off)") },
  4989. { TR_NOOP ("Knobs and faders"), TR_NOOP ("Drag (Ctrl: fine), wheel, Alt+click or middle-click resets") },
  4990. { TR_NOOP ("Right-click a knob/fader"), TR_NOOP ("Type value, reset, automation, MIDI link") },
  4991. { TR_NOOP ("Right-click Pattern / Song"), TR_NOOP ("Show the Channel Rack / Playlist") },
  4992. { TR_NOOP ("Double-click Stop"), TR_NOOP ("All notes off") } } },
  4993. { "Piano Roll",
  4994. { { TR_NOOP ("Click"), TR_NOOP ("Create a note (or chord, via the selector)") },
  4995. { TR_NOOP ("Drag"), TR_NOOP ("Move; the right edge changes the length") },
  4996. { TR_NOOP ("Right-click"), TR_NOOP ("Delete") },
  4997. { TR_NOOP ("Ctrl+drag"), TR_NOOP ("Select (Ctrl+click adds to the selection)") },
  4998. { TR_NOOP ("Shift+drag"), TR_NOOP ("Copy") },
  4999. { "Ctrl+A/C/X/V", TR_NOOP ("Select all, copy, cut, paste") },
  5000. { "Ctrl+B / Ctrl+Q", TR_NOOP ("Duplicate / quantize") },
  5001. { "Alt+M / Shift+Alt+M", TR_NOOP ("Mute / unmute") },
  5002. { "Ctrl+P / Ctrl+D", TR_NOOP ("Portamento / deselect") },
  5003. { TR_NOOP ("Shift+arrows"), TR_NOOP ("Transpose a semitone / move by the grid (Ctrl+Up/Down: an octave)") },
  5004. { TR_NOOP ("Alt / Ctrl+wheel"), TR_NOOP ("Disable snap / zoom") } } },
  5005. { "Playlist",
  5006. { { TR_NOOP ("Click"), TR_NOOP ("Paint the current pattern") },
  5007. { TR_NOOP ("Drag on the ruler"), TR_NOOP ("Set the loop (right-click clears)") },
  5008. { TR_NOOP ("Right-click a clip name"), TR_NOOP ("Split, make unique...") },
  5009. { TR_NOOP ("Track LED"), TR_NOOP ("Mute the track") },
  5010. { "Ctrl+A/C/X/V Ctrl+B", TR_NOOP ("Edit and duplicate") } } },
  5011. };
  5012. // the fourth column: every F-key of the live key map (issue #23: the sheet listed no F-keys), custom keys included
  5013. const keys::KeyMap defaults;
  5014. const auto& map = keyMapIn != nullptr ? *keyMapIn : defaults;
  5015. std::vector<std::pair<juce::String, juce::String>> functionKeys;
  5016. for (const auto& b : map.functionKeyBindings())
  5017. if (const auto* action = keys::findAction (b.actionId))
  5018. {
  5019. auto text = tr (action->description);
  5020. if (b.context != keys::Context::global)
  5021. text << " (" << tr (b.context == keys::Context::browser ? "Browser"
  5022. : b.context == keys::Context::mixer ? "Mixer"
  5023. : b.context == keys::Context::playlist ? "Playlist"
  5024. : b.context == keys::Context::pianoRoll ? "Piano Roll"
  5025. : "Channel Rack")
  5026. << ")";
  5027. functionKeys.push_back ({ juce::String (keys::displayString (b.chord)), text });
  5028. }
  5029. struct Sheet final : juce::Component
  5030. {
  5031. explicit Sheet (std::vector<std::pair<juce::String, juce::String>> f) : fkeys (std::move (f))
  5032. {
  5033. setSize (1500, juce::jmax (520, 20 + 28 + (int) fkeys.size() * 22 + 20));
  5034. }
  5035. void paint (juce::Graphics& g) override
  5036. {
  5037. using namespace theme;
  5038. g.fillAll (colour::bg2);
  5039. const auto columnWidth = (getWidth() - 5 * 24) / 4;
  5040. int column = 0, y = 20;
  5041. for (std::size_t i = 0; i < sections.size(); ++i)
  5042. {
  5043. if (i == 2 || i == 3) // next column
  5044. {
  5045. ++column;
  5046. y = 20;
  5047. }
  5048. const auto x = 24 + column * (columnWidth + 24);
  5049. const auto& section = sections[i];
  5050. g.setColour (colour::accent);
  5051. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  5052. g.setColour (colour::textPrimary);
  5053. g.setFont (font (type::title, true));
  5054. g.drawText (tr (section.title), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  5055. y += 28;
  5056. for (const auto& row : section.rows)
  5057. {
  5058. const auto keys = tr (row.keys);
  5059. g.setFont (font (type::small, true));
  5060. const auto keyWidth = juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14;
  5061. g.setColour (colour::bg4);
  5062. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  5063. g.setColour (colour::textPrimary);
  5064. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  5065. g.setColour (colour::textSecondary);
  5066. g.setFont (font (type::body));
  5067. g.drawFittedText (tr (row.action), x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.85f);
  5068. y += 24;
  5069. }
  5070. y += 14;
  5071. }
  5072. // Function keys
  5073. const auto x = 24 + 3 * (columnWidth + 24);
  5074. y = 20;
  5075. g.setColour (colour::accent);
  5076. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  5077. g.setColour (colour::textPrimary);
  5078. g.setFont (font (type::title, true));
  5079. g.drawText (tr ("Function keys"), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  5080. y += 28;
  5081. g.setFont (font (type::small, true));
  5082. int keyWidth = 0;
  5083. for (const auto& [keys, text] : fkeys)
  5084. keyWidth = juce::jmax (keyWidth, juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14);
  5085. for (const auto& [keys, text] : fkeys)
  5086. {
  5087. g.setFont (font (type::small, true));
  5088. g.setColour (colour::bg4);
  5089. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  5090. g.setColour (colour::textPrimary);
  5091. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  5092. g.setColour (colour::textSecondary);
  5093. g.setFont (font (type::body));
  5094. g.drawFittedText (text, x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.8f);
  5095. y += 22;
  5096. }
  5097. }
  5098. std::vector<std::pair<juce::String, juce::String>> fkeys;
  5099. };
  5100. return std::make_unique<Sheet> (std::move (functionKeys));
  5101. }
  5102. void MainComponent::showHelp()
  5103. {
  5104. juce::DialogWindow::LaunchOptions options;
  5105. options.content.setOwned (makeHelpContent (&keyMap).release());
  5106. options.dialogTitle = tr ("LYNX SHARE shortcuts");
  5107. options.dialogBackgroundColour = theme::colour::bg2;
  5108. options.useNativeTitleBar = true;
  5109. options.resizable = true;
  5110. options.escapeKeyTriggersCloseButton = true;
  5111. if (auto* dialog = options.launchAsync())
  5112. {
  5113. keepAboveMainWindow (*dialog);
  5114. helpWindow = dialog;
  5115. }
  5116. }
  5117. void MainComponent::closeHelp()
  5118. {
  5119. // (the key may come from the sheet itself: delete it after this call stack)
  5120. if (helpWindow == nullptr)
  5121. return;
  5122. helpWindow->setVisible (false);
  5123. juce::MessageManager::callAsync ([w = helpWindow] { delete w.getComponent(); });
  5124. helpWindow = nullptr;
  5125. }
  5126. void MainComponent::closeUnfocusedWindows()
  5127. {
  5128. // FL's Ctrl+F12 (CloseAllUnfocusedWindowsAction, round 167o): every window but the focused one closes. LYNX's
  5129. // docked or detached panels and dialogs that wait for an answer stay, as for F12.
  5130. auto* focused = juce::TopLevelWindow::getActiveTopLevelWindow();
  5131. auto* main = getTopLevelComponent();
  5132. juce::Array<juce::Component::SafePointer<juce::DocumentWindow>> close;
  5133. for (int i = 0; i < juce::TopLevelWindow::getNumTopLevelWindows(); ++i)
  5134. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (i)))
  5135. if (w != focused && w != main && w->isVisible() && ! w->isCurrentlyModal() && ! (bool) w->getProperties()["lynxPanel"])
  5136. close.add (w);
  5137. for (auto& w : close)
  5138. if (w != nullptr)
  5139. w->closeButtonPressed();
  5140. }
  5141. void MainComponent::showSetupWizard()
  5142. {
  5143. // on top of the main window (round 140), so the DAW is visible behind it from the first start on
  5144. if (setupOverlay != nullptr)
  5145. return;
  5146. auto safe = juce::Component::SafePointer<MainComponent> (this);
  5147. setupOverlay = lynx::makeSetupWizardOverlay (
  5148. engine,
  5149. [safe] (const juce::String& language) {
  5150. if (safe != nullptr)
  5151. safe->showLanguageChoice (language);
  5152. },
  5153. [safe] {
  5154. juce::MessageManager::callAsync ([safe] { // the overlay's own button is still running
  5155. if (safe != nullptr)
  5156. safe->setupOverlay.reset();
  5157. });
  5158. });
  5159. addAndMakeVisible (*setupOverlay);
  5160. setupOverlay->setBounds (getLocalBounds());
  5161. setupOverlay->toFront (true);
  5162. }
  5163. void MainComponent::showImportReport()
  5164. {
  5165. // summary of what the .flp had that LYNX doesn't reproduce exactly (only when there is something to say)
  5166. const auto& r = engine.getImportReport();
  5167. const auto& missing = engine.getMissingPlugins();
  5168. auto list = [] (const std::map<std::string, int>& items) {
  5169. std::vector<std::pair<int, std::string>> sorted;
  5170. for (const auto& [name, count] : items)
  5171. sorted.push_back ({ count, name });
  5172. std::sort (sorted.rbegin(), sorted.rend());
  5173. juce::StringArray lines;
  5174. for (const auto& [count, name] : sorted)
  5175. lines.add (" " + juce::String::fromUTF8 (name.c_str()) + (count > 1 ? " (" + juce::String (count) + ")" : juce::String()));
  5176. return lines.joinIntoString ("\n");
  5177. };
  5178. juce::String text;
  5179. if (! r.approximated.empty())
  5180. text << tr ("Approximated by the built-in synth:") << "\n" << list (r.approximated) << "\n\n";
  5181. if (! r.unsupported.empty())
  5182. text << tr ("No equivalent (played with a synth preset):") << "\n" << list (r.unsupported) << "\n\n";
  5183. if (const auto& matched = engine.getMatchedPlugins(); ! matched.isEmpty())
  5184. text << tr ("Plugins found on this PC:") << "\n " << matched.joinIntoString ("\n ") << "\n\n";
  5185. if (! missing.isEmpty())
  5186. text << tr ("Plugins not installed on this PC (or in a folder LYNX SHARE doesn't scan; Options > Setup wizard):") << "\n "
  5187. << missing.joinIntoString ("\n ") << "\n\n";
  5188. if (const auto& lost = engine.getPluginsWithoutState(); ! lost.isEmpty())
  5189. text << tr ("Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):") << "\n "
  5190. << lost.joinIntoString ("\n ") << "\n\n";
  5191. if (const auto failed = engine.getPluginHost().getLoadFailures(); ! failed.isEmpty())
  5192. text << tr ("Plugins installed but not loaded (silent):") << "\n " << failed.joinIntoString ("\n ") << "\n\n";
  5193. if (! r.droppedEffects.empty())
  5194. text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
  5195. if (! r.partialEffects.empty())
  5196. text << tr ("Effects kept but approximated or partly reproduced:") << "\n" << list (r.partialEffects) << "\n\n";
  5197. if (r.missingSamples > 0)
  5198. text << tr ("Samples missing on this machine: {0}", { juce::String (r.missingSamples) }) << "\n";
  5199. if (r.relocatedSamples > 0)
  5200. text << tr ("Samples found in another folder than the project says (FL Studio's folders or next to the project): {0}",
  5201. { juce::String (r.relocatedSamples) }) << "\n";
  5202. if (text.isNotEmpty())
  5203. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"), text.trimEnd());
  5204. }
  5205. void MainComponent::showAudioSettings()
  5206. {
  5207. openSettings ((int) SettingsPage::audio);
  5208. }
  5209. // --- the Channel Rack's filter box ---------------------------------------------------------------
  5210. void MainComponent::FilterBox::paint (juce::Graphics& g)
  5211. {
  5212. using namespace theme;
  5213. auto area = getLocalBounds().toFloat();
  5214. g.setColour (hovered ? colour::bg3 : colour::bg1);
  5215. g.fillRoundedRectangle (area, radius::sm);
  5216. g.setColour (hovered ? colour::borderStrong : colour::border);
  5217. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  5218. g.setColour (colour::textPrimary);
  5219. g.setFont (font (type::small));
  5220. g.drawText (text, getLocalBounds().withTrimmedLeft (7).withTrimmedRight (16), juce::Justification::centredLeft, true);
  5221. icons::draw (g, Icon::chevronDown, area.removeFromRight (16.0f).reduced (3.0f).translated (-2.0f, 0.0f), colour::textSecondary);
  5222. }
  5223. // FL's Tools › Macros › Prepare for performance mode ([DECOMP] FUN_0122d010, its "Marker settings" dialog: marker count
  5224. // 4 / 8 / 16 / 32 / 64, default 16; spacing 1…128 steps, default 16 = a bar): room for a launch grid before the song,
  5225. // a marker per column, a Start marker, Performance mode on, the zone in view. FL warns it can't be undone; in LYNX it
  5226. // is one undo step.
  5227. void MainComponent::prepareForPerformance()
  5228. {
  5229. auto* window = new juce::AlertWindow (tr ("Prepare for performance mode"),
  5230. tr ("Inserts empty columns before the song for the clips to launch, a marker on each, and a Start "
  5231. "marker where the song begins; Performance mode is turned on."),
  5232. juce::MessageBoxIconType::NoIcon);
  5233. window->addComboBox ("count", { "4", "8", "16", "32", "64" }, tr ("Marker count"));
  5234. 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") },
  5235. tr ("Spacing"));
  5236. if (auto* c = window->getComboBoxComponent ("count"))
  5237. c->setSelectedItemIndex (2, juce::dontSendNotification);
  5238. if (auto* c = window->getComboBoxComponent ("spacing"))
  5239. c->setSelectedItemIndex (4, juce::dontSendNotification);
  5240. window->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  5241. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  5242. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  5243. if (result != 1)
  5244. return;
  5245. const auto count = 4 << juce::jlimit (0, 4, window->getComboBoxComponent ("count")->getSelectedItemIndex());
  5246. const auto steps = 1 << juce::jlimit (0, 7, window->getComboBoxComponent ("spacing")->getSelectedItemIndex());
  5247. engine.editSong ([count, steps] (Song& s) { perf::prepareForPerformance (s, count, (std::int64_t) steps * (ppq / 4)); });
  5248. showPanel (Panel::playlist);
  5249. playlist.runAction ("playlist.zoomPerformance");
  5250. }),
  5251. true);
  5252. keepAboveMainWindow (*window);
  5253. }
  5254. } // namespace lynx