window-basic-main.cpp 300 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. Zachary Lund <[email protected]>
  4. Philippe Groarke <[email protected]>
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ******************************************************************************/
  16. #include "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <unordered_set>
  21. #include <obs-data.h>
  22. #include <obs.h>
  23. #include <obs.hpp>
  24. #include <QGuiApplication>
  25. #include <QMessageBox>
  26. #include <QShowEvent>
  27. #include <QDesktopServices>
  28. #include <QFileDialog>
  29. #include <QScreen>
  30. #include <QColorDialog>
  31. #include <QSizePolicy>
  32. #include <QScrollBar>
  33. #include <QTextStream>
  34. #include <QActionGroup>
  35. #include <util/dstr.h>
  36. #include <util/util.hpp>
  37. #include <util/platform.h>
  38. #include <util/profiler.hpp>
  39. #include <util/dstr.hpp>
  40. #include "obs-app.hpp"
  41. #include "platform.hpp"
  42. #include "visibility-item-widget.hpp"
  43. #include "item-widget-helpers.hpp"
  44. #include "window-basic-settings.hpp"
  45. #include "window-namedialog.hpp"
  46. #include "window-basic-auto-config.hpp"
  47. #include "window-basic-source-select.hpp"
  48. #include "window-basic-main.hpp"
  49. #include "window-basic-stats.hpp"
  50. #include "window-basic-main-outputs.hpp"
  51. #include "window-basic-vcam-config.hpp"
  52. #include "window-log-reply.hpp"
  53. #ifdef __APPLE__
  54. #include "window-permissions.hpp"
  55. #endif
  56. #include "window-projector.hpp"
  57. #include "window-remux.hpp"
  58. #ifdef YOUTUBE_ENABLED
  59. #include "auth-youtube.hpp"
  60. #include "window-youtube-actions.hpp"
  61. #include "youtube-api-wrappers.hpp"
  62. #endif
  63. #include "qt-wrappers.hpp"
  64. #include "context-bar-controls.hpp"
  65. #include "obs-proxy-style.hpp"
  66. #include "display-helpers.hpp"
  67. #include "volume-control.hpp"
  68. #include "remote-text.hpp"
  69. #include "ui-validation.hpp"
  70. #include "media-controls.hpp"
  71. #include "undo-stack-obs.hpp"
  72. #include <fstream>
  73. #include <sstream>
  74. #ifdef _WIN32
  75. #include "update/win-update.hpp"
  76. #include "update/shared-update.hpp"
  77. #include "windows.h"
  78. #endif
  79. #if !defined(_WIN32) && defined(WHATSNEW_ENABLED)
  80. #include "update/shared-update.hpp"
  81. #endif
  82. #ifdef ENABLE_SPARKLE_UPDATER
  83. #include "update/mac-update.hpp"
  84. #endif
  85. #include "ui_OBSBasic.h"
  86. #include "ui_ColorSelect.h"
  87. #include <QWindow>
  88. #include "update/models/whatsnew.hpp"
  89. #ifdef ENABLE_WAYLAND
  90. #include <obs-nix-platform.h>
  91. #endif
  92. using namespace std;
  93. #ifdef BROWSER_AVAILABLE
  94. #include <browser-panel.hpp>
  95. #endif
  96. #include "ui-config.h"
  97. struct QCef;
  98. struct QCefCookieManager;
  99. QCef *cef = nullptr;
  100. QCefCookieManager *panel_cookies = nullptr;
  101. bool cef_js_avail = false;
  102. void DestroyPanelCookieManager();
  103. namespace {
  104. template<typename OBSRef> struct SignalContainer {
  105. OBSRef ref;
  106. vector<shared_ptr<OBSSignal>> handlers;
  107. };
  108. } // namespace
  109. extern volatile long insideEventLoop;
  110. Q_DECLARE_METATYPE(OBSScene);
  111. Q_DECLARE_METATYPE(OBSSceneItem);
  112. Q_DECLARE_METATYPE(OBSSource);
  113. Q_DECLARE_METATYPE(obs_order_movement);
  114. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  115. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  116. {
  117. out << v.ref;
  118. return out;
  119. }
  120. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  121. {
  122. in >> v.ref;
  123. return in;
  124. }
  125. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  126. {
  127. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  128. }
  129. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  130. {
  131. item->setData(static_cast<int>(QtDataRole::OBSRef),
  132. QVariant::fromValue(val));
  133. }
  134. static void AddExtraModulePaths()
  135. {
  136. string plugins_path, plugins_data_path;
  137. char *s;
  138. s = getenv("OBS_PLUGINS_PATH");
  139. if (s)
  140. plugins_path = s;
  141. s = getenv("OBS_PLUGINS_DATA_PATH");
  142. if (s)
  143. plugins_data_path = s;
  144. if (!plugins_path.empty() && !plugins_data_path.empty()) {
  145. string data_path_with_module_suffix;
  146. data_path_with_module_suffix += plugins_data_path;
  147. data_path_with_module_suffix += "/%module%";
  148. obs_add_module_path(plugins_path.c_str(),
  149. data_path_with_module_suffix.c_str());
  150. }
  151. if (portable_mode)
  152. return;
  153. char base_module_dir[512];
  154. #if defined(_WIN32)
  155. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  156. "obs-studio/plugins/%module%");
  157. #elif defined(__APPLE__)
  158. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  159. "obs-studio/plugins/%module%.plugin");
  160. #else
  161. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  162. "obs-studio/plugins/%module%");
  163. #endif
  164. if (ret <= 0)
  165. return;
  166. string path = base_module_dir;
  167. #if defined(__APPLE__)
  168. /* User Application Support Search Path */
  169. obs_add_module_path((path + "/Contents/MacOS").c_str(),
  170. (path + "/Contents/Resources").c_str());
  171. #ifndef __aarch64__
  172. /* Legacy System Library Search Path */
  173. char system_legacy_module_dir[PATH_MAX];
  174. GetProgramDataPath(system_legacy_module_dir,
  175. sizeof(system_legacy_module_dir),
  176. "obs-studio/plugins/%module%");
  177. std::string path_system_legacy = system_legacy_module_dir;
  178. obs_add_module_path((path_system_legacy + "/bin").c_str(),
  179. (path_system_legacy + "/data").c_str());
  180. /* Legacy User Application Support Search Path */
  181. char user_legacy_module_dir[PATH_MAX];
  182. GetConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir),
  183. "obs-studio/plugins/%module%");
  184. std::string path_user_legacy = user_legacy_module_dir;
  185. obs_add_module_path((path_user_legacy + "/bin").c_str(),
  186. (path_user_legacy + "/data").c_str());
  187. #endif
  188. #else
  189. #if ARCH_BITS == 64
  190. obs_add_module_path((path + "/bin/64bit").c_str(),
  191. (path + "/data").c_str());
  192. #else
  193. obs_add_module_path((path + "/bin/32bit").c_str(),
  194. (path + "/data").c_str());
  195. #endif
  196. #endif
  197. }
  198. /* First-party modules considered to be potentially unsafe to load in Safe Mode
  199. * due to them allowing external code (e.g. scripts) to modify OBS's state. */
  200. static const unordered_set<string> unsafe_modules = {
  201. "frontend-tools", // Scripting
  202. "obs-websocket", // Allows outside modifications
  203. };
  204. static void SetSafeModuleNames()
  205. {
  206. #ifndef SAFE_MODULES
  207. return;
  208. #else
  209. string module;
  210. stringstream modules(SAFE_MODULES);
  211. while (getline(modules, module, '|')) {
  212. /* When only disallowing third-party plugins, still add
  213. * "unsafe" bundled modules to the safe list. */
  214. if (disable_3p_plugins || !unsafe_modules.count(module))
  215. obs_add_safe_module(module.c_str());
  216. }
  217. #endif
  218. }
  219. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  220. void assignDockToggle(QDockWidget *dock, QAction *action)
  221. {
  222. auto handleWindowToggle = [action](bool vis) {
  223. action->blockSignals(true);
  224. action->setChecked(vis);
  225. action->blockSignals(false);
  226. };
  227. auto handleMenuToggle = [dock](bool check) {
  228. dock->blockSignals(true);
  229. dock->setVisible(check);
  230. dock->blockSignals(false);
  231. };
  232. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  233. handleWindowToggle);
  234. dock->connect(action, &QAction::toggled, handleMenuToggle);
  235. }
  236. void setupDockAction(QDockWidget *dock)
  237. {
  238. QAction *action = dock->toggleViewAction();
  239. auto neverDisable = [action]() {
  240. QSignalBlocker block(action);
  241. action->setEnabled(true);
  242. };
  243. auto newToggleView = [dock](bool check) {
  244. QSignalBlocker block(dock);
  245. dock->setVisible(check);
  246. };
  247. // Replace the slot connected by default
  248. QObject::disconnect(action, &QAction::triggered, nullptr, 0);
  249. dock->connect(action, &QAction::triggered, newToggleView);
  250. // Make the action unable to be disabled
  251. action->connect(action, &QAction::enabledChanged, neverDisable);
  252. }
  253. extern void RegisterTwitchAuth();
  254. extern void RegisterRestreamAuth();
  255. #ifdef YOUTUBE_ENABLED
  256. extern void RegisterYoutubeAuth();
  257. #endif
  258. OBSBasic::OBSBasic(QWidget *parent)
  259. : OBSMainWindow(parent),
  260. undo_s(ui),
  261. ui(new Ui::OBSBasic)
  262. {
  263. setAttribute(Qt::WA_NativeWindow);
  264. #ifdef TWITCH_ENABLED
  265. RegisterTwitchAuth();
  266. #endif
  267. #ifdef RESTREAM_ENABLED
  268. RegisterRestreamAuth();
  269. #endif
  270. #ifdef YOUTUBE_ENABLED
  271. RegisterYoutubeAuth();
  272. #endif
  273. setAcceptDrops(true);
  274. setContextMenuPolicy(Qt::CustomContextMenu);
  275. api = InitializeAPIInterface(this);
  276. ui->setupUi(this);
  277. ui->previewDisabledWidget->setVisible(false);
  278. QStyle *contextBarStyle = new OBSContextBarProxyStyle();
  279. contextBarStyle->setParent(ui->contextContainer);
  280. ui->contextContainer->setStyle(contextBarStyle);
  281. ui->broadcastButton->setVisible(false);
  282. startingDockLayout = saveState();
  283. statsDock = new OBSDock();
  284. statsDock->setObjectName(QStringLiteral("statsDock"));
  285. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  286. QDockWidget::DockWidgetMovable |
  287. QDockWidget::DockWidgetFloatable);
  288. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  289. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  290. statsDock->setVisible(false);
  291. statsDock->setFloating(true);
  292. statsDock->resize(700, 200);
  293. copyActionsDynamicProperties();
  294. qRegisterMetaType<int64_t>("int64_t");
  295. qRegisterMetaType<uint32_t>("uint32_t");
  296. qRegisterMetaType<OBSScene>("OBSScene");
  297. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  298. qRegisterMetaType<OBSSource>("OBSSource");
  299. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  300. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  301. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  302. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  303. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  304. "gridMode");
  305. ui->scenes->SetGridMode(sceneGrid);
  306. if (sceneGrid)
  307. ui->actionSceneGridMode->setChecked(true);
  308. else
  309. ui->actionSceneListMode->setChecked(true);
  310. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  311. auto displayResize = [this]() {
  312. struct obs_video_info ovi;
  313. if (obs_get_video_info(&ovi))
  314. ResizePreview(ovi.base_width, ovi.base_height);
  315. UpdateContextBarVisibility();
  316. dpi = devicePixelRatioF();
  317. };
  318. dpi = devicePixelRatioF();
  319. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  320. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  321. delete shortcutFilter;
  322. shortcutFilter = CreateShortcutFilter();
  323. installEventFilter(shortcutFilter);
  324. stringstream name;
  325. name << "OBS " << App()->GetVersionString();
  326. blog(LOG_INFO, "%s", name.str().c_str());
  327. blog(LOG_INFO, "---------------------------------");
  328. UpdateTitleBar();
  329. connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor,
  330. this, &OBSBasic::SceneNameEdited);
  331. cpuUsageInfo = os_cpu_usage_info_start();
  332. cpuUsageTimer = new QTimer(this);
  333. connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar,
  334. &OBSBasicStatusBar::UpdateCPUUsage);
  335. cpuUsageTimer->start(3000);
  336. diskFullTimer = new QTimer(this);
  337. connect(diskFullTimer, &QTimer::timeout, this,
  338. &OBSBasic::CheckDiskSpaceRemaining);
  339. renameScene = new QAction(QTStr("Rename"), ui->scenesDock);
  340. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  341. connect(renameScene, &QAction::triggered, this,
  342. &OBSBasic::EditSceneName);
  343. ui->scenesDock->addAction(renameScene);
  344. renameSource = new QAction(QTStr("Rename"), ui->sourcesDock);
  345. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  346. connect(renameSource, &QAction::triggered, this,
  347. &OBSBasic::EditSceneItemName);
  348. ui->sourcesDock->addAction(renameSource);
  349. #ifdef __APPLE__
  350. renameScene->setShortcut({Qt::Key_Return});
  351. renameSource->setShortcut({Qt::Key_Return});
  352. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  353. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  354. ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole);
  355. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  356. ui->actionShowMacPermissions->setMenuRole(
  357. QAction::ApplicationSpecificRole);
  358. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  359. #else
  360. renameScene->setShortcut({Qt::Key_F2});
  361. renameSource->setShortcut({Qt::Key_F2});
  362. #endif
  363. #ifdef __linux__
  364. ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q);
  365. #endif
  366. auto addNudge = [this](const QKeySequence &seq, MoveDir direction,
  367. int distance) {
  368. QAction *nudge = new QAction(ui->preview);
  369. nudge->setShortcut(seq);
  370. nudge->setShortcutContext(Qt::WidgetShortcut);
  371. ui->preview->addAction(nudge);
  372. connect(nudge, &QAction::triggered,
  373. [this, distance, direction]() {
  374. Nudge(distance, direction);
  375. });
  376. };
  377. addNudge(Qt::Key_Up, MoveDir::Up, 1);
  378. addNudge(Qt::Key_Down, MoveDir::Down, 1);
  379. addNudge(Qt::Key_Left, MoveDir::Left, 1);
  380. addNudge(Qt::Key_Right, MoveDir::Right, 1);
  381. addNudge(Qt::SHIFT | Qt::Key_Up, MoveDir::Up, 10);
  382. addNudge(Qt::SHIFT | Qt::Key_Down, MoveDir::Down, 10);
  383. addNudge(Qt::SHIFT | Qt::Key_Left, MoveDir::Left, 10);
  384. addNudge(Qt::SHIFT | Qt::Key_Right, MoveDir::Right, 10);
  385. /* Setup dock toggle action
  386. * And hide all docks before restoring parent geometry */
  387. #define SETUP_DOCK(dock) \
  388. setupDockAction(dock); \
  389. ui->menuDocks->addAction(dock->toggleViewAction()); \
  390. dock->setVisible(false);
  391. SETUP_DOCK(ui->scenesDock);
  392. SETUP_DOCK(ui->sourcesDock);
  393. SETUP_DOCK(ui->mixerDock);
  394. SETUP_DOCK(ui->transitionsDock);
  395. SETUP_DOCK(ui->controlsDock);
  396. SETUP_DOCK(statsDock);
  397. #undef SETUP_DOCK
  398. // Register shortcuts for Undo/Redo
  399. ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z);
  400. QList<QKeySequence> shrt;
  401. shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z)
  402. << QKeySequence(Qt::CTRL | Qt::Key_Y);
  403. ui->actionMainRedo->setShortcuts(shrt);
  404. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  405. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  406. QPoint curPos;
  407. //restore parent window geometry
  408. const char *geometry = config_get_string(App()->GlobalConfig(),
  409. "BasicWindow", "geometry");
  410. if (geometry != NULL) {
  411. QByteArray byteArray =
  412. QByteArray::fromBase64(QByteArray(geometry));
  413. restoreGeometry(byteArray);
  414. QRect windowGeometry = normalGeometry();
  415. if (!WindowPositionValid(windowGeometry)) {
  416. QRect rect =
  417. QGuiApplication::primaryScreen()->geometry();
  418. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  419. Qt::AlignCenter, size(),
  420. rect));
  421. }
  422. curPos = pos();
  423. } else {
  424. QRect desktopRect =
  425. QGuiApplication::primaryScreen()->geometry();
  426. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  427. curPos = QPoint(adjSize.width(), adjSize.height());
  428. }
  429. QPoint curSize(width(), height());
  430. QPoint statsDockSize(statsDock->width(), statsDock->height());
  431. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  432. QPoint newPos = curPos + statsDockPos;
  433. statsDock->move(newPos);
  434. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  435. connect(ui->enablePreviewButton, &QPushButton::clicked, this,
  436. &OBSBasic::TogglePreview);
  437. connect(ui->scenes, &SceneTree::scenesReordered,
  438. []() { OBSProjector::UpdateMultiviewProjectors(); });
  439. connect(ui->broadcastButton, &QPushButton::clicked, this,
  440. &OBSBasic::BroadcastButtonClicked);
  441. connect(App(), &OBSApp::StyleChanged, this, &OBSBasic::ThemeChanged);
  442. QActionGroup *actionGroup = new QActionGroup(this);
  443. actionGroup->addAction(ui->actionSceneListMode);
  444. actionGroup->addAction(ui->actionSceneGridMode);
  445. UpdatePreviewSafeAreas();
  446. UpdatePreviewSpacingHelpers();
  447. UpdatePreviewOverflowSettings();
  448. }
  449. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  450. vector<OBSSource> &audioSources)
  451. {
  452. OBSSourceAutoRelease source = obs_get_output_source(channel);
  453. if (!source)
  454. return;
  455. audioSources.push_back(source.Get());
  456. OBSDataAutoRelease data = obs_save_source(source);
  457. obs_data_set_obj(parent, name, data);
  458. }
  459. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  460. obs_data_array_t *quickTransitionData,
  461. int transitionDuration,
  462. obs_data_array_t *transitions,
  463. OBSScene &scene, OBSSource &curProgramScene,
  464. obs_data_array_t *savedProjectorList)
  465. {
  466. obs_data_t *saveData = obs_data_create();
  467. vector<OBSSource> audioSources;
  468. audioSources.reserve(6);
  469. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  470. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  471. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  472. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  473. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  474. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  475. /* -------------------------------- */
  476. /* save non-group sources */
  477. auto FilterAudioSources = [&](obs_source_t *source) {
  478. if (obs_source_is_group(source))
  479. return false;
  480. return find(begin(audioSources), end(audioSources), source) ==
  481. end(audioSources);
  482. };
  483. using FilterAudioSources_t = decltype(FilterAudioSources);
  484. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  485. [](void *data, obs_source_t *source) {
  486. auto &func = *static_cast<FilterAudioSources_t *>(data);
  487. return func(source);
  488. },
  489. static_cast<void *>(&FilterAudioSources));
  490. /* -------------------------------- */
  491. /* save group sources separately */
  492. /* saving separately ensures they won't be loaded in older versions */
  493. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  494. [](void *, obs_source_t *source) {
  495. return obs_source_is_group(source);
  496. },
  497. nullptr);
  498. /* -------------------------------- */
  499. OBSSourceAutoRelease transition = obs_get_output_source(0);
  500. obs_source_t *currentScene = obs_scene_get_source(scene);
  501. const char *sceneName = obs_source_get_name(currentScene);
  502. const char *programName = obs_source_get_name(curProgramScene);
  503. const char *sceneCollection = config_get_string(
  504. App()->GlobalConfig(), "Basic", "SceneCollection");
  505. obs_data_set_string(saveData, "current_scene", sceneName);
  506. obs_data_set_string(saveData, "current_program_scene", programName);
  507. obs_data_set_array(saveData, "scene_order", sceneOrder);
  508. obs_data_set_string(saveData, "name", sceneCollection);
  509. obs_data_set_array(saveData, "sources", sourcesArray);
  510. obs_data_set_array(saveData, "groups", groupsArray);
  511. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  512. obs_data_set_array(saveData, "transitions", transitions);
  513. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  514. obs_data_array_release(sourcesArray);
  515. obs_data_array_release(groupsArray);
  516. obs_data_set_string(saveData, "current_transition",
  517. obs_source_get_name(transition));
  518. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  519. return saveData;
  520. }
  521. void OBSBasic::copyActionsDynamicProperties()
  522. {
  523. // Themes need the QAction dynamic properties
  524. for (QAction *x : ui->scenesToolbar->actions()) {
  525. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  526. if (!temp)
  527. continue;
  528. for (QByteArray &y : x->dynamicPropertyNames()) {
  529. temp->setProperty(y, x->property(y));
  530. }
  531. }
  532. for (QAction *x : ui->sourcesToolbar->actions()) {
  533. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  534. if (!temp)
  535. continue;
  536. for (QByteArray &y : x->dynamicPropertyNames()) {
  537. temp->setProperty(y, x->property(y));
  538. }
  539. }
  540. for (QAction *x : ui->mixerToolbar->actions()) {
  541. QWidget *temp = ui->mixerToolbar->widgetForAction(x);
  542. if (!temp)
  543. continue;
  544. for (QByteArray &y : x->dynamicPropertyNames()) {
  545. temp->setProperty(y, x->property(y));
  546. }
  547. }
  548. }
  549. void OBSBasic::UpdateVolumeControlsDecayRate()
  550. {
  551. double meterDecayRate =
  552. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  553. for (size_t i = 0; i < volumes.size(); i++) {
  554. volumes[i]->SetMeterDecayRate(meterDecayRate);
  555. }
  556. }
  557. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  558. {
  559. uint32_t peakMeterTypeIdx =
  560. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  561. enum obs_peak_meter_type peakMeterType;
  562. switch (peakMeterTypeIdx) {
  563. case 0:
  564. peakMeterType = SAMPLE_PEAK_METER;
  565. break;
  566. case 1:
  567. peakMeterType = TRUE_PEAK_METER;
  568. break;
  569. default:
  570. peakMeterType = SAMPLE_PEAK_METER;
  571. break;
  572. }
  573. for (size_t i = 0; i < volumes.size(); i++) {
  574. volumes[i]->setPeakMeterType(peakMeterType);
  575. }
  576. }
  577. void OBSBasic::ClearVolumeControls()
  578. {
  579. for (VolControl *vol : volumes)
  580. delete vol;
  581. volumes.clear();
  582. }
  583. void OBSBasic::RefreshVolumeColors()
  584. {
  585. for (VolControl *vol : volumes) {
  586. vol->refreshColors();
  587. }
  588. }
  589. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  590. {
  591. obs_data_array_t *sceneOrder = obs_data_array_create();
  592. for (int i = 0; i < ui->scenes->count(); i++) {
  593. OBSDataAutoRelease data = obs_data_create();
  594. obs_data_set_string(data, "name",
  595. QT_TO_UTF8(ui->scenes->item(i)->text()));
  596. obs_data_array_push_back(sceneOrder, data);
  597. }
  598. return sceneOrder;
  599. }
  600. obs_data_array_t *OBSBasic::SaveProjectors()
  601. {
  602. obs_data_array_t *savedProjectors = obs_data_array_create();
  603. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  604. if (!projector)
  605. return;
  606. OBSDataAutoRelease data = obs_data_create();
  607. ProjectorType type = projector->GetProjectorType();
  608. switch (type) {
  609. case ProjectorType::Scene:
  610. case ProjectorType::Source: {
  611. OBSSource source = projector->GetSource();
  612. const char *name = obs_source_get_name(source);
  613. obs_data_set_string(data, "name", name);
  614. break;
  615. }
  616. default:
  617. break;
  618. }
  619. obs_data_set_int(data, "monitor", projector->GetMonitor());
  620. obs_data_set_int(data, "type", static_cast<int>(type));
  621. obs_data_set_string(
  622. data, "geometry",
  623. projector->saveGeometry().toBase64().constData());
  624. if (projector->IsAlwaysOnTopOverridden())
  625. obs_data_set_bool(data, "alwaysOnTop",
  626. projector->IsAlwaysOnTop());
  627. obs_data_set_bool(data, "alwaysOnTopOverridden",
  628. projector->IsAlwaysOnTopOverridden());
  629. obs_data_array_push_back(savedProjectors, data);
  630. };
  631. for (size_t i = 0; i < projectors.size(); i++)
  632. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  633. return savedProjectors;
  634. }
  635. void OBSBasic::Save(const char *file)
  636. {
  637. OBSScene scene = GetCurrentScene();
  638. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  639. if (!curProgramScene)
  640. curProgramScene = obs_scene_get_source(scene);
  641. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  642. OBSDataArrayAutoRelease transitions = SaveTransitions();
  643. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  644. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  645. OBSDataAutoRelease saveData = GenerateSaveData(
  646. sceneOrder, quickTrData, ui->transitionDuration->value(),
  647. transitions, scene, curProgramScene, savedProjectorList);
  648. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  649. obs_data_set_bool(saveData, "scaling_enabled",
  650. ui->preview->IsFixedScaling());
  651. obs_data_set_int(saveData, "scaling_level",
  652. ui->preview->GetScalingLevel());
  653. obs_data_set_double(saveData, "scaling_off_x",
  654. ui->preview->GetScrollX());
  655. obs_data_set_double(saveData, "scaling_off_y",
  656. ui->preview->GetScrollY());
  657. if (vcamEnabled) {
  658. OBSDataAutoRelease obj = obs_data_create();
  659. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  660. switch (vcamConfig.type) {
  661. case VCamOutputType::Invalid:
  662. case VCamOutputType::ProgramView:
  663. case VCamOutputType::PreviewOutput:
  664. break;
  665. case VCamOutputType::SceneOutput:
  666. obs_data_set_string(obj, "scene",
  667. vcamConfig.scene.c_str());
  668. break;
  669. case VCamOutputType::SourceOutput:
  670. obs_data_set_string(obj, "source",
  671. vcamConfig.source.c_str());
  672. break;
  673. }
  674. obs_data_set_obj(saveData, "virtual-camera", obj);
  675. }
  676. if (api) {
  677. if (safeModeModuleData) {
  678. /* If we're in Safe Mode and have retained unloaded
  679. * plugin data, update the existing data object instead
  680. * of creating a new one. */
  681. api->on_save(safeModeModuleData);
  682. obs_data_set_obj(saveData, "modules",
  683. safeModeModuleData);
  684. } else {
  685. OBSDataAutoRelease moduleObj = obs_data_create();
  686. api->on_save(moduleObj);
  687. obs_data_set_obj(saveData, "modules", moduleObj);
  688. }
  689. }
  690. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  691. blog(LOG_ERROR, "Could not save scene data to %s", file);
  692. }
  693. void OBSBasic::DeferSaveBegin()
  694. {
  695. os_atomic_inc_long(&disableSaving);
  696. }
  697. void OBSBasic::DeferSaveEnd()
  698. {
  699. long result = os_atomic_dec_long(&disableSaving);
  700. if (result == 0) {
  701. SaveProject();
  702. }
  703. }
  704. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  705. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  706. {
  707. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  708. if (!data)
  709. return;
  710. OBSSourceAutoRelease source = obs_load_source(data);
  711. if (!source)
  712. return;
  713. obs_set_output_source(channel, source);
  714. const char *source_name = obs_source_get_name(source);
  715. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  716. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  717. obs_monitoring_type monitoring_type =
  718. obs_source_get_monitoring_type(source);
  719. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  720. const char *type =
  721. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  722. ? "monitor only"
  723. : "monitor and output";
  724. blog(LOG_INFO, " - monitoring: %s", type);
  725. }
  726. }
  727. static inline bool HasAudioDevices(const char *source_id)
  728. {
  729. const char *output_id = source_id;
  730. obs_properties_t *props = obs_get_source_properties(output_id);
  731. size_t count = 0;
  732. if (!props)
  733. return false;
  734. obs_property_t *devices = obs_properties_get(props, "device_id");
  735. if (devices)
  736. count = obs_property_list_item_count(devices);
  737. obs_properties_destroy(props);
  738. return count != 0;
  739. }
  740. void OBSBasic::CreateFirstRunSources()
  741. {
  742. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  743. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  744. if (hasDesktopAudio)
  745. ResetAudioDevice(App()->OutputAudioSource(), "default",
  746. Str("Basic.DesktopDevice1"), 1);
  747. if (hasInputAudio)
  748. ResetAudioDevice(App()->InputAudioSource(), "default",
  749. Str("Basic.AuxDevice1"), 3);
  750. }
  751. void OBSBasic::CreateDefaultScene(bool firstStart)
  752. {
  753. disableSaving++;
  754. ClearSceneData();
  755. InitDefaultTransitions();
  756. CreateDefaultQuickTransitions();
  757. ui->transitionDuration->setValue(300);
  758. SetTransition(fadeTransition);
  759. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  760. if (firstStart)
  761. CreateFirstRunSources();
  762. SetCurrentScene(scene, true);
  763. disableSaving--;
  764. }
  765. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  766. {
  767. for (int i = 0; i < lw->count(); i++) {
  768. QListWidgetItem *item = lw->item(i);
  769. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  770. if (newIndex != i) {
  771. item = lw->takeItem(i);
  772. lw->insertItem(newIndex, item);
  773. }
  774. break;
  775. }
  776. }
  777. }
  778. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  779. {
  780. size_t num = obs_data_array_count(array);
  781. for (size_t i = 0; i < num; i++) {
  782. OBSDataAutoRelease data = obs_data_array_item(array, i);
  783. const char *name = obs_data_get_string(data, "name");
  784. ReorderItemByName(ui->scenes, name, (int)i);
  785. }
  786. }
  787. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  788. {
  789. for (SavedProjectorInfo *info : savedProjectorsArray) {
  790. delete info;
  791. }
  792. savedProjectorsArray.clear();
  793. size_t num = obs_data_array_count(array);
  794. for (size_t i = 0; i < num; i++) {
  795. OBSDataAutoRelease data = obs_data_array_item(array, i);
  796. SavedProjectorInfo *info = new SavedProjectorInfo();
  797. info->monitor = obs_data_get_int(data, "monitor");
  798. info->type = static_cast<ProjectorType>(
  799. obs_data_get_int(data, "type"));
  800. info->geometry =
  801. std::string(obs_data_get_string(data, "geometry"));
  802. info->name = std::string(obs_data_get_string(data, "name"));
  803. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  804. info->alwaysOnTopOverridden =
  805. obs_data_get_bool(data, "alwaysOnTopOverridden");
  806. savedProjectorsArray.emplace_back(info);
  807. }
  808. }
  809. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  810. {
  811. const char *name = obs_source_get_name(filter);
  812. const char *id = obs_source_get_id(filter);
  813. int val = (int)(intptr_t)v_val;
  814. string indent;
  815. for (int i = 0; i < val; i++)
  816. indent += " ";
  817. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  818. }
  819. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  820. {
  821. obs_source_t *source = obs_sceneitem_get_source(item);
  822. const char *name = obs_source_get_name(source);
  823. const char *id = obs_source_get_id(source);
  824. int indent_count = (int)(intptr_t)v_val;
  825. string indent;
  826. for (int i = 0; i < indent_count; i++)
  827. indent += " ";
  828. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  829. obs_monitoring_type monitoring_type =
  830. obs_source_get_monitoring_type(source);
  831. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  832. const char *type =
  833. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  834. ? "monitor only"
  835. : "monitor and output";
  836. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  837. }
  838. int child_indent = 1 + indent_count;
  839. obs_source_enum_filters(source, LogFilter,
  840. (void *)(intptr_t)child_indent);
  841. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  842. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  843. if (show_tn)
  844. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  845. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  846. if (hide_tn)
  847. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  848. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  849. if (obs_sceneitem_is_group(item))
  850. obs_sceneitem_group_enum_items(item, LogSceneItem,
  851. (void *)(intptr_t)child_indent);
  852. return true;
  853. }
  854. void OBSBasic::LogScenes()
  855. {
  856. blog(LOG_INFO, "------------------------------------------------");
  857. blog(LOG_INFO, "Loaded scenes:");
  858. for (int i = 0; i < ui->scenes->count(); i++) {
  859. QListWidgetItem *item = ui->scenes->item(i);
  860. OBSScene scene = GetOBSRef<OBSScene>(item);
  861. obs_source_t *source = obs_scene_get_source(scene);
  862. const char *name = obs_source_get_name(source);
  863. blog(LOG_INFO, "- scene '%s':", name);
  864. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  865. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  866. }
  867. blog(LOG_INFO, "------------------------------------------------");
  868. }
  869. void OBSBasic::Load(const char *file)
  870. {
  871. disableSaving++;
  872. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  873. if (!data) {
  874. disableSaving--;
  875. blog(LOG_INFO, "No scene file found, creating default scene");
  876. CreateDefaultScene(true);
  877. SaveProject();
  878. return;
  879. }
  880. LoadData(data, file);
  881. }
  882. static inline void AddMissingFiles(void *data, obs_source_t *source)
  883. {
  884. obs_missing_files_t *f = (obs_missing_files_t *)data;
  885. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  886. obs_missing_files_append(f, sf);
  887. obs_missing_files_destroy(sf);
  888. }
  889. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  890. {
  891. ClearSceneData();
  892. ClearContextBar();
  893. /* Exit OBS if clearing scene data failed for some reason. */
  894. if (clearingFailed) {
  895. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"),
  896. QTStr("SourceLeak.Text"));
  897. close();
  898. return;
  899. }
  900. InitDefaultTransitions();
  901. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  902. devicePropertiesThread->wait();
  903. devicePropertiesThread.reset();
  904. }
  905. QApplication::sendPostedEvents(nullptr);
  906. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  907. if (api)
  908. api->on_preload(modulesObj);
  909. if (safe_mode || disable_3p_plugins) {
  910. /* Keep a reference to "modules" data so plugins that are not
  911. * loaded do not have their collection specific data lost. */
  912. safeModeModuleData = obs_data_get_obj(data, "modules");
  913. }
  914. OBSDataArrayAutoRelease sceneOrder =
  915. obs_data_get_array(data, "scene_order");
  916. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  917. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  918. OBSDataArrayAutoRelease transitions =
  919. obs_data_get_array(data, "transitions");
  920. const char *sceneName = obs_data_get_string(data, "current_scene");
  921. const char *programSceneName =
  922. obs_data_get_string(data, "current_program_scene");
  923. const char *transitionName =
  924. obs_data_get_string(data, "current_transition");
  925. if (!opt_starting_scene.empty()) {
  926. programSceneName = opt_starting_scene.c_str();
  927. if (!IsPreviewProgramMode())
  928. sceneName = opt_starting_scene.c_str();
  929. }
  930. int newDuration = obs_data_get_int(data, "transition_duration");
  931. if (!newDuration)
  932. newDuration = 300;
  933. if (!transitionName)
  934. transitionName = obs_source_get_name(fadeTransition);
  935. const char *curSceneCollection = config_get_string(
  936. App()->GlobalConfig(), "Basic", "SceneCollection");
  937. obs_data_set_default_string(data, "name", curSceneCollection);
  938. const char *name = obs_data_get_string(data, "name");
  939. OBSSourceAutoRelease curScene;
  940. OBSSourceAutoRelease curProgramScene;
  941. obs_source_t *curTransition;
  942. if (!name || !*name)
  943. name = curSceneCollection;
  944. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  945. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  946. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  947. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  948. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  949. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  950. if (!sources) {
  951. sources = std::move(groups);
  952. } else {
  953. obs_data_array_push_back_array(sources, groups);
  954. }
  955. obs_missing_files_t *files = obs_missing_files_create();
  956. obs_load_sources(sources, AddMissingFiles, files);
  957. if (transitions)
  958. LoadTransitions(transitions, AddMissingFiles, files);
  959. if (sceneOrder)
  960. LoadSceneListOrder(sceneOrder);
  961. curTransition = FindTransition(transitionName);
  962. if (!curTransition)
  963. curTransition = fadeTransition;
  964. ui->transitionDuration->setValue(newDuration);
  965. SetTransition(curTransition);
  966. retryScene:
  967. curScene = obs_get_source_by_name(sceneName);
  968. curProgramScene = obs_get_source_by_name(programSceneName);
  969. /* if the starting scene command line parameter is bad at all,
  970. * fall back to original settings */
  971. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  972. sceneName = obs_data_get_string(data, "current_scene");
  973. programSceneName =
  974. obs_data_get_string(data, "current_program_scene");
  975. opt_starting_scene.clear();
  976. goto retryScene;
  977. }
  978. SetCurrentScene(curScene.Get(), true);
  979. if (!curProgramScene)
  980. curProgramScene = std::move(curScene);
  981. if (IsPreviewProgramMode())
  982. TransitionToScene(curProgramScene.Get(), true);
  983. /* ------------------- */
  984. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  985. "SaveProjectors");
  986. if (projectorSave) {
  987. OBSDataArrayAutoRelease savedProjectors =
  988. obs_data_get_array(data, "saved_projectors");
  989. if (savedProjectors) {
  990. LoadSavedProjectors(savedProjectors);
  991. OpenSavedProjectors();
  992. activateWindow();
  993. }
  994. }
  995. /* ------------------- */
  996. std::string file_base = strrchr(file, '/') + 1;
  997. file_base.erase(file_base.size() - 5, 5);
  998. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  999. name);
  1000. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  1001. file_base.c_str());
  1002. OBSDataArrayAutoRelease quickTransitionData =
  1003. obs_data_get_array(data, "quick_transitions");
  1004. LoadQuickTransitions(quickTransitionData);
  1005. RefreshQuickTransitions();
  1006. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1007. ui->preview->SetLocked(previewLocked);
  1008. ui->actionLockPreview->setChecked(previewLocked);
  1009. /* ---------------------- */
  1010. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1011. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1012. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1013. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1014. if (fixedScaling) {
  1015. ui->preview->SetScalingLevel(scalingLevel);
  1016. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1017. }
  1018. ui->preview->SetFixedScaling(fixedScaling);
  1019. emit ui->preview->DisplayResized();
  1020. if (vcamEnabled) {
  1021. OBSDataAutoRelease obj =
  1022. obs_data_get_obj(data, "virtual-camera");
  1023. vcamConfig.type =
  1024. (VCamOutputType)obs_data_get_int(obj, "type2");
  1025. if (vcamConfig.type == VCamOutputType::Invalid)
  1026. vcamConfig.type =
  1027. (VCamOutputType)obs_data_get_int(obj, "type");
  1028. if (vcamConfig.type == VCamOutputType::Invalid) {
  1029. VCamInternalType internal =
  1030. (VCamInternalType)obs_data_get_int(obj,
  1031. "internal");
  1032. switch (internal) {
  1033. case VCamInternalType::Default:
  1034. vcamConfig.type = VCamOutputType::ProgramView;
  1035. break;
  1036. case VCamInternalType::Preview:
  1037. vcamConfig.type = VCamOutputType::PreviewOutput;
  1038. break;
  1039. }
  1040. }
  1041. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1042. vcamConfig.source = obs_data_get_string(obj, "source");
  1043. }
  1044. /* ---------------------- */
  1045. if (api)
  1046. api->on_load(modulesObj);
  1047. obs_data_release(data);
  1048. if (!opt_starting_scene.empty())
  1049. opt_starting_scene.clear();
  1050. if (opt_start_streaming && !safe_mode) {
  1051. blog(LOG_INFO, "Starting stream due to command line parameter");
  1052. QMetaObject::invokeMethod(this, "StartStreaming",
  1053. Qt::QueuedConnection);
  1054. opt_start_streaming = false;
  1055. }
  1056. if (opt_start_recording && !safe_mode) {
  1057. blog(LOG_INFO,
  1058. "Starting recording due to command line parameter");
  1059. QMetaObject::invokeMethod(this, "StartRecording",
  1060. Qt::QueuedConnection);
  1061. opt_start_recording = false;
  1062. }
  1063. if (opt_start_replaybuffer && !safe_mode) {
  1064. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  1065. Qt::QueuedConnection);
  1066. opt_start_replaybuffer = false;
  1067. }
  1068. if (opt_start_virtualcam && !safe_mode) {
  1069. QMetaObject::invokeMethod(this, "StartVirtualCam",
  1070. Qt::QueuedConnection);
  1071. opt_start_virtualcam = false;
  1072. }
  1073. LogScenes();
  1074. if (!App()->IsMissingFilesCheckDisabled())
  1075. ShowMissingFilesDialog(files);
  1076. disableSaving--;
  1077. if (vcamEnabled)
  1078. outputHandler->UpdateVirtualCamOutputSource();
  1079. if (api) {
  1080. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1081. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1082. }
  1083. }
  1084. #define SERVICE_PATH "service.json"
  1085. void OBSBasic::SaveService()
  1086. {
  1087. if (!service)
  1088. return;
  1089. char serviceJsonPath[512];
  1090. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1091. SERVICE_PATH);
  1092. if (ret <= 0)
  1093. return;
  1094. OBSDataAutoRelease data = obs_data_create();
  1095. OBSDataAutoRelease settings = obs_service_get_settings(service);
  1096. obs_data_set_string(data, "type", obs_service_get_type(service));
  1097. obs_data_set_obj(data, "settings", settings);
  1098. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  1099. blog(LOG_WARNING, "Failed to save service");
  1100. }
  1101. bool OBSBasic::LoadService()
  1102. {
  1103. const char *type;
  1104. char serviceJsonPath[512];
  1105. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1106. SERVICE_PATH);
  1107. if (ret <= 0)
  1108. return false;
  1109. OBSDataAutoRelease data =
  1110. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  1111. if (!data)
  1112. return false;
  1113. obs_data_set_default_string(data, "type", "rtmp_common");
  1114. type = obs_data_get_string(data, "type");
  1115. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  1116. OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys");
  1117. service = obs_service_create(type, "default_service", settings,
  1118. hotkey_data);
  1119. obs_service_release(service);
  1120. if (!service)
  1121. return false;
  1122. /* Enforce Opus on FTL if needed */
  1123. if (strcmp(obs_service_get_protocol(service), "FTL") == 0 ||
  1124. strcmp(obs_service_get_protocol(service), "WHIP") == 0) {
  1125. const char *option = config_get_string(
  1126. basicConfig, "SimpleOutput", "StreamAudioEncoder");
  1127. if (strcmp(option, "opus") != 0)
  1128. config_set_string(basicConfig, "SimpleOutput",
  1129. "StreamAudioEncoder", "opus");
  1130. option = config_get_string(basicConfig, "AdvOut",
  1131. "AudioEncoder");
  1132. if (strcmp(obs_get_encoder_codec(option), "opus") != 0)
  1133. config_set_string(basicConfig, "AdvOut", "AudioEncoder",
  1134. "ffmpeg_opus");
  1135. }
  1136. return true;
  1137. }
  1138. bool OBSBasic::InitService()
  1139. {
  1140. ProfileScope("OBSBasic::InitService");
  1141. if (LoadService())
  1142. return true;
  1143. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1144. nullptr);
  1145. if (!service)
  1146. return false;
  1147. obs_service_release(service);
  1148. return true;
  1149. }
  1150. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1151. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1152. 2.5, 2.75, 3.0, 0.0};
  1153. extern void CheckExistingCookieId();
  1154. #if OBS_RELEASE_CANDIDATE == 0 && OBS_BETA == 0
  1155. #define DEFAULT_CONTAINER "mkv"
  1156. #elif defined(__APPLE__)
  1157. #define DEFAULT_CONTAINER "fragmented_mov"
  1158. #else
  1159. #define DEFAULT_CONTAINER "fragmented_mp4"
  1160. #endif
  1161. bool OBSBasic::InitBasicConfigDefaults()
  1162. {
  1163. QList<QScreen *> screens = QGuiApplication::screens();
  1164. if (!screens.size()) {
  1165. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1166. "technically shouldn't be possible.");
  1167. return false;
  1168. }
  1169. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1170. uint32_t cx = primaryScreen->size().width();
  1171. uint32_t cy = primaryScreen->size().height();
  1172. cx *= devicePixelRatioF();
  1173. cy *= devicePixelRatioF();
  1174. bool oldResolutionDefaults = config_get_bool(
  1175. App()->GlobalConfig(), "General", "Pre19Defaults");
  1176. /* use 1920x1080 for new default base res if main monitor is above
  1177. * 1920x1080, but don't apply for people from older builds -- only to
  1178. * new users */
  1179. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1180. cx = 1920;
  1181. cy = 1080;
  1182. }
  1183. bool changed = false;
  1184. /* ----------------------------------------------------- */
  1185. /* move over old FFmpeg track settings */
  1186. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1187. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1188. int track = (int)config_get_int(basicConfig, "AdvOut",
  1189. "FFAudioTrack");
  1190. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1191. 1LL << (track - 1));
  1192. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1193. changed = true;
  1194. }
  1195. /* ----------------------------------------------------- */
  1196. /* move over mixer values in advanced if older config */
  1197. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1198. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1199. uint64_t track =
  1200. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1201. track = 1ULL << (track - 1);
  1202. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1203. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1204. changed = true;
  1205. }
  1206. /* ----------------------------------------------------- */
  1207. /* set twitch chat extensions to "both" if prev version */
  1208. /* is under 24.1 */
  1209. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1210. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1211. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1212. changed = true;
  1213. }
  1214. /* ----------------------------------------------------- */
  1215. /* move bitrate enforcement setting to new value */
  1216. if (config_has_user_value(basicConfig, "SimpleOutput",
  1217. "EnforceBitrate") &&
  1218. !config_has_user_value(basicConfig, "Stream1",
  1219. "IgnoreRecommended") &&
  1220. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1221. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1222. "EnforceBitrate");
  1223. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1224. !enforce);
  1225. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1226. true);
  1227. changed = true;
  1228. }
  1229. /* ----------------------------------------------------- */
  1230. /* enforce minimum retry delay of 1 second prior to 27.1 */
  1231. if (config_has_user_value(basicConfig, "Output", "RetryDelay")) {
  1232. int retryDelay =
  1233. config_get_uint(basicConfig, "Output", "RetryDelay");
  1234. if (retryDelay < 1) {
  1235. config_set_uint(basicConfig, "Output", "RetryDelay", 1);
  1236. changed = true;
  1237. }
  1238. }
  1239. /* ----------------------------------------------------- */
  1240. /* Migrate old container selection (if any) to new key. */
  1241. auto MigrateFormat = [&](const char *section) {
  1242. bool has_old_key = config_has_user_value(basicConfig, section,
  1243. "RecFormat");
  1244. bool has_new_key = config_has_user_value(basicConfig, section,
  1245. "RecFormat2");
  1246. if (!has_new_key && !has_old_key)
  1247. return;
  1248. string old_format = config_get_string(
  1249. basicConfig, section,
  1250. has_new_key ? "RecFormat2" : "RecFormat");
  1251. string new_format = old_format;
  1252. if (old_format == "ts")
  1253. new_format = "mpegts";
  1254. else if (old_format == "m3u8")
  1255. new_format = "hls";
  1256. else if (old_format == "fmp4")
  1257. new_format = "fragmented_mp4";
  1258. else if (old_format == "fmov")
  1259. new_format = "fragmented_mov";
  1260. if (new_format != old_format || !has_new_key) {
  1261. config_set_string(basicConfig, section, "RecFormat2",
  1262. new_format.c_str());
  1263. changed = true;
  1264. }
  1265. };
  1266. MigrateFormat("AdvOut");
  1267. MigrateFormat("SimpleOutput");
  1268. /* ----------------------------------------------------- */
  1269. if (changed)
  1270. config_save_safe(basicConfig, "tmp", nullptr);
  1271. /* ----------------------------------------------------- */
  1272. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1273. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1274. false);
  1275. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1276. GetDefaultVideoSavePath().c_str());
  1277. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat2",
  1278. DEFAULT_CONTAINER);
  1279. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1280. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1281. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1282. false);
  1283. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1284. "veryfast");
  1285. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset2",
  1286. "p5");
  1287. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1288. "Stream");
  1289. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1290. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1291. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1292. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1293. "Replay");
  1294. config_set_default_string(basicConfig, "SimpleOutput",
  1295. "StreamAudioEncoder", "aac");
  1296. config_set_default_string(basicConfig, "SimpleOutput",
  1297. "RecAudioEncoder", "aac");
  1298. config_set_default_uint(basicConfig, "SimpleOutput", "RecTracks",
  1299. (1 << 0));
  1300. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1301. true);
  1302. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1303. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1304. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1305. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1306. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1307. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1308. GetDefaultVideoSavePath().c_str());
  1309. config_set_default_string(basicConfig, "AdvOut", "RecFormat2",
  1310. DEFAULT_CONTAINER);
  1311. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1312. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1313. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1314. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1315. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1316. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1317. GetDefaultVideoSavePath().c_str());
  1318. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1319. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1320. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1321. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1322. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1323. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1324. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1325. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1326. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1327. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1328. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1329. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1330. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1331. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileTime", 15);
  1332. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileSize",
  1333. 2048);
  1334. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1335. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1336. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1337. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1338. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1339. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1340. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1341. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1342. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1343. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1344. config_save_safe(basicConfig, "tmp", nullptr);
  1345. }
  1346. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1347. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1348. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1349. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1350. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1351. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1352. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1353. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1354. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1355. config_set_default_string(basicConfig, "Output", "IPFamily",
  1356. "IPv4+IPv6");
  1357. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1358. false);
  1359. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1360. false);
  1361. int i = 0;
  1362. uint32_t scale_cx = cx;
  1363. uint32_t scale_cy = cy;
  1364. /* use a default scaled resolution that has a pixel count no higher
  1365. * than 1280x720 */
  1366. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1367. double scale = scaled_vals[i++];
  1368. scale_cx = uint32_t(double(cx) / scale);
  1369. scale_cy = uint32_t(double(cy) / scale);
  1370. }
  1371. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1372. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1373. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1374. * changing */
  1375. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1376. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1377. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1378. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1379. config_save_safe(basicConfig, "tmp", nullptr);
  1380. }
  1381. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1382. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1383. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1384. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1385. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1386. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1387. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1388. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1389. config_set_default_string(basicConfig, "Video", "ColorRange",
  1390. "Partial");
  1391. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1392. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1393. 1000);
  1394. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1395. "default");
  1396. config_set_default_string(
  1397. basicConfig, "Audio", "MonitoringDeviceName",
  1398. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1399. ".Default"));
  1400. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1401. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1402. "Stereo");
  1403. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1404. VOLUME_METER_DECAY_FAST);
  1405. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1406. CheckExistingCookieId();
  1407. return true;
  1408. }
  1409. extern bool EncoderAvailable(const char *encoder);
  1410. extern bool update_nvenc_presets(ConfigFile &config);
  1411. void OBSBasic::InitBasicConfigDefaults2()
  1412. {
  1413. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1414. "Pre23Defaults");
  1415. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1416. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1417. useNV ? SIMPLE_ENCODER_NVENC
  1418. : SIMPLE_ENCODER_X264);
  1419. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1420. useNV ? SIMPLE_ENCODER_NVENC
  1421. : SIMPLE_ENCODER_X264);
  1422. const char *aac_default = "ffmpeg_aac";
  1423. if (EncoderAvailable("CoreAudio_AAC"))
  1424. aac_default = "CoreAudio_AAC";
  1425. else if (EncoderAvailable("libfdk_aac"))
  1426. aac_default = "libfdk_aac";
  1427. config_set_default_string(basicConfig, "AdvOut", "AudioEncoder",
  1428. aac_default);
  1429. config_set_default_string(basicConfig, "AdvOut", "RecAudioEncoder",
  1430. aac_default);
  1431. if (update_nvenc_presets(basicConfig))
  1432. config_save_safe(basicConfig, "tmp", nullptr);
  1433. }
  1434. bool OBSBasic::InitBasicConfig()
  1435. {
  1436. ProfileScope("OBSBasic::InitBasicConfig");
  1437. char configPath[512];
  1438. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1439. if (ret <= 0) {
  1440. OBSErrorBox(nullptr, "Failed to get profile path");
  1441. return false;
  1442. }
  1443. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1444. OBSErrorBox(nullptr, "Failed to create profile path");
  1445. return false;
  1446. }
  1447. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1448. if (ret <= 0) {
  1449. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1450. return false;
  1451. }
  1452. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1453. if (code != CONFIG_SUCCESS) {
  1454. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1455. return false;
  1456. }
  1457. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1458. const char *curName = config_get_string(App()->GlobalConfig(),
  1459. "Basic", "Profile");
  1460. config_set_string(basicConfig, "General", "Name", curName);
  1461. basicConfig.SaveSafe("tmp");
  1462. }
  1463. return InitBasicConfigDefaults();
  1464. }
  1465. void OBSBasic::InitOBSCallbacks()
  1466. {
  1467. ProfileScope("OBSBasic::InitOBSCallbacks");
  1468. signalHandlers.reserve(signalHandlers.size() + 7);
  1469. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1470. OBSBasic::SourceCreated, this);
  1471. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1472. OBSBasic::SourceRemoved, this);
  1473. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1474. OBSBasic::SourceActivated, this);
  1475. signalHandlers.emplace_back(obs_get_signal_handler(),
  1476. "source_deactivate",
  1477. OBSBasic::SourceDeactivated, this);
  1478. signalHandlers.emplace_back(obs_get_signal_handler(),
  1479. "source_audio_activate",
  1480. OBSBasic::SourceAudioActivated, this);
  1481. signalHandlers.emplace_back(obs_get_signal_handler(),
  1482. "source_audio_deactivate",
  1483. OBSBasic::SourceAudioDeactivated, this);
  1484. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1485. OBSBasic::SourceRenamed, this);
  1486. }
  1487. void OBSBasic::InitPrimitives()
  1488. {
  1489. ProfileScope("OBSBasic::InitPrimitives");
  1490. obs_enter_graphics();
  1491. gs_render_start(true);
  1492. gs_vertex2f(0.0f, 0.0f);
  1493. gs_vertex2f(0.0f, 1.0f);
  1494. gs_vertex2f(1.0f, 0.0f);
  1495. gs_vertex2f(1.0f, 1.0f);
  1496. box = gs_render_save();
  1497. gs_render_start(true);
  1498. gs_vertex2f(0.0f, 0.0f);
  1499. gs_vertex2f(0.0f, 1.0f);
  1500. boxLeft = gs_render_save();
  1501. gs_render_start(true);
  1502. gs_vertex2f(0.0f, 0.0f);
  1503. gs_vertex2f(1.0f, 0.0f);
  1504. boxTop = gs_render_save();
  1505. gs_render_start(true);
  1506. gs_vertex2f(1.0f, 0.0f);
  1507. gs_vertex2f(1.0f, 1.0f);
  1508. boxRight = gs_render_save();
  1509. gs_render_start(true);
  1510. gs_vertex2f(0.0f, 1.0f);
  1511. gs_vertex2f(1.0f, 1.0f);
  1512. boxBottom = gs_render_save();
  1513. gs_render_start(true);
  1514. for (int i = 0; i <= 360; i += (360 / 20)) {
  1515. float pos = RAD(float(i));
  1516. gs_vertex2f(cosf(pos), sinf(pos));
  1517. }
  1518. circle = gs_render_save();
  1519. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1520. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1521. obs_leave_graphics();
  1522. }
  1523. void OBSBasic::ReplayBufferClicked()
  1524. {
  1525. if (outputHandler->ReplayBufferActive())
  1526. StopReplayBuffer();
  1527. else
  1528. StartReplayBuffer();
  1529. };
  1530. void OBSBasic::AddVCamButton()
  1531. {
  1532. vcamButton = new ControlsSplitButton(
  1533. QTStr("Basic.Main.StartVirtualCam"), "vcamButton",
  1534. &OBSBasic::VCamButtonClicked);
  1535. vcamButton->addIcon(QTStr("Basic.Main.VirtualCamConfig"),
  1536. QStringLiteral("configIconSmall"),
  1537. &OBSBasic::VCamConfigButtonClicked);
  1538. vcamButton->insert(2);
  1539. }
  1540. void OBSBasic::ResetOutputs()
  1541. {
  1542. ProfileScope("OBSBasic::ResetOutputs");
  1543. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1544. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1545. if (!outputHandler || !outputHandler->Active()) {
  1546. outputHandler.reset();
  1547. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1548. : CreateSimpleOutputHandler(this));
  1549. delete replayBufferButton;
  1550. if (outputHandler->replayBuffer) {
  1551. replayBufferButton = new ControlsSplitButton(
  1552. QTStr("Basic.Main.StartReplayBuffer"),
  1553. "replayBufferButton",
  1554. &OBSBasic::ReplayBufferClicked);
  1555. replayBufferButton->insert(2);
  1556. }
  1557. if (sysTrayReplayBuffer)
  1558. sysTrayReplayBuffer->setEnabled(
  1559. !!outputHandler->replayBuffer);
  1560. } else {
  1561. outputHandler->Update();
  1562. }
  1563. }
  1564. #define STARTUP_SEPARATOR \
  1565. "==== Startup complete ==============================================="
  1566. #define SHUTDOWN_SEPARATOR \
  1567. "==== Shutting down =================================================="
  1568. #define UNSUPPORTED_ERROR \
  1569. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1570. "not found. Your GPU may not be supported."
  1571. #define UNKNOWN_ERROR \
  1572. "Failed to initialize video. Your GPU may not be supported, " \
  1573. "or your graphics drivers may need to be updated."
  1574. void OBSBasic::OBSInit()
  1575. {
  1576. ProfileScope("OBSBasic::OBSInit");
  1577. const char *sceneCollection = config_get_string(
  1578. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1579. char savePath[1024];
  1580. char fileName[1024];
  1581. int ret;
  1582. if (!sceneCollection)
  1583. throw "Failed to get scene collection name";
  1584. ret = snprintf(fileName, sizeof(fileName),
  1585. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1586. if (ret <= 0)
  1587. throw "Failed to create scene collection file name";
  1588. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1589. if (ret <= 0)
  1590. throw "Failed to get scene collection json file path";
  1591. if (!InitBasicConfig())
  1592. throw "Failed to load basic.ini";
  1593. if (!ResetAudio())
  1594. throw "Failed to initialize audio";
  1595. ret = ResetVideo();
  1596. switch (ret) {
  1597. case OBS_VIDEO_MODULE_NOT_FOUND:
  1598. throw "Failed to initialize video: Graphics module not found";
  1599. case OBS_VIDEO_NOT_SUPPORTED:
  1600. throw UNSUPPORTED_ERROR;
  1601. case OBS_VIDEO_INVALID_PARAM:
  1602. throw "Failed to initialize video: Invalid parameters";
  1603. default:
  1604. if (ret != OBS_VIDEO_SUCCESS)
  1605. throw UNKNOWN_ERROR;
  1606. }
  1607. /* load audio monitoring */
  1608. if (obs_audio_monitoring_available()) {
  1609. const char *device_name = config_get_string(
  1610. basicConfig, "Audio", "MonitoringDeviceName");
  1611. const char *device_id = config_get_string(basicConfig, "Audio",
  1612. "MonitoringDeviceId");
  1613. obs_set_audio_monitoring_device(device_name, device_id);
  1614. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1615. device_name, device_id);
  1616. }
  1617. InitOBSCallbacks();
  1618. InitHotkeys();
  1619. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1620. * to ship with */
  1621. #if defined(_WIN32) && !defined(_DEBUG)
  1622. LoadLibraryW(L"Qt6Network");
  1623. #endif
  1624. struct obs_module_failure_info mfi;
  1625. /* Safe Mode disables third-party plugins so we don't need to add earch
  1626. * paths outside the OBS bundle/installation. */
  1627. if (safe_mode || disable_3p_plugins) {
  1628. SetSafeModuleNames();
  1629. } else {
  1630. AddExtraModulePaths();
  1631. }
  1632. blog(LOG_INFO, "---------------------------------");
  1633. obs_load_all_modules2(&mfi);
  1634. blog(LOG_INFO, "---------------------------------");
  1635. obs_log_loaded_modules();
  1636. blog(LOG_INFO, "---------------------------------");
  1637. obs_post_load_modules();
  1638. BPtr<char *> failed_modules = mfi.failed_modules;
  1639. #ifdef BROWSER_AVAILABLE
  1640. cef = obs_browser_init_panel();
  1641. cef_js_avail = cef && obs_browser_qcef_version() >= 3;
  1642. #endif
  1643. OBSDataAutoRelease obsData = obs_get_private_data();
  1644. vcamEnabled = obs_data_get_bool(obsData, "vcamEnabled");
  1645. if (vcamEnabled) {
  1646. AddVCamButton();
  1647. }
  1648. InitBasicConfigDefaults2();
  1649. CheckForSimpleModeX264Fallback();
  1650. blog(LOG_INFO, STARTUP_SEPARATOR);
  1651. if (!InitService())
  1652. throw "Failed to initialize service";
  1653. ResetOutputs();
  1654. CreateHotkeys();
  1655. InitPrimitives();
  1656. sceneDuplicationMode = config_get_bool(
  1657. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1658. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1659. "SwapScenesMode");
  1660. editPropertiesMode = config_get_bool(
  1661. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1662. if (!opt_studio_mode) {
  1663. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1664. "BasicWindow",
  1665. "PreviewProgramMode"));
  1666. } else {
  1667. SetPreviewProgramMode(true);
  1668. opt_studio_mode = false;
  1669. }
  1670. #define SET_VISIBILITY(name, control) \
  1671. do { \
  1672. if (config_has_user_value(App()->GlobalConfig(), \
  1673. "BasicWindow", name)) { \
  1674. bool visible = config_get_bool(App()->GlobalConfig(), \
  1675. "BasicWindow", name); \
  1676. ui->control->setChecked(visible); \
  1677. } \
  1678. } while (false)
  1679. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1680. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1681. #undef SET_VISIBILITY
  1682. bool sourceIconsVisible = config_get_bool(
  1683. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1684. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1685. bool contextVisible = config_get_bool(
  1686. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1687. ui->toggleContextBar->setChecked(contextVisible);
  1688. ui->contextContainer->setVisible(contextVisible);
  1689. if (contextVisible)
  1690. UpdateContextBar(true);
  1691. UpdateEditMenu();
  1692. {
  1693. ProfileScope("OBSBasic::Load");
  1694. disableSaving--;
  1695. Load(savePath);
  1696. disableSaving++;
  1697. }
  1698. loaded = true;
  1699. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1700. "PreviewEnabled");
  1701. if (!previewEnabled && !IsPreviewProgramMode())
  1702. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1703. Qt::QueuedConnection,
  1704. Q_ARG(bool, previewEnabled));
  1705. else if (!previewEnabled && IsPreviewProgramMode())
  1706. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1707. Qt::QueuedConnection,
  1708. Q_ARG(bool, true));
  1709. RefreshSceneCollections();
  1710. RefreshProfiles();
  1711. disableSaving--;
  1712. auto addDisplay = [this](OBSQTDisplay *window) {
  1713. obs_display_add_draw_callback(window->GetDisplay(),
  1714. OBSBasic::RenderMain, this);
  1715. struct obs_video_info ovi;
  1716. if (obs_get_video_info(&ovi))
  1717. ResizePreview(ovi.base_width, ovi.base_height);
  1718. };
  1719. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1720. /* Show the main window, unless the tray icon isn't available
  1721. * or neither the setting nor flag for starting minimized is set. */
  1722. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1723. "BasicWindow", "SysTrayEnabled");
  1724. bool sysTrayWhenStarted = config_get_bool(
  1725. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1726. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1727. sysTrayEnabled &&
  1728. (opt_minimize_tray || sysTrayWhenStarted);
  1729. #ifdef _WIN32
  1730. SetWin32DropStyle(this);
  1731. if (!hideWindowOnStart)
  1732. show();
  1733. #endif
  1734. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1735. "AlwaysOnTop");
  1736. #ifdef ENABLE_WAYLAND
  1737. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1738. #else
  1739. bool isWayland = false;
  1740. #endif
  1741. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1742. SetAlwaysOnTop(this, true);
  1743. ui->actionAlwaysOnTop->setChecked(true);
  1744. } else if (isWayland) {
  1745. if (opt_always_on_top)
  1746. blog(LOG_INFO,
  1747. "Always On Top not available on Wayland, ignoring.");
  1748. ui->actionAlwaysOnTop->setEnabled(false);
  1749. ui->actionAlwaysOnTop->setVisible(false);
  1750. }
  1751. #ifndef _WIN32
  1752. if (!hideWindowOnStart)
  1753. show();
  1754. #endif
  1755. /* setup stats dock */
  1756. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1757. statsDock->setWidget(statsDlg);
  1758. /* ----------------------------- */
  1759. /* add custom browser docks */
  1760. #if defined(BROWSER_AVAILABLE) && defined(YOUTUBE_ENABLED)
  1761. YouTubeAppDock::CleanupYouTubeUrls();
  1762. #endif
  1763. #ifdef BROWSER_AVAILABLE
  1764. if (cef) {
  1765. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1766. "CustomBrowserDocks"),
  1767. this);
  1768. ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(),
  1769. action);
  1770. connect(action, &QAction::triggered, this,
  1771. &OBSBasic::ManageExtraBrowserDocks);
  1772. ui->menuDocks->insertSeparator(
  1773. ui->scenesDock->toggleViewAction());
  1774. LoadExtraBrowserDocks();
  1775. }
  1776. #endif
  1777. #ifdef YOUTUBE_ENABLED
  1778. /* setup YouTube app dock */
  1779. if (YouTubeAppDock::IsYTServiceSelected())
  1780. youtubeAppDock = new YouTubeAppDock();
  1781. #endif
  1782. const char *dockStateStr = config_get_string(
  1783. App()->GlobalConfig(), "BasicWindow", "DockState");
  1784. if (!dockStateStr) {
  1785. on_resetDocks_triggered(true);
  1786. } else {
  1787. QByteArray dockState =
  1788. QByteArray::fromBase64(QByteArray(dockStateStr));
  1789. if (!restoreState(dockState))
  1790. on_resetDocks_triggered(true);
  1791. }
  1792. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1793. "Pre23Defaults");
  1794. if (pre23Defaults) {
  1795. bool resetDockLock23 = config_get_bool(
  1796. App()->GlobalConfig(), "General", "ResetDockLock23");
  1797. if (!resetDockLock23) {
  1798. config_set_bool(App()->GlobalConfig(), "General",
  1799. "ResetDockLock23", true);
  1800. config_remove_value(App()->GlobalConfig(),
  1801. "BasicWindow", "DocksLocked");
  1802. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1803. }
  1804. }
  1805. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1806. "DocksLocked");
  1807. on_lockDocks_toggled(docksLocked);
  1808. ui->lockDocks->blockSignals(true);
  1809. ui->lockDocks->setChecked(docksLocked);
  1810. ui->lockDocks->blockSignals(false);
  1811. bool sideDocks = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1812. "SideDocks");
  1813. on_sideDocks_toggled(sideDocks);
  1814. ui->sideDocks->blockSignals(true);
  1815. ui->sideDocks->setChecked(sideDocks);
  1816. ui->sideDocks->blockSignals(false);
  1817. SystemTray(true);
  1818. TaskbarOverlayInit();
  1819. #ifdef __APPLE__
  1820. disableColorSpaceConversion(this);
  1821. #endif
  1822. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1823. "General", "LastVersion");
  1824. bool first_run =
  1825. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1826. if (!first_run) {
  1827. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1828. true);
  1829. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1830. }
  1831. if (!first_run && !has_last_version && !Active())
  1832. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1833. Qt::QueuedConnection);
  1834. #if (defined(_WIN32) || defined(__APPLE__)) && \
  1835. (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0)
  1836. /* Automatically set branch to "beta" the first time a pre-release build is run. */
  1837. if (!config_get_bool(App()->GlobalConfig(), "General",
  1838. "AutoBetaOptIn")) {
  1839. config_set_string(App()->GlobalConfig(), "General",
  1840. "UpdateBranch", "beta");
  1841. config_set_bool(App()->GlobalConfig(), "General",
  1842. "AutoBetaOptIn", true);
  1843. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1844. }
  1845. #endif
  1846. TimedCheckForUpdates();
  1847. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1848. "VerticalVolControl"));
  1849. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1850. on_stats_triggered();
  1851. OBSBasicStats::InitializeValues();
  1852. /* ----------------------- */
  1853. /* Add multiview menu */
  1854. ui->viewMenu->addSeparator();
  1855. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  1856. &OBSBasic::OpenMultiviewProjector);
  1857. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1858. &OBSBasic::UpdateMultiviewProjectorMenu);
  1859. ui->sources->UpdateIcons();
  1860. #if !defined(_WIN32)
  1861. delete ui->actionShowCrashLogs;
  1862. delete ui->actionUploadLastCrashLog;
  1863. delete ui->menuCrashLogs;
  1864. delete ui->actionRepair;
  1865. ui->actionShowCrashLogs = nullptr;
  1866. ui->actionUploadLastCrashLog = nullptr;
  1867. ui->menuCrashLogs = nullptr;
  1868. ui->actionRepair = nullptr;
  1869. #if !defined(__APPLE__)
  1870. delete ui->actionCheckForUpdates;
  1871. ui->actionCheckForUpdates = nullptr;
  1872. #endif
  1873. #endif
  1874. #ifdef __APPLE__
  1875. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  1876. delete ui->actionFullscreenInterface;
  1877. ui->actionFullscreenInterface = nullptr;
  1878. #else
  1879. /* Don't show menu to raise macOS-only permissions dialog */
  1880. delete ui->actionShowMacPermissions;
  1881. ui->actionShowMacPermissions = nullptr;
  1882. #endif
  1883. #if defined(_WIN32) || defined(__APPLE__)
  1884. if (App()->IsUpdaterDisabled()) {
  1885. ui->actionCheckForUpdates->setEnabled(false);
  1886. #if defined(_WIN32)
  1887. ui->actionRepair->setEnabled(false);
  1888. #endif
  1889. }
  1890. #endif
  1891. #ifndef WHATSNEW_ENABLED
  1892. delete ui->actionShowWhatsNew;
  1893. ui->actionShowWhatsNew = nullptr;
  1894. #endif
  1895. if (safe_mode) {
  1896. ui->actionRestartSafe->setText(
  1897. QTStr("Basic.MainMenu.Help.RestartNormal"));
  1898. }
  1899. UpdatePreviewProgramIndicators();
  1900. OnFirstLoad();
  1901. if (!hideWindowOnStart)
  1902. activateWindow();
  1903. /* ------------------------------------------- */
  1904. /* display warning message for failed modules */
  1905. if (mfi.count) {
  1906. QString failed_plugins;
  1907. char **plugin = mfi.failed_modules;
  1908. while (*plugin) {
  1909. failed_plugins += *plugin;
  1910. failed_plugins += "\n";
  1911. plugin++;
  1912. }
  1913. QString failed_msg =
  1914. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  1915. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  1916. failed_msg);
  1917. }
  1918. }
  1919. void OBSBasic::OnFirstLoad()
  1920. {
  1921. if (api)
  1922. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1923. #ifdef WHATSNEW_ENABLED
  1924. /* Attempt to load init screen if available */
  1925. if (cef) {
  1926. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1927. connect(wnit, &WhatsNewInfoThread::Result, this,
  1928. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  1929. introCheckThread.reset(wnit);
  1930. introCheckThread->start();
  1931. }
  1932. #endif
  1933. Auth::Load();
  1934. bool showLogViewerOnStartup = config_get_bool(
  1935. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1936. if (showLogViewerOnStartup)
  1937. on_actionViewCurrentLog_triggered();
  1938. }
  1939. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1940. #define CUR_VER \
  1941. ((uint64_t)OBS_RELEASE_CANDIDATE_VER << 16ULL | OBS_RELEASE_CANDIDATE)
  1942. #define LAST_INFO_VERSION_STRING "InfoLastRCVersion"
  1943. #elif OBS_BETA > 0
  1944. #define CUR_VER ((uint64_t)OBS_BETA_VER << 16ULL | OBS_BETA)
  1945. #define LAST_INFO_VERSION_STRING "InfoLastBetaVersion"
  1946. #else
  1947. #define CUR_VER ((uint64_t)LIBOBS_API_VER << 16ULL)
  1948. #define LAST_INFO_VERSION_STRING "InfoLastVersion"
  1949. #endif
  1950. /* shows a "what's new" page on startup of new versions using CEF */
  1951. void OBSBasic::ReceivedIntroJson(const QString &text)
  1952. {
  1953. #ifdef WHATSNEW_ENABLED
  1954. if (closing)
  1955. return;
  1956. WhatsNewList items;
  1957. try {
  1958. nlohmann::json json = nlohmann::json::parse(text.toStdString());
  1959. items = json.get<WhatsNewList>();
  1960. } catch (nlohmann::json::exception &e) {
  1961. blog(LOG_WARNING, "Parsing whatsnew data failed: %s", e.what());
  1962. return;
  1963. }
  1964. std::string info_url;
  1965. int info_increment = -1;
  1966. /* check to see if there's an info page for this version */
  1967. for (const WhatsNewItem &item : items) {
  1968. if (item.os) {
  1969. WhatsNewPlatforms platforms = *item.os;
  1970. #ifdef _WIN32
  1971. if (!platforms.windows)
  1972. continue;
  1973. #elif defined(__APPLE__)
  1974. if (!platforms.macos)
  1975. continue;
  1976. #else
  1977. if (!platforms.linux)
  1978. continue;
  1979. #endif
  1980. }
  1981. int major = 0;
  1982. int minor = 0;
  1983. sscanf(item.version.c_str(), "%d.%d", &major, &minor);
  1984. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1985. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1986. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1987. item.RC == OBS_RELEASE_CANDIDATE) {
  1988. #elif OBS_BETA > 0
  1989. if (major == OBS_BETA_MAJOR && minor == OBS_BETA_MINOR &&
  1990. item.Beta == OBS_BETA) {
  1991. #else
  1992. if (major == LIBOBS_API_MAJOR_VER &&
  1993. minor == LIBOBS_API_MINOR_VER && item.RC == 0 &&
  1994. item.Beta == 0) {
  1995. #endif
  1996. info_url = item.url;
  1997. info_increment = item.increment;
  1998. }
  1999. }
  2000. /* this version was not found, or no info for this version */
  2001. if (info_increment == -1) {
  2002. return;
  2003. }
  2004. uint64_t lastVersion = config_get_uint(App()->GlobalConfig(), "General",
  2005. LAST_INFO_VERSION_STRING);
  2006. int current_version_increment = -1;
  2007. if ((lastVersion & ~0xFFFF0000ULL) < (CUR_VER & ~0xFFFF0000ULL)) {
  2008. config_set_int(App()->GlobalConfig(), "General",
  2009. "InfoIncrement", -1);
  2010. config_set_uint(App()->GlobalConfig(), "General",
  2011. LAST_INFO_VERSION_STRING, CUR_VER);
  2012. } else {
  2013. current_version_increment = config_get_int(
  2014. App()->GlobalConfig(), "General", "InfoIncrement");
  2015. }
  2016. if (info_increment <= current_version_increment) {
  2017. return;
  2018. }
  2019. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  2020. info_increment);
  2021. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2022. cef->init_browser();
  2023. WhatsNewBrowserInitThread *wnbit =
  2024. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  2025. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  2026. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  2027. whatsNewInitThread.reset(wnbit);
  2028. whatsNewInitThread->start();
  2029. #else
  2030. UNUSED_PARAMETER(text);
  2031. #endif
  2032. }
  2033. #undef CUR_VER
  2034. #undef LAST_INFO_VERSION_STRING
  2035. void OBSBasic::ShowWhatsNew(const QString &url)
  2036. {
  2037. #ifdef BROWSER_AVAILABLE
  2038. if (closing)
  2039. return;
  2040. std::string info_url = QT_TO_UTF8(url);
  2041. QDialog *dlg = new QDialog(this);
  2042. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  2043. dlg->setWindowTitle("What's New");
  2044. dlg->resize(700, 600);
  2045. Qt::WindowFlags flags = dlg->windowFlags();
  2046. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  2047. dlg->setWindowFlags(flags & (~helpFlag));
  2048. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  2049. if (!cefWidget) {
  2050. return;
  2051. }
  2052. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  2053. SLOT(setWindowTitle(const QString &)));
  2054. QPushButton *close = new QPushButton(QTStr("Close"));
  2055. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  2056. QHBoxLayout *bottomLayout = new QHBoxLayout();
  2057. bottomLayout->addStretch();
  2058. bottomLayout->addWidget(close);
  2059. bottomLayout->addStretch();
  2060. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  2061. topLayout->addWidget(cefWidget);
  2062. topLayout->addLayout(bottomLayout);
  2063. dlg->show();
  2064. #else
  2065. UNUSED_PARAMETER(url);
  2066. #endif
  2067. }
  2068. void OBSBasic::UpdateMultiviewProjectorMenu()
  2069. {
  2070. ui->multiviewProjectorMenu->clear();
  2071. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  2072. &OBSBasic::OpenMultiviewProjector);
  2073. }
  2074. void OBSBasic::InitHotkeys()
  2075. {
  2076. ProfileScope("OBSBasic::InitHotkeys");
  2077. struct obs_hotkeys_translations t = {};
  2078. t.insert = Str("Hotkeys.Insert");
  2079. t.del = Str("Hotkeys.Delete");
  2080. t.home = Str("Hotkeys.Home");
  2081. t.end = Str("Hotkeys.End");
  2082. t.page_up = Str("Hotkeys.PageUp");
  2083. t.page_down = Str("Hotkeys.PageDown");
  2084. t.num_lock = Str("Hotkeys.NumLock");
  2085. t.scroll_lock = Str("Hotkeys.ScrollLock");
  2086. t.caps_lock = Str("Hotkeys.CapsLock");
  2087. t.backspace = Str("Hotkeys.Backspace");
  2088. t.tab = Str("Hotkeys.Tab");
  2089. t.print = Str("Hotkeys.Print");
  2090. t.pause = Str("Hotkeys.Pause");
  2091. t.left = Str("Hotkeys.Left");
  2092. t.right = Str("Hotkeys.Right");
  2093. t.up = Str("Hotkeys.Up");
  2094. t.down = Str("Hotkeys.Down");
  2095. #ifdef _WIN32
  2096. t.meta = Str("Hotkeys.Windows");
  2097. #else
  2098. t.meta = Str("Hotkeys.Super");
  2099. #endif
  2100. t.menu = Str("Hotkeys.Menu");
  2101. t.space = Str("Hotkeys.Space");
  2102. t.numpad_num = Str("Hotkeys.NumpadNum");
  2103. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  2104. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  2105. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  2106. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  2107. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  2108. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  2109. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  2110. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  2111. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  2112. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  2113. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  2114. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  2115. t.mouse_num = Str("Hotkeys.MouseButton");
  2116. t.escape = Str("Hotkeys.Escape");
  2117. obs_hotkeys_set_translations(&t);
  2118. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  2119. Str("Push-to-mute"),
  2120. Str("Push-to-talk"));
  2121. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  2122. Str("SceneItemHide"));
  2123. obs_hotkey_enable_callback_rerouting(true);
  2124. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  2125. }
  2126. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  2127. {
  2128. obs_hotkey_trigger_routed_callback(id, pressed);
  2129. }
  2130. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  2131. {
  2132. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2133. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  2134. Q_ARG(obs_hotkey_id, id),
  2135. Q_ARG(bool, pressed));
  2136. }
  2137. void OBSBasic::CreateHotkeys()
  2138. {
  2139. ProfileScope("OBSBasic::CreateHotkeys");
  2140. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  2141. const char *info =
  2142. config_get_string(basicConfig, "Hotkeys", name);
  2143. if (!info)
  2144. return {};
  2145. OBSDataAutoRelease data = obs_data_create_from_json(info);
  2146. if (!data)
  2147. return {};
  2148. return data.Get();
  2149. };
  2150. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  2151. OBSDataArrayAutoRelease array =
  2152. obs_data_get_array(LoadHotkeyData(name), "bindings");
  2153. obs_hotkey_load(id, array);
  2154. };
  2155. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  2156. const char *name1,
  2157. const char *oldName = NULL) {
  2158. if (oldName) {
  2159. const auto info = config_get_string(basicConfig,
  2160. "Hotkeys", oldName);
  2161. if (info) {
  2162. config_set_string(basicConfig, "Hotkeys", name0,
  2163. info);
  2164. config_set_string(basicConfig, "Hotkeys", name1,
  2165. info);
  2166. config_remove_value(basicConfig, "Hotkeys",
  2167. oldName);
  2168. config_save(basicConfig);
  2169. }
  2170. }
  2171. OBSDataArrayAutoRelease array0 =
  2172. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  2173. OBSDataArrayAutoRelease array1 =
  2174. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  2175. obs_hotkey_pair_load(id, array0, array1);
  2176. };
  2177. #define MAKE_CALLBACK(pred, method, log_action) \
  2178. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  2179. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  2180. if ((pred) && pressed) { \
  2181. blog(LOG_INFO, log_action " due to hotkey"); \
  2182. method(); \
  2183. return true; \
  2184. } \
  2185. return false; \
  2186. }
  2187. streamingHotkeys = obs_hotkey_pair_register_frontend(
  2188. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  2189. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  2190. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  2191. basic.ui->streamButton->isEnabled(),
  2192. basic.StartStreaming, "Starting stream"),
  2193. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  2194. basic.ui->streamButton->isEnabled(),
  2195. basic.StopStreaming, "Stopping stream"),
  2196. this, this);
  2197. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  2198. "OBSBasic.StopStreaming");
  2199. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2200. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2201. if (basic.outputHandler->StreamingActive() && pressed) {
  2202. basic.ForceStopStreaming();
  2203. }
  2204. };
  2205. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  2206. "OBSBasic.ForceStopStreaming",
  2207. Str("Basic.Main.ForceStopStreaming"), cb, this);
  2208. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  2209. recordingHotkeys = obs_hotkey_pair_register_frontend(
  2210. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  2211. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  2212. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  2213. !basic.ui->recordButton->isChecked(),
  2214. basic.StartRecording, "Starting recording"),
  2215. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  2216. basic.ui->recordButton->isChecked(),
  2217. basic.StopRecording, "Stopping recording"),
  2218. this, this);
  2219. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  2220. "OBSBasic.StopRecording");
  2221. pauseHotkeys = obs_hotkey_pair_register_frontend(
  2222. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  2223. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  2224. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  2225. basic.PauseRecording, "Pausing recording"),
  2226. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  2227. basic.UnpauseRecording, "Unpausing recording"),
  2228. this, this);
  2229. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  2230. "OBSBasic.UnpauseRecording");
  2231. splitFileHotkey = obs_hotkey_register_frontend(
  2232. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  2233. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2234. if (pressed)
  2235. obs_frontend_recording_split_file();
  2236. },
  2237. this);
  2238. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  2239. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  2240. "OBSBasic.StartReplayBuffer",
  2241. Str("Basic.Main.StartReplayBuffer"),
  2242. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  2243. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  2244. basic.StartReplayBuffer,
  2245. "Starting replay buffer"),
  2246. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2247. basic.StopReplayBuffer, "Stopping replay buffer"),
  2248. this, this);
  2249. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2250. "OBSBasic.StopReplayBuffer");
  2251. if (vcamEnabled) {
  2252. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2253. "OBSBasic.StartVirtualCam",
  2254. Str("Basic.Main.StartVirtualCam"),
  2255. "OBSBasic.StopVirtualCam",
  2256. Str("Basic.Main.StopVirtualCam"),
  2257. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2258. basic.StartVirtualCam,
  2259. "Starting virtual camera"),
  2260. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2261. basic.StopVirtualCam,
  2262. "Stopping virtual camera"),
  2263. this, this);
  2264. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2265. "OBSBasic.StopVirtualCam");
  2266. }
  2267. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2268. "OBSBasic.EnablePreview",
  2269. Str("Basic.Main.PreviewConextMenu.Enable"),
  2270. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2271. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2272. "Enabling preview"),
  2273. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2274. "Disabling preview"),
  2275. this, this);
  2276. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2277. "OBSBasic.DisablePreview");
  2278. togglePreviewProgramHotkeys = obs_hotkey_pair_register_frontend(
  2279. "OBSBasic.EnablePreviewProgram",
  2280. Str("Basic.EnablePreviewProgramMode"),
  2281. "OBSBasic.DisablePreviewProgram",
  2282. Str("Basic.DisablePreviewProgramMode"),
  2283. MAKE_CALLBACK(!basic.IsPreviewProgramMode(),
  2284. basic.EnablePreviewProgram,
  2285. "Enabling preview program"),
  2286. MAKE_CALLBACK(basic.IsPreviewProgramMode(),
  2287. basic.DisablePreviewProgram,
  2288. "Disabling preview program"),
  2289. this, this);
  2290. LoadHotkeyPair(togglePreviewProgramHotkeys,
  2291. "OBSBasic.EnablePreviewProgram",
  2292. "OBSBasic.DisablePreviewProgram",
  2293. "OBSBasic.TogglePreviewProgram");
  2294. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2295. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2296. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2297. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2298. basic.ShowContextBar, "Showing Context Bar"),
  2299. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2300. basic.HideContextBar, "Hiding Context Bar"),
  2301. this, this);
  2302. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2303. "OBSBasic.HideContextBar");
  2304. #undef MAKE_CALLBACK
  2305. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2306. bool pressed) {
  2307. if (pressed)
  2308. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2309. "TransitionClicked",
  2310. Qt::QueuedConnection);
  2311. };
  2312. transitionHotkey = obs_hotkey_register_frontend(
  2313. "OBSBasic.Transition", Str("Transition"), transition, this);
  2314. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2315. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2316. bool pressed) {
  2317. if (pressed)
  2318. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2319. "ResetStatsHotkey",
  2320. Qt::QueuedConnection);
  2321. };
  2322. statsHotkey = obs_hotkey_register_frontend(
  2323. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2324. resetStats, this);
  2325. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2326. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2327. bool pressed) {
  2328. if (pressed)
  2329. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2330. "Screenshot",
  2331. Qt::QueuedConnection);
  2332. };
  2333. screenshotHotkey = obs_hotkey_register_frontend(
  2334. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2335. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2336. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2337. bool pressed) {
  2338. if (pressed)
  2339. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2340. "ScreenshotSelectedSource",
  2341. Qt::QueuedConnection);
  2342. };
  2343. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2344. "OBSBasic.SelectedSourceScreenshot",
  2345. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2346. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2347. }
  2348. void OBSBasic::ClearHotkeys()
  2349. {
  2350. obs_hotkey_pair_unregister(streamingHotkeys);
  2351. obs_hotkey_pair_unregister(recordingHotkeys);
  2352. obs_hotkey_pair_unregister(pauseHotkeys);
  2353. obs_hotkey_unregister(splitFileHotkey);
  2354. obs_hotkey_pair_unregister(replayBufHotkeys);
  2355. obs_hotkey_pair_unregister(vcamHotkeys);
  2356. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2357. obs_hotkey_pair_unregister(contextBarHotkeys);
  2358. obs_hotkey_pair_unregister(togglePreviewProgramHotkeys);
  2359. obs_hotkey_unregister(forceStreamingStopHotkey);
  2360. obs_hotkey_unregister(transitionHotkey);
  2361. obs_hotkey_unregister(statsHotkey);
  2362. obs_hotkey_unregister(screenshotHotkey);
  2363. obs_hotkey_unregister(sourceScreenshotHotkey);
  2364. }
  2365. OBSBasic::~OBSBasic()
  2366. {
  2367. /* clear out UI event queue */
  2368. QApplication::sendPostedEvents(nullptr);
  2369. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2370. if (updateCheckThread && updateCheckThread->isRunning())
  2371. updateCheckThread->wait();
  2372. if (patronJsonThread && patronJsonThread->isRunning())
  2373. patronJsonThread->wait();
  2374. delete screenshotData;
  2375. delete previewProjector;
  2376. delete studioProgramProjector;
  2377. delete previewProjectorSource;
  2378. delete previewProjectorMain;
  2379. delete sourceProjector;
  2380. delete sceneProjectorMenu;
  2381. delete scaleFilteringMenu;
  2382. delete blendingModeMenu;
  2383. delete colorMenu;
  2384. delete colorWidgetAction;
  2385. delete colorSelect;
  2386. delete deinterlaceMenu;
  2387. delete perSceneTransitionMenu;
  2388. delete shortcutFilter;
  2389. delete trayMenu;
  2390. delete programOptions;
  2391. delete program;
  2392. /* XXX: any obs data must be released before calling obs_shutdown.
  2393. * currently, we can't automate this with C++ RAII because of the
  2394. * delicate nature of obs_shutdown needing to be freed before the UI
  2395. * can be freed, and we have no control over the destruction order of
  2396. * the Qt UI stuff, so we have to manually clear any references to
  2397. * libobs. */
  2398. delete cpuUsageTimer;
  2399. os_cpu_usage_info_destroy(cpuUsageInfo);
  2400. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2401. ClearHotkeys();
  2402. service = nullptr;
  2403. outputHandler.reset();
  2404. delete interaction;
  2405. delete properties;
  2406. delete filters;
  2407. delete transformWindow;
  2408. delete advAudioWindow;
  2409. delete about;
  2410. delete remux;
  2411. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2412. OBSBasic::RenderMain, this);
  2413. obs_enter_graphics();
  2414. gs_vertexbuffer_destroy(box);
  2415. gs_vertexbuffer_destroy(boxLeft);
  2416. gs_vertexbuffer_destroy(boxTop);
  2417. gs_vertexbuffer_destroy(boxRight);
  2418. gs_vertexbuffer_destroy(boxBottom);
  2419. gs_vertexbuffer_destroy(circle);
  2420. gs_vertexbuffer_destroy(actionSafeMargin);
  2421. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2422. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2423. gs_vertexbuffer_destroy(leftLine);
  2424. gs_vertexbuffer_destroy(topLine);
  2425. gs_vertexbuffer_destroy(rightLine);
  2426. obs_leave_graphics();
  2427. /* When shutting down, sometimes source references can get in to the
  2428. * event queue, and if we don't forcibly process those events they
  2429. * won't get processed until after obs_shutdown has been called. I
  2430. * really wish there were a more elegant way to deal with this via C++,
  2431. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2432. * normal C++ behavior for your data to be freed in the order that you
  2433. * expect or want it to. */
  2434. QApplication::sendPostedEvents(nullptr);
  2435. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2436. LIBOBS_API_VER);
  2437. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  2438. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2439. OBS_RELEASE_CANDIDATE_VER);
  2440. #elif OBS_BETA > 0
  2441. config_set_int(App()->GlobalConfig(), "General", "LastBetaVersion",
  2442. OBS_BETA_VER);
  2443. #endif
  2444. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2445. previewEnabled);
  2446. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2447. ui->actionAlwaysOnTop->isChecked());
  2448. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2449. "SceneDuplicationMode", sceneDuplicationMode);
  2450. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2451. swapScenesMode);
  2452. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2453. "EditPropertiesMode", editPropertiesMode);
  2454. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2455. "PreviewProgramMode", IsPreviewProgramMode());
  2456. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2457. ui->lockDocks->isChecked());
  2458. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SideDocks",
  2459. ui->sideDocks->isChecked());
  2460. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2461. #ifdef BROWSER_AVAILABLE
  2462. DestroyPanelCookieManager();
  2463. delete cef;
  2464. cef = nullptr;
  2465. #endif
  2466. }
  2467. void OBSBasic::SaveProjectNow()
  2468. {
  2469. if (disableSaving)
  2470. return;
  2471. projectChanged = true;
  2472. SaveProjectDeferred();
  2473. }
  2474. void OBSBasic::SaveProject()
  2475. {
  2476. if (disableSaving)
  2477. return;
  2478. projectChanged = true;
  2479. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2480. Qt::QueuedConnection);
  2481. }
  2482. void OBSBasic::SaveProjectDeferred()
  2483. {
  2484. if (disableSaving)
  2485. return;
  2486. if (!projectChanged)
  2487. return;
  2488. projectChanged = false;
  2489. const char *sceneCollection = config_get_string(
  2490. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2491. char savePath[1024];
  2492. char fileName[1024];
  2493. int ret;
  2494. if (!sceneCollection)
  2495. return;
  2496. ret = snprintf(fileName, sizeof(fileName),
  2497. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2498. if (ret <= 0)
  2499. return;
  2500. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2501. if (ret <= 0)
  2502. return;
  2503. Save(savePath);
  2504. }
  2505. OBSSource OBSBasic::GetProgramSource()
  2506. {
  2507. return OBSGetStrongRef(programScene);
  2508. }
  2509. OBSScene OBSBasic::GetCurrentScene()
  2510. {
  2511. return currentScene.load();
  2512. }
  2513. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2514. {
  2515. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2516. }
  2517. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2518. {
  2519. return ui->sources->Get(GetTopSelectedSourceItem());
  2520. }
  2521. void OBSBasic::UpdatePreviewScalingMenu()
  2522. {
  2523. bool fixedScaling = ui->preview->IsFixedScaling();
  2524. float scalingAmount = ui->preview->GetScalingAmount();
  2525. if (!fixedScaling) {
  2526. ui->actionScaleWindow->setChecked(true);
  2527. ui->actionScaleCanvas->setChecked(false);
  2528. ui->actionScaleOutput->setChecked(false);
  2529. return;
  2530. }
  2531. obs_video_info ovi;
  2532. obs_get_video_info(&ovi);
  2533. ui->actionScaleWindow->setChecked(false);
  2534. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2535. ui->actionScaleOutput->setChecked(scalingAmount ==
  2536. float(ovi.output_width) /
  2537. float(ovi.base_width));
  2538. }
  2539. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2540. {
  2541. bool closed = true;
  2542. if (interaction)
  2543. closed = interaction->close();
  2544. if (!closed)
  2545. return;
  2546. interaction = new OBSBasicInteraction(this, source);
  2547. interaction->Init();
  2548. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2549. }
  2550. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2551. {
  2552. bool closed = true;
  2553. if (properties)
  2554. closed = properties->close();
  2555. if (!closed)
  2556. return;
  2557. properties = new OBSBasicProperties(this, source);
  2558. properties->Init();
  2559. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2560. }
  2561. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2562. {
  2563. bool closed = true;
  2564. if (filters)
  2565. closed = filters->close();
  2566. if (!closed)
  2567. return;
  2568. filters = new OBSBasicFilters(this, source);
  2569. filters->Init();
  2570. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2571. }
  2572. /* Qt callbacks for invokeMethod */
  2573. void OBSBasic::AddScene(OBSSource source)
  2574. {
  2575. const char *name = obs_source_get_name(source);
  2576. obs_scene_t *scene = obs_scene_from_source(source);
  2577. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2578. SetOBSRef(item, OBSScene(scene));
  2579. ui->scenes->insertItem(ui->scenes->currentRow() + 1, item);
  2580. obs_hotkey_register_source(
  2581. source, "OBSBasic.SelectScene",
  2582. Str("Basic.Hotkeys.SelectScene"),
  2583. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2584. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2585. App()->GetMainWindow());
  2586. auto potential_source =
  2587. static_cast<obs_source_t *>(data);
  2588. OBSSourceAutoRelease source =
  2589. obs_source_get_ref(potential_source);
  2590. if (source && pressed)
  2591. main->SetCurrentScene(source.Get());
  2592. },
  2593. static_cast<obs_source_t *>(source));
  2594. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2595. SignalContainer<OBSScene> container;
  2596. container.ref = scene;
  2597. container.handlers.assign({
  2598. std::make_shared<OBSSignal>(handler, "item_add",
  2599. OBSBasic::SceneItemAdded, this),
  2600. std::make_shared<OBSSignal>(handler, "reorder",
  2601. OBSBasic::SceneReordered, this),
  2602. std::make_shared<OBSSignal>(handler, "refresh",
  2603. OBSBasic::SceneRefreshed, this),
  2604. });
  2605. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2606. QVariant::fromValue(container));
  2607. /* if the scene already has items (a duplicated scene) add them */
  2608. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2609. AddSceneItem(item);
  2610. };
  2611. using addSceneItem_t = decltype(addSceneItem);
  2612. obs_scene_enum_items(
  2613. scene,
  2614. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2615. addSceneItem_t *func;
  2616. func = reinterpret_cast<addSceneItem_t *>(param);
  2617. (*func)(item);
  2618. return true;
  2619. },
  2620. &addSceneItem);
  2621. SaveProject();
  2622. if (!disableSaving) {
  2623. obs_source_t *source = obs_scene_get_source(scene);
  2624. blog(LOG_INFO, "User added scene '%s'",
  2625. obs_source_get_name(source));
  2626. OBSProjector::UpdateMultiviewProjectors();
  2627. }
  2628. if (api)
  2629. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2630. }
  2631. void OBSBasic::RemoveScene(OBSSource source)
  2632. {
  2633. obs_scene_t *scene = obs_scene_from_source(source);
  2634. QListWidgetItem *sel = nullptr;
  2635. int count = ui->scenes->count();
  2636. for (int i = 0; i < count; i++) {
  2637. auto item = ui->scenes->item(i);
  2638. auto cur_scene = GetOBSRef<OBSScene>(item);
  2639. if (cur_scene != scene)
  2640. continue;
  2641. sel = item;
  2642. break;
  2643. }
  2644. if (sel != nullptr) {
  2645. if (sel == ui->scenes->currentItem())
  2646. ui->sources->Clear();
  2647. delete sel;
  2648. }
  2649. SaveProject();
  2650. if (!disableSaving) {
  2651. blog(LOG_INFO, "User Removed scene '%s'",
  2652. obs_source_get_name(source));
  2653. OBSProjector::UpdateMultiviewProjectors();
  2654. }
  2655. if (api)
  2656. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2657. }
  2658. static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item,
  2659. void *param)
  2660. {
  2661. obs_sceneitem_t *selectedItem =
  2662. reinterpret_cast<obs_sceneitem_t *>(param);
  2663. if (obs_sceneitem_is_group(item))
  2664. obs_sceneitem_group_enum_items(item, select_one, param);
  2665. obs_sceneitem_select(item, (selectedItem == item));
  2666. return true;
  2667. }
  2668. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2669. {
  2670. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2671. if (GetCurrentScene() == scene)
  2672. ui->sources->Add(item);
  2673. SaveProject();
  2674. if (!disableSaving) {
  2675. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2676. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2677. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2678. obs_source_get_name(itemSource),
  2679. obs_source_get_id(itemSource),
  2680. obs_source_get_name(sceneSource));
  2681. obs_scene_enum_items(scene, select_one,
  2682. (obs_sceneitem_t *)item);
  2683. }
  2684. }
  2685. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2686. const QString &prevName)
  2687. {
  2688. QList<QListWidgetItem *> items =
  2689. listWidget->findItems(prevName, Qt::MatchExactly);
  2690. for (int i = 0; i < items.count(); i++)
  2691. items[i]->setText(newName);
  2692. }
  2693. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2694. QString prevName)
  2695. {
  2696. RenameListValues(ui->scenes, newName, prevName);
  2697. for (size_t i = 0; i < volumes.size(); i++) {
  2698. if (volumes[i]->GetName().compare(prevName) == 0)
  2699. volumes[i]->SetName(newName);
  2700. }
  2701. for (size_t i = 0; i < projectors.size(); i++) {
  2702. if (projectors[i]->GetSource() == source)
  2703. projectors[i]->RenameProjector(prevName, newName);
  2704. }
  2705. if (vcamConfig.type == VCamOutputType::SourceOutput &&
  2706. prevName == QString::fromStdString(vcamConfig.source))
  2707. vcamConfig.source = newName.toStdString();
  2708. if (vcamConfig.type == VCamOutputType::SceneOutput &&
  2709. prevName == QString::fromStdString(vcamConfig.scene))
  2710. vcamConfig.scene = newName.toStdString();
  2711. SaveProject();
  2712. obs_scene_t *scene = obs_scene_from_source(source);
  2713. if (scene)
  2714. OBSProjector::UpdateMultiviewProjectors();
  2715. UpdateContextBar();
  2716. UpdatePreviewProgramIndicators();
  2717. }
  2718. void OBSBasic::ClearContextBar()
  2719. {
  2720. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2721. if (la) {
  2722. delete la->widget();
  2723. ui->emptySpace->layout()->removeItem(la);
  2724. }
  2725. }
  2726. void OBSBasic::UpdateContextBarVisibility()
  2727. {
  2728. int width = ui->centralwidget->size().width();
  2729. ContextBarSize contextBarSizeNew;
  2730. if (width >= 740) {
  2731. contextBarSizeNew = ContextBarSize_Normal;
  2732. } else if (width >= 600) {
  2733. contextBarSizeNew = ContextBarSize_Reduced;
  2734. } else {
  2735. contextBarSizeNew = ContextBarSize_Minimized;
  2736. }
  2737. if (contextBarSize == contextBarSizeNew)
  2738. return;
  2739. contextBarSize = contextBarSizeNew;
  2740. UpdateContextBarDeferred();
  2741. }
  2742. static bool is_network_media_source(obs_source_t *source, const char *id)
  2743. {
  2744. if (strcmp(id, "ffmpeg_source") != 0)
  2745. return false;
  2746. OBSDataAutoRelease s = obs_source_get_settings(source);
  2747. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2748. return !is_local_file;
  2749. }
  2750. void OBSBasic::UpdateContextBarDeferred(bool force)
  2751. {
  2752. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2753. Qt::QueuedConnection, Q_ARG(bool, force));
  2754. }
  2755. void OBSBasic::SourceToolBarActionsSetEnabled()
  2756. {
  2757. bool enable = false;
  2758. bool disableProps = false;
  2759. OBSSceneItem item = GetCurrentSceneItem();
  2760. if (item) {
  2761. OBSSource source = obs_sceneitem_get_source(item);
  2762. disableProps = !obs_source_configurable(source);
  2763. enable = true;
  2764. }
  2765. if (disableProps)
  2766. ui->actionSourceProperties->setEnabled(false);
  2767. else
  2768. ui->actionSourceProperties->setEnabled(enable);
  2769. ui->actionRemoveSource->setEnabled(enable);
  2770. ui->actionSourceUp->setEnabled(enable);
  2771. ui->actionSourceDown->setEnabled(enable);
  2772. RefreshToolBarStyling(ui->sourcesToolbar);
  2773. }
  2774. void OBSBasic::UpdateTransformShortcuts()
  2775. {
  2776. bool hasVideo = false;
  2777. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  2778. if (source) {
  2779. uint32_t flags = obs_source_get_output_flags(source);
  2780. hasVideo = (flags & OBS_SOURCE_VIDEO) != 0;
  2781. }
  2782. ui->actionEditTransform->setEnabled(hasVideo);
  2783. ui->actionCopyTransform->setEnabled(hasVideo);
  2784. ui->actionPasteTransform->setEnabled(hasVideo ? hasCopiedTransform
  2785. : false);
  2786. ui->actionResetTransform->setEnabled(hasVideo);
  2787. }
  2788. void OBSBasic::UpdateContextBar(bool force)
  2789. {
  2790. SourceToolBarActionsSetEnabled();
  2791. UpdateTransformShortcuts();
  2792. if (!ui->contextContainer->isVisible() && !force)
  2793. return;
  2794. OBSSceneItem item = GetCurrentSceneItem();
  2795. if (item) {
  2796. obs_source_t *source = obs_sceneitem_get_source(item);
  2797. bool updateNeeded = true;
  2798. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2799. if (la) {
  2800. if (SourceToolbar *toolbar =
  2801. dynamic_cast<SourceToolbar *>(
  2802. la->widget())) {
  2803. if (toolbar->GetSource() == source)
  2804. updateNeeded = false;
  2805. } else if (MediaControls *toolbar =
  2806. dynamic_cast<MediaControls *>(
  2807. la->widget())) {
  2808. if (toolbar->GetSource() == source)
  2809. updateNeeded = false;
  2810. }
  2811. }
  2812. const char *id = obs_source_get_unversioned_id(source);
  2813. uint32_t flags = obs_source_get_output_flags(source);
  2814. ui->sourceInteractButton->setVisible(flags &
  2815. OBS_SOURCE_INTERACTION);
  2816. if (contextBarSize >= ContextBarSize_Reduced &&
  2817. (updateNeeded || force)) {
  2818. ClearContextBar();
  2819. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2820. if (!is_network_media_source(source, id)) {
  2821. MediaControls *mediaControls =
  2822. new MediaControls(
  2823. ui->emptySpace);
  2824. mediaControls->SetSource(source);
  2825. ui->emptySpace->layout()->addWidget(
  2826. mediaControls);
  2827. }
  2828. } else if (strcmp(id, "browser_source") == 0) {
  2829. BrowserToolbar *c = new BrowserToolbar(
  2830. ui->emptySpace, source);
  2831. ui->emptySpace->layout()->addWidget(c);
  2832. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2833. strcmp(id, "wasapi_output_capture") == 0 ||
  2834. strcmp(id, "coreaudio_input_capture") == 0 ||
  2835. strcmp(id, "coreaudio_output_capture") ==
  2836. 0 ||
  2837. strcmp(id, "pulse_input_capture") == 0 ||
  2838. strcmp(id, "pulse_output_capture") == 0 ||
  2839. strcmp(id, "alsa_input_capture") == 0) {
  2840. AudioCaptureToolbar *c =
  2841. new AudioCaptureToolbar(ui->emptySpace,
  2842. source);
  2843. c->Init();
  2844. ui->emptySpace->layout()->addWidget(c);
  2845. } else if (strcmp(id,
  2846. "wasapi_process_output_capture") ==
  2847. 0) {
  2848. ApplicationAudioCaptureToolbar *c =
  2849. new ApplicationAudioCaptureToolbar(
  2850. ui->emptySpace, source);
  2851. c->Init();
  2852. ui->emptySpace->layout()->addWidget(c);
  2853. } else if (strcmp(id, "window_capture") == 0 ||
  2854. strcmp(id, "xcomposite_input") == 0) {
  2855. WindowCaptureToolbar *c =
  2856. new WindowCaptureToolbar(ui->emptySpace,
  2857. source);
  2858. c->Init();
  2859. ui->emptySpace->layout()->addWidget(c);
  2860. } else if (strcmp(id, "monitor_capture") == 0 ||
  2861. strcmp(id, "display_capture") == 0 ||
  2862. strcmp(id, "xshm_input") == 0) {
  2863. DisplayCaptureToolbar *c =
  2864. new DisplayCaptureToolbar(
  2865. ui->emptySpace, source);
  2866. c->Init();
  2867. ui->emptySpace->layout()->addWidget(c);
  2868. } else if (strcmp(id, "dshow_input") == 0) {
  2869. DeviceCaptureToolbar *c =
  2870. new DeviceCaptureToolbar(ui->emptySpace,
  2871. source);
  2872. ui->emptySpace->layout()->addWidget(c);
  2873. } else if (strcmp(id, "game_capture") == 0) {
  2874. GameCaptureToolbar *c = new GameCaptureToolbar(
  2875. ui->emptySpace, source);
  2876. ui->emptySpace->layout()->addWidget(c);
  2877. } else if (strcmp(id, "image_source") == 0) {
  2878. ImageSourceToolbar *c = new ImageSourceToolbar(
  2879. ui->emptySpace, source);
  2880. ui->emptySpace->layout()->addWidget(c);
  2881. } else if (strcmp(id, "color_source") == 0) {
  2882. ColorSourceToolbar *c = new ColorSourceToolbar(
  2883. ui->emptySpace, source);
  2884. ui->emptySpace->layout()->addWidget(c);
  2885. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2886. strcmp(id, "text_gdiplus") == 0) {
  2887. TextSourceToolbar *c = new TextSourceToolbar(
  2888. ui->emptySpace, source);
  2889. ui->emptySpace->layout()->addWidget(c);
  2890. }
  2891. } else if (contextBarSize == ContextBarSize_Minimized) {
  2892. ClearContextBar();
  2893. }
  2894. QIcon icon;
  2895. if (strcmp(id, "scene") == 0)
  2896. icon = GetSceneIcon();
  2897. else if (strcmp(id, "group") == 0)
  2898. icon = GetGroupIcon();
  2899. else
  2900. icon = GetSourceIcon(id);
  2901. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2902. ui->contextSourceIcon->setPixmap(pixmap);
  2903. ui->contextSourceIconSpacer->hide();
  2904. ui->contextSourceIcon->show();
  2905. const char *name = obs_source_get_name(source);
  2906. ui->contextSourceLabel->setText(name);
  2907. ui->sourceFiltersButton->setEnabled(true);
  2908. ui->sourcePropertiesButton->setEnabled(
  2909. obs_source_configurable(source));
  2910. } else {
  2911. ClearContextBar();
  2912. ui->contextSourceIcon->hide();
  2913. ui->contextSourceIconSpacer->show();
  2914. ui->contextSourceLabel->setText(
  2915. QTStr("ContextBar.NoSelectedSource"));
  2916. ui->sourceFiltersButton->setEnabled(false);
  2917. ui->sourcePropertiesButton->setEnabled(false);
  2918. ui->sourceInteractButton->setVisible(false);
  2919. }
  2920. if (contextBarSize == ContextBarSize_Normal) {
  2921. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  2922. ui->sourceFiltersButton->setText(QTStr("Filters"));
  2923. ui->sourceInteractButton->setText(QTStr("Interact"));
  2924. } else {
  2925. ui->sourcePropertiesButton->setText("");
  2926. ui->sourceFiltersButton->setText("");
  2927. ui->sourceInteractButton->setText("");
  2928. }
  2929. }
  2930. static inline bool SourceMixerHidden(obs_source_t *source)
  2931. {
  2932. OBSDataAutoRelease priv_settings =
  2933. obs_source_get_private_settings(source);
  2934. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2935. return hidden;
  2936. }
  2937. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2938. {
  2939. OBSDataAutoRelease priv_settings =
  2940. obs_source_get_private_settings(source);
  2941. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2942. }
  2943. void OBSBasic::GetAudioSourceFilters()
  2944. {
  2945. QAction *action = reinterpret_cast<QAction *>(sender());
  2946. VolControl *vol = action->property("volControl").value<VolControl *>();
  2947. obs_source_t *source = vol->GetSource();
  2948. CreateFiltersWindow(source);
  2949. }
  2950. void OBSBasic::GetAudioSourceProperties()
  2951. {
  2952. QAction *action = reinterpret_cast<QAction *>(sender());
  2953. VolControl *vol = action->property("volControl").value<VolControl *>();
  2954. obs_source_t *source = vol->GetSource();
  2955. CreatePropertiesWindow(source);
  2956. }
  2957. void OBSBasic::HideAudioControl()
  2958. {
  2959. QAction *action = reinterpret_cast<QAction *>(sender());
  2960. VolControl *vol = action->property("volControl").value<VolControl *>();
  2961. obs_source_t *source = vol->GetSource();
  2962. if (!SourceMixerHidden(source)) {
  2963. SetSourceMixerHidden(source, true);
  2964. /* Due to a bug with QT 6.2.4, the version that's in the Ubuntu
  2965. * 22.04 ppa, hiding the audio mixer causes a crash, so defer to
  2966. * the next event loop to hide it. Doesn't seem to be a problem
  2967. * with newer versions of QT. */
  2968. QMetaObject::invokeMethod(this, "DeactivateAudioSource",
  2969. Qt::QueuedConnection,
  2970. Q_ARG(OBSSource, OBSSource(source)));
  2971. }
  2972. }
  2973. void OBSBasic::UnhideAllAudioControls()
  2974. {
  2975. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2976. {
  2977. if (!obs_source_active(source))
  2978. return true;
  2979. if (!SourceMixerHidden(source))
  2980. return true;
  2981. SetSourceMixerHidden(source, false);
  2982. ActivateAudioSource(source);
  2983. return true;
  2984. };
  2985. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2986. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2987. {
  2988. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2989. };
  2990. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2991. }
  2992. void OBSBasic::ToggleHideMixer()
  2993. {
  2994. OBSSceneItem item = GetCurrentSceneItem();
  2995. OBSSource source = obs_sceneitem_get_source(item);
  2996. if (!SourceMixerHidden(source)) {
  2997. SetSourceMixerHidden(source, true);
  2998. DeactivateAudioSource(source);
  2999. } else {
  3000. SetSourceMixerHidden(source, false);
  3001. ActivateAudioSource(source);
  3002. }
  3003. }
  3004. void OBSBasic::MixerRenameSource()
  3005. {
  3006. QAction *action = reinterpret_cast<QAction *>(sender());
  3007. VolControl *vol = action->property("volControl").value<VolControl *>();
  3008. OBSSource source = vol->GetSource();
  3009. const char *prevName = obs_source_get_name(source);
  3010. for (;;) {
  3011. string name;
  3012. bool accepted = NameDialog::AskForName(
  3013. this, QTStr("Basic.Main.MixerRename.Title"),
  3014. QTStr("Basic.Main.MixerRename.Text"), name,
  3015. QT_UTF8(prevName));
  3016. if (!accepted)
  3017. return;
  3018. if (name.empty()) {
  3019. OBSMessageBox::warning(this,
  3020. QTStr("NoNameEntered.Title"),
  3021. QTStr("NoNameEntered.Text"));
  3022. continue;
  3023. }
  3024. OBSSourceAutoRelease sourceTest =
  3025. obs_get_source_by_name(name.c_str());
  3026. if (sourceTest) {
  3027. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3028. QTStr("NameExists.Text"));
  3029. continue;
  3030. }
  3031. obs_source_set_name(source, name.c_str());
  3032. break;
  3033. }
  3034. }
  3035. static inline bool SourceVolumeLocked(obs_source_t *source)
  3036. {
  3037. OBSDataAutoRelease priv_settings =
  3038. obs_source_get_private_settings(source);
  3039. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  3040. return lock;
  3041. }
  3042. void OBSBasic::LockVolumeControl(bool lock)
  3043. {
  3044. QAction *action = reinterpret_cast<QAction *>(sender());
  3045. VolControl *vol = action->property("volControl").value<VolControl *>();
  3046. obs_source_t *source = vol->GetSource();
  3047. OBSDataAutoRelease priv_settings =
  3048. obs_source_get_private_settings(source);
  3049. obs_data_set_bool(priv_settings, "volume_locked", lock);
  3050. vol->EnableSlider(!lock);
  3051. }
  3052. void OBSBasic::VolControlContextMenu()
  3053. {
  3054. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  3055. /* ------------------- */
  3056. QAction lockAction(QTStr("LockVolume"), this);
  3057. lockAction.setCheckable(true);
  3058. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  3059. QAction hideAction(QTStr("Hide"), this);
  3060. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3061. QAction mixerRenameAction(QTStr("Rename"), this);
  3062. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  3063. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  3064. QAction filtersAction(QTStr("Filters"), this);
  3065. QAction propertiesAction(QTStr("Properties"), this);
  3066. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3067. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3068. toggleControlLayoutAction.setCheckable(true);
  3069. toggleControlLayoutAction.setChecked(config_get_bool(
  3070. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3071. /* ------------------- */
  3072. connect(&hideAction, &QAction::triggered, this,
  3073. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  3074. connect(&unhideAllAction, &QAction::triggered, this,
  3075. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3076. connect(&lockAction, &QAction::toggled, this,
  3077. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  3078. connect(&mixerRenameAction, &QAction::triggered, this,
  3079. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  3080. connect(&copyFiltersAction, &QAction::triggered, this,
  3081. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  3082. connect(&pasteFiltersAction, &QAction::triggered, this,
  3083. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  3084. connect(&filtersAction, &QAction::triggered, this,
  3085. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  3086. connect(&propertiesAction, &QAction::triggered, this,
  3087. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  3088. connect(&advPropAction, &QAction::triggered, this,
  3089. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3090. Qt::DirectConnection);
  3091. /* ------------------- */
  3092. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3093. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3094. /* ------------------- */
  3095. hideAction.setProperty("volControl",
  3096. QVariant::fromValue<VolControl *>(vol));
  3097. lockAction.setProperty("volControl",
  3098. QVariant::fromValue<VolControl *>(vol));
  3099. mixerRenameAction.setProperty("volControl",
  3100. QVariant::fromValue<VolControl *>(vol));
  3101. copyFiltersAction.setProperty("volControl",
  3102. QVariant::fromValue<VolControl *>(vol));
  3103. pasteFiltersAction.setProperty("volControl",
  3104. QVariant::fromValue<VolControl *>(vol));
  3105. filtersAction.setProperty("volControl",
  3106. QVariant::fromValue<VolControl *>(vol));
  3107. propertiesAction.setProperty("volControl",
  3108. QVariant::fromValue<VolControl *>(vol));
  3109. /* ------------------- */
  3110. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  3111. 0);
  3112. OBSSourceAutoRelease source =
  3113. obs_weak_source_get_source(copyFiltersSource);
  3114. if (source) {
  3115. pasteFiltersAction.setEnabled(true);
  3116. } else {
  3117. pasteFiltersAction.setEnabled(false);
  3118. }
  3119. QMenu popup;
  3120. vol->SetContextMenu(&popup);
  3121. popup.addAction(&lockAction);
  3122. popup.addSeparator();
  3123. popup.addAction(&unhideAllAction);
  3124. popup.addAction(&hideAction);
  3125. popup.addAction(&mixerRenameAction);
  3126. popup.addSeparator();
  3127. popup.addAction(&copyFiltersAction);
  3128. popup.addAction(&pasteFiltersAction);
  3129. popup.addSeparator();
  3130. popup.addAction(&toggleControlLayoutAction);
  3131. popup.addSeparator();
  3132. popup.addAction(&filtersAction);
  3133. popup.addAction(&propertiesAction);
  3134. popup.addAction(&advPropAction);
  3135. // toggleControlLayoutAction deletes and re-creates the volume controls
  3136. // meaning that "vol" would be pointing to freed memory.
  3137. if (popup.exec(QCursor::pos()) != &toggleControlLayoutAction)
  3138. vol->SetContextMenu(nullptr);
  3139. }
  3140. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  3141. {
  3142. StackedMixerAreaContextMenuRequested();
  3143. }
  3144. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  3145. {
  3146. StackedMixerAreaContextMenuRequested();
  3147. }
  3148. void OBSBasic::StackedMixerAreaContextMenuRequested()
  3149. {
  3150. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3151. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3152. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3153. toggleControlLayoutAction.setCheckable(true);
  3154. toggleControlLayoutAction.setChecked(config_get_bool(
  3155. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3156. /* ------------------- */
  3157. connect(&unhideAllAction, &QAction::triggered, this,
  3158. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3159. connect(&advPropAction, &QAction::triggered, this,
  3160. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3161. Qt::DirectConnection);
  3162. /* ------------------- */
  3163. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3164. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3165. /* ------------------- */
  3166. QMenu popup;
  3167. popup.addAction(&unhideAllAction);
  3168. popup.addSeparator();
  3169. popup.addAction(&toggleControlLayoutAction);
  3170. popup.addSeparator();
  3171. popup.addAction(&advPropAction);
  3172. popup.exec(QCursor::pos());
  3173. }
  3174. void OBSBasic::ToggleMixerLayout(bool vertical)
  3175. {
  3176. if (vertical) {
  3177. ui->stackedMixerArea->setMinimumSize(180, 220);
  3178. ui->stackedMixerArea->setCurrentIndex(1);
  3179. } else {
  3180. ui->stackedMixerArea->setMinimumSize(220, 0);
  3181. ui->stackedMixerArea->setCurrentIndex(0);
  3182. }
  3183. }
  3184. void OBSBasic::ToggleVolControlLayout()
  3185. {
  3186. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  3187. "VerticalVolControl");
  3188. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  3189. vertical);
  3190. ToggleMixerLayout(vertical);
  3191. // We need to store it so we can delete current and then add
  3192. // at the right order
  3193. vector<OBSSource> sources;
  3194. for (size_t i = 0; i != volumes.size(); i++)
  3195. sources.emplace_back(volumes[i]->GetSource());
  3196. ClearVolumeControls();
  3197. for (const auto &source : sources)
  3198. ActivateAudioSource(source);
  3199. }
  3200. void OBSBasic::ActivateAudioSource(OBSSource source)
  3201. {
  3202. if (SourceMixerHidden(source))
  3203. return;
  3204. if (!obs_source_active(source))
  3205. return;
  3206. if (!obs_source_audio_active(source))
  3207. return;
  3208. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3209. "VerticalVolControl");
  3210. VolControl *vol = new VolControl(source, true, vertical);
  3211. vol->EnableSlider(!SourceVolumeLocked(source));
  3212. double meterDecayRate =
  3213. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  3214. vol->SetMeterDecayRate(meterDecayRate);
  3215. uint32_t peakMeterTypeIdx =
  3216. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  3217. enum obs_peak_meter_type peakMeterType;
  3218. switch (peakMeterTypeIdx) {
  3219. case 0:
  3220. peakMeterType = SAMPLE_PEAK_METER;
  3221. break;
  3222. case 1:
  3223. peakMeterType = TRUE_PEAK_METER;
  3224. break;
  3225. default:
  3226. peakMeterType = SAMPLE_PEAK_METER;
  3227. break;
  3228. }
  3229. vol->setPeakMeterType(peakMeterType);
  3230. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  3231. connect(vol, &QWidget::customContextMenuRequested, this,
  3232. &OBSBasic::VolControlContextMenu);
  3233. connect(vol, &VolControl::ConfigClicked, this,
  3234. &OBSBasic::VolControlContextMenu);
  3235. InsertQObjectByName(volumes, vol);
  3236. for (auto volume : volumes) {
  3237. if (vertical)
  3238. ui->vVolControlLayout->addWidget(volume);
  3239. else
  3240. ui->hVolControlLayout->addWidget(volume);
  3241. }
  3242. }
  3243. void OBSBasic::DeactivateAudioSource(OBSSource source)
  3244. {
  3245. for (size_t i = 0; i < volumes.size(); i++) {
  3246. if (volumes[i]->GetSource() == source) {
  3247. delete volumes[i];
  3248. volumes.erase(volumes.begin() + i);
  3249. break;
  3250. }
  3251. }
  3252. }
  3253. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  3254. {
  3255. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  3256. !obs_source_is_group(source)) {
  3257. int count = ui->scenes->count();
  3258. if (count == 1) {
  3259. OBSMessageBox::information(this,
  3260. QTStr("FinalScene.Title"),
  3261. QTStr("FinalScene.Text"));
  3262. return false;
  3263. }
  3264. }
  3265. const char *name = obs_source_get_name(source);
  3266. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  3267. QMessageBox remove_source(this);
  3268. remove_source.setText(text);
  3269. QPushButton *Yes =
  3270. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  3271. remove_source.setDefaultButton(Yes);
  3272. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  3273. remove_source.setIcon(QMessageBox::Question);
  3274. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3275. remove_source.exec();
  3276. return Yes == remove_source.clickedButton();
  3277. }
  3278. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  3279. void OBSBasic::TimedCheckForUpdates()
  3280. {
  3281. if (App()->IsUpdaterDisabled())
  3282. return;
  3283. if (!config_get_bool(App()->GlobalConfig(), "General",
  3284. "EnableAutoUpdates"))
  3285. return;
  3286. #if defined(ENABLE_SPARKLE_UPDATER)
  3287. CheckForUpdates(false);
  3288. #elif _WIN32
  3289. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  3290. "LastUpdateCheck");
  3291. uint32_t lastVersion =
  3292. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  3293. if (lastVersion < LIBOBS_API_VER) {
  3294. lastUpdate = 0;
  3295. config_set_int(App()->GlobalConfig(), "General",
  3296. "LastUpdateCheck", 0);
  3297. }
  3298. long long t = (long long)time(nullptr);
  3299. long long secs = t - lastUpdate;
  3300. if (secs > UPDATE_CHECK_INTERVAL)
  3301. CheckForUpdates(false);
  3302. #endif
  3303. }
  3304. void OBSBasic::CheckForUpdates(bool manualUpdate)
  3305. {
  3306. #if _WIN32
  3307. ui->actionCheckForUpdates->setEnabled(false);
  3308. ui->actionRepair->setEnabled(false);
  3309. if (updateCheckThread && updateCheckThread->isRunning())
  3310. return;
  3311. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  3312. updateCheckThread->start();
  3313. #elif defined(ENABLE_SPARKLE_UPDATER)
  3314. ui->actionCheckForUpdates->setEnabled(false);
  3315. if (updateCheckThread && updateCheckThread->isRunning())
  3316. return;
  3317. MacUpdateThread *mut = new MacUpdateThread(manualUpdate);
  3318. connect(mut, &MacUpdateThread::Result, this,
  3319. &OBSBasic::MacBranchesFetched, Qt::QueuedConnection);
  3320. updateCheckThread.reset(mut);
  3321. updateCheckThread->start();
  3322. #else
  3323. UNUSED_PARAMETER(manualUpdate);
  3324. #endif
  3325. }
  3326. void OBSBasic::MacBranchesFetched(const QString &branch, bool manualUpdate)
  3327. {
  3328. #ifdef ENABLE_SPARKLE_UPDATER
  3329. static OBSSparkle *updater;
  3330. if (!updater) {
  3331. updater = new OBSSparkle(QT_TO_UTF8(branch),
  3332. ui->actionCheckForUpdates);
  3333. return;
  3334. }
  3335. updater->setBranch(QT_TO_UTF8(branch));
  3336. updater->checkForUpdates(manualUpdate);
  3337. #else
  3338. UNUSED_PARAMETER(branch);
  3339. UNUSED_PARAMETER(manualUpdate);
  3340. #endif
  3341. }
  3342. void OBSBasic::updateCheckFinished()
  3343. {
  3344. ui->actionCheckForUpdates->setEnabled(true);
  3345. ui->actionRepair->setEnabled(true);
  3346. }
  3347. void OBSBasic::DuplicateSelectedScene()
  3348. {
  3349. OBSScene curScene = GetCurrentScene();
  3350. if (!curScene)
  3351. return;
  3352. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3353. QString format{obs_source_get_name(curSceneSource)};
  3354. format += " %1";
  3355. int i = 2;
  3356. QString placeHolderText = format.arg(i);
  3357. OBSSourceAutoRelease source = nullptr;
  3358. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3359. placeHolderText = format.arg(++i);
  3360. }
  3361. for (;;) {
  3362. string name;
  3363. bool accepted = NameDialog::AskForName(
  3364. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3365. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3366. placeHolderText);
  3367. if (!accepted)
  3368. return;
  3369. if (name.empty()) {
  3370. OBSMessageBox::warning(this,
  3371. QTStr("NoNameEntered.Title"),
  3372. QTStr("NoNameEntered.Text"));
  3373. continue;
  3374. }
  3375. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3376. if (source) {
  3377. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3378. QTStr("NameExists.Text"));
  3379. obs_source_release(source);
  3380. continue;
  3381. }
  3382. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3383. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3384. source = obs_scene_get_source(scene);
  3385. SetCurrentScene(source, true);
  3386. auto undo = [](const std::string &data) {
  3387. OBSSourceAutoRelease source =
  3388. obs_get_source_by_name(data.c_str());
  3389. obs_source_remove(source);
  3390. };
  3391. auto redo = [this, name](const std::string &data) {
  3392. OBSSourceAutoRelease source =
  3393. obs_get_source_by_name(data.c_str());
  3394. obs_scene_t *scene = obs_scene_from_source(source);
  3395. scene = obs_scene_duplicate(scene, name.c_str(),
  3396. OBS_SCENE_DUP_REFS);
  3397. source = obs_scene_get_source(scene);
  3398. SetCurrentScene(source.Get(), true);
  3399. };
  3400. undo_s.add_action(
  3401. QTStr("Undo.Scene.Duplicate")
  3402. .arg(obs_source_get_name(source)),
  3403. undo, redo, obs_source_get_name(source),
  3404. obs_source_get_name(obs_scene_get_source(curScene)));
  3405. break;
  3406. }
  3407. }
  3408. static bool save_undo_source_enum(obs_scene_t * /* scene */,
  3409. obs_sceneitem_t *item, void *p)
  3410. {
  3411. obs_source_t *source = obs_sceneitem_get_source(item);
  3412. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3413. return true;
  3414. obs_data_array_t *array = (obs_data_array_t *)p;
  3415. /* check if the source is already stored in the array */
  3416. const char *name = obs_source_get_name(source);
  3417. const size_t count = obs_data_array_count(array);
  3418. for (size_t i = 0; i < count; i++) {
  3419. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3420. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3421. return true;
  3422. }
  3423. if (obs_source_is_group(source))
  3424. obs_scene_enum_items(obs_group_from_source(source),
  3425. save_undo_source_enum, p);
  3426. OBSDataAutoRelease source_data = obs_save_source(source);
  3427. obs_data_array_push_back(array, source_data);
  3428. return true;
  3429. }
  3430. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3431. {
  3432. obs_source_remove(source);
  3433. auto cb = [](void *, obs_source_t *source) {
  3434. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3435. obs_scene_prune_sources(obs_scene_from_source(source));
  3436. return true;
  3437. };
  3438. obs_enum_scenes(cb, NULL);
  3439. }
  3440. void OBSBasic::RemoveSelectedScene()
  3441. {
  3442. OBSScene scene = GetCurrentScene();
  3443. obs_source_t *source = obs_scene_get_source(scene);
  3444. if (!source || !QueryRemoveSource(source)) {
  3445. return;
  3446. }
  3447. /* ------------------------------ */
  3448. /* save all sources in scene */
  3449. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3450. obs_data_array_create();
  3451. obs_scene_enum_items(scene, save_undo_source_enum,
  3452. sources_in_deleted_scene);
  3453. OBSDataAutoRelease scene_data = obs_save_source(source);
  3454. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3455. /* ----------------------------------------------- */
  3456. /* save all scenes and groups the scene is used in */
  3457. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3458. obs_data_array_create();
  3459. struct other_scenes_cb_data {
  3460. obs_source_t *oldScene;
  3461. obs_data_array_t *scene_used_in_other_scenes;
  3462. } other_scenes_cb_data;
  3463. other_scenes_cb_data.oldScene = source;
  3464. other_scenes_cb_data.scene_used_in_other_scenes =
  3465. scene_used_in_other_scenes;
  3466. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3467. struct other_scenes_cb_data *data =
  3468. (struct other_scenes_cb_data *)data_ptr;
  3469. if (strcmp(obs_source_get_name(scene),
  3470. obs_source_get_name(data->oldScene)) == 0)
  3471. return true;
  3472. obs_sceneitem_t *item = obs_scene_find_source(
  3473. obs_group_or_scene_from_source(scene),
  3474. obs_source_get_name(data->oldScene));
  3475. if (item) {
  3476. OBSDataAutoRelease scene_data =
  3477. obs_save_source(obs_scene_get_source(
  3478. obs_sceneitem_get_scene(item)));
  3479. obs_data_array_push_back(
  3480. data->scene_used_in_other_scenes, scene_data);
  3481. }
  3482. return true;
  3483. };
  3484. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3485. /* --------------------------- */
  3486. /* undo/redo */
  3487. auto undo = [this](const std::string &json) {
  3488. OBSDataAutoRelease base =
  3489. obs_data_create_from_json(json.c_str());
  3490. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3491. obs_data_get_array(base, "sources_in_deleted_scene");
  3492. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3493. obs_data_get_array(base, "scene_used_in_other_scenes");
  3494. int savedIndex = (int)obs_data_get_int(base, "index");
  3495. std::vector<OBSSource> sources;
  3496. /* create missing sources */
  3497. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3498. sources.reserve(count);
  3499. for (size_t i = 0; i < count; i++) {
  3500. OBSDataAutoRelease data = obs_data_array_item(
  3501. sources_in_deleted_scene, i);
  3502. const char *name = obs_data_get_string(data, "name");
  3503. OBSSourceAutoRelease source =
  3504. obs_get_source_by_name(name);
  3505. if (!source) {
  3506. source = obs_load_source(data);
  3507. sources.push_back(source.Get());
  3508. }
  3509. }
  3510. /* actually load sources now */
  3511. for (obs_source_t *source : sources)
  3512. obs_source_load2(source);
  3513. /* Add scene to scenes and groups it was nested in */
  3514. for (size_t i = 0;
  3515. i < obs_data_array_count(scene_used_in_other_scenes);
  3516. i++) {
  3517. OBSDataAutoRelease data = obs_data_array_item(
  3518. scene_used_in_other_scenes, i);
  3519. const char *name = obs_data_get_string(data, "name");
  3520. OBSSourceAutoRelease source =
  3521. obs_get_source_by_name(name);
  3522. OBSDataAutoRelease settings =
  3523. obs_data_get_obj(data, "settings");
  3524. OBSDataArrayAutoRelease items =
  3525. obs_data_get_array(settings, "items");
  3526. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3527. std::vector<OBSSource> existing_sources;
  3528. auto cb = [](obs_scene_t *, obs_sceneitem_t *item,
  3529. void *data) {
  3530. std::vector<OBSSource> *existing =
  3531. (std::vector<OBSSource> *)data;
  3532. OBSSource source =
  3533. obs_sceneitem_get_source(item);
  3534. obs_sceneitem_remove(item);
  3535. existing->push_back(source);
  3536. return true;
  3537. };
  3538. obs_scene_enum_items(
  3539. obs_group_or_scene_from_source(source), cb,
  3540. (void *)&existing_sources);
  3541. /* Re-add sources to the scene */
  3542. obs_sceneitems_add(
  3543. obs_group_or_scene_from_source(source), items);
  3544. }
  3545. obs_source_t *scene_source = sources.back();
  3546. OBSScene scene = obs_scene_from_source(scene_source);
  3547. SetCurrentScene(scene, true);
  3548. /* set original index in list box */
  3549. ui->scenes->blockSignals(true);
  3550. int curIndex = ui->scenes->currentRow();
  3551. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3552. ui->scenes->insertItem(savedIndex, item);
  3553. ui->scenes->setCurrentRow(savedIndex);
  3554. currentScene = scene.Get();
  3555. ui->scenes->blockSignals(false);
  3556. };
  3557. auto redo = [](const std::string &name) {
  3558. OBSSourceAutoRelease source =
  3559. obs_get_source_by_name(name.c_str());
  3560. RemoveSceneAndReleaseNested(source);
  3561. };
  3562. OBSDataAutoRelease data = obs_data_create();
  3563. obs_data_set_array(data, "sources_in_deleted_scene",
  3564. sources_in_deleted_scene);
  3565. obs_data_set_array(data, "scene_used_in_other_scenes",
  3566. scene_used_in_other_scenes);
  3567. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3568. const char *scene_name = obs_source_get_name(source);
  3569. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3570. obs_data_get_json(data), scene_name);
  3571. /* --------------------------- */
  3572. /* remove */
  3573. RemoveSceneAndReleaseNested(source);
  3574. if (api)
  3575. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3576. }
  3577. void OBSBasic::ReorderSources(OBSScene scene)
  3578. {
  3579. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3580. return;
  3581. ui->sources->ReorderItems();
  3582. SaveProject();
  3583. }
  3584. void OBSBasic::RefreshSources(OBSScene scene)
  3585. {
  3586. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3587. return;
  3588. ui->sources->RefreshItems();
  3589. SaveProject();
  3590. }
  3591. /* OBS Callbacks */
  3592. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3593. {
  3594. OBSBasic *window = static_cast<OBSBasic *>(data);
  3595. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3596. QMetaObject::invokeMethod(window, "ReorderSources",
  3597. Q_ARG(OBSScene, OBSScene(scene)));
  3598. }
  3599. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3600. {
  3601. OBSBasic *window = static_cast<OBSBasic *>(data);
  3602. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3603. QMetaObject::invokeMethod(window, "RefreshSources",
  3604. Q_ARG(OBSScene, OBSScene(scene)));
  3605. }
  3606. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3607. {
  3608. OBSBasic *window = static_cast<OBSBasic *>(data);
  3609. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3610. QMetaObject::invokeMethod(window, "AddSceneItem",
  3611. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3612. }
  3613. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3614. {
  3615. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3616. if (obs_scene_from_source(source) != NULL)
  3617. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3618. "AddScene", WaitConnection(),
  3619. Q_ARG(OBSSource, OBSSource(source)));
  3620. }
  3621. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3622. {
  3623. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3624. if (obs_scene_from_source(source) != NULL)
  3625. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3626. "RemoveScene",
  3627. Q_ARG(OBSSource, OBSSource(source)));
  3628. }
  3629. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3630. {
  3631. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3632. uint32_t flags = obs_source_get_output_flags(source);
  3633. if (flags & OBS_SOURCE_AUDIO)
  3634. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3635. "ActivateAudioSource",
  3636. Q_ARG(OBSSource, OBSSource(source)));
  3637. }
  3638. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3639. {
  3640. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3641. uint32_t flags = obs_source_get_output_flags(source);
  3642. if (flags & OBS_SOURCE_AUDIO)
  3643. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3644. "DeactivateAudioSource",
  3645. Q_ARG(OBSSource, OBSSource(source)));
  3646. }
  3647. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3648. {
  3649. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3650. if (obs_source_active(source))
  3651. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3652. "ActivateAudioSource",
  3653. Q_ARG(OBSSource, OBSSource(source)));
  3654. }
  3655. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3656. {
  3657. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3658. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3659. "DeactivateAudioSource",
  3660. Q_ARG(OBSSource, OBSSource(source)));
  3661. }
  3662. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3663. {
  3664. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3665. const char *newName = calldata_string(params, "new_name");
  3666. const char *prevName = calldata_string(params, "prev_name");
  3667. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3668. "RenameSources", Q_ARG(OBSSource, source),
  3669. Q_ARG(QString, QT_UTF8(newName)),
  3670. Q_ARG(QString, QT_UTF8(prevName)));
  3671. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3672. }
  3673. void OBSBasic::DrawBackdrop(float cx, float cy)
  3674. {
  3675. if (!box)
  3676. return;
  3677. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3678. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3679. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3680. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3681. vec4 colorVal;
  3682. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3683. gs_effect_set_vec4(color, &colorVal);
  3684. gs_technique_begin(tech);
  3685. gs_technique_begin_pass(tech, 0);
  3686. gs_matrix_push();
  3687. gs_matrix_identity();
  3688. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3689. gs_load_vertexbuffer(box);
  3690. gs_draw(GS_TRISTRIP, 0, 0);
  3691. gs_matrix_pop();
  3692. gs_technique_end_pass(tech);
  3693. gs_technique_end(tech);
  3694. gs_load_vertexbuffer(nullptr);
  3695. GS_DEBUG_MARKER_END();
  3696. }
  3697. void OBSBasic::RenderMain(void *data, uint32_t, uint32_t)
  3698. {
  3699. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3700. OBSBasic *window = static_cast<OBSBasic *>(data);
  3701. obs_video_info ovi;
  3702. obs_get_video_info(&ovi);
  3703. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3704. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3705. gs_viewport_push();
  3706. gs_projection_push();
  3707. obs_display_t *display = window->ui->preview->GetDisplay();
  3708. uint32_t width, height;
  3709. obs_display_size(display, &width, &height);
  3710. float right = float(width) - window->previewX;
  3711. float bottom = float(height) - window->previewY;
  3712. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3713. 100.0f);
  3714. window->ui->preview->DrawOverflow();
  3715. /* --------------------------------------- */
  3716. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3717. -100.0f, 100.0f);
  3718. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3719. window->previewCY);
  3720. if (window->IsPreviewProgramMode()) {
  3721. window->DrawBackdrop(float(ovi.base_width),
  3722. float(ovi.base_height));
  3723. OBSScene scene = window->GetCurrentScene();
  3724. obs_source_t *source = obs_scene_get_source(scene);
  3725. if (source)
  3726. obs_source_video_render(source);
  3727. } else {
  3728. obs_render_main_texture_src_color_only();
  3729. }
  3730. gs_load_vertexbuffer(nullptr);
  3731. /* --------------------------------------- */
  3732. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3733. 100.0f);
  3734. gs_reset_viewport();
  3735. uint32_t targetCX = window->previewCX;
  3736. uint32_t targetCY = window->previewCY;
  3737. if (window->drawSafeAreas) {
  3738. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3739. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3740. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3741. targetCY);
  3742. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3743. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3744. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3745. }
  3746. window->ui->preview->DrawSceneEditing();
  3747. if (window->drawSpacingHelpers)
  3748. window->ui->preview->DrawSpacingHelpers();
  3749. /* --------------------------------------- */
  3750. gs_projection_pop();
  3751. gs_viewport_pop();
  3752. GS_DEBUG_MARKER_END();
  3753. }
  3754. /* Main class functions */
  3755. obs_service_t *OBSBasic::GetService()
  3756. {
  3757. if (!service) {
  3758. service =
  3759. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3760. obs_service_release(service);
  3761. }
  3762. return service;
  3763. }
  3764. void OBSBasic::SetService(obs_service_t *newService)
  3765. {
  3766. if (newService) {
  3767. service = newService;
  3768. }
  3769. }
  3770. int OBSBasic::GetTransitionDuration()
  3771. {
  3772. return ui->transitionDuration->value();
  3773. }
  3774. bool OBSBasic::Active() const
  3775. {
  3776. if (!outputHandler)
  3777. return false;
  3778. return outputHandler->Active();
  3779. }
  3780. #ifdef _WIN32
  3781. #define IS_WIN32 1
  3782. #else
  3783. #define IS_WIN32 0
  3784. #endif
  3785. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3786. {
  3787. return obs_reset_video(ovi);
  3788. }
  3789. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3790. {
  3791. const char *scaleTypeStr =
  3792. config_get_string(basicConfig, "Video", "ScaleType");
  3793. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3794. return OBS_SCALE_BILINEAR;
  3795. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3796. return OBS_SCALE_LANCZOS;
  3797. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3798. return OBS_SCALE_AREA;
  3799. else
  3800. return OBS_SCALE_BICUBIC;
  3801. }
  3802. static inline enum video_format GetVideoFormatFromName(const char *name)
  3803. {
  3804. if (astrcmpi(name, "I420") == 0)
  3805. return VIDEO_FORMAT_I420;
  3806. else if (astrcmpi(name, "NV12") == 0)
  3807. return VIDEO_FORMAT_NV12;
  3808. else if (astrcmpi(name, "I444") == 0)
  3809. return VIDEO_FORMAT_I444;
  3810. else if (astrcmpi(name, "I010") == 0)
  3811. return VIDEO_FORMAT_I010;
  3812. else if (astrcmpi(name, "P010") == 0)
  3813. return VIDEO_FORMAT_P010;
  3814. else if (astrcmpi(name, "P216") == 0)
  3815. return VIDEO_FORMAT_P216;
  3816. else if (astrcmpi(name, "P416") == 0)
  3817. return VIDEO_FORMAT_P416;
  3818. #if 0 //currently unsupported
  3819. else if (astrcmpi(name, "YVYU") == 0)
  3820. return VIDEO_FORMAT_YVYU;
  3821. else if (astrcmpi(name, "YUY2") == 0)
  3822. return VIDEO_FORMAT_YUY2;
  3823. else if (astrcmpi(name, "UYVY") == 0)
  3824. return VIDEO_FORMAT_UYVY;
  3825. #endif
  3826. else
  3827. return VIDEO_FORMAT_BGRA;
  3828. }
  3829. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3830. {
  3831. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3832. if (strcmp(name, "601") == 0)
  3833. colorspace = VIDEO_CS_601;
  3834. else if (strcmp(name, "709") == 0)
  3835. colorspace = VIDEO_CS_709;
  3836. else if (strcmp(name, "2100PQ") == 0)
  3837. colorspace = VIDEO_CS_2100_PQ;
  3838. else if (strcmp(name, "2100HLG") == 0)
  3839. colorspace = VIDEO_CS_2100_HLG;
  3840. return colorspace;
  3841. }
  3842. void OBSBasic::ResetUI()
  3843. {
  3844. bool studioPortraitLayout = config_get_bool(
  3845. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3846. if (studioPortraitLayout)
  3847. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3848. else
  3849. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3850. UpdatePreviewProgramIndicators();
  3851. }
  3852. int OBSBasic::ResetVideo()
  3853. {
  3854. if (outputHandler && outputHandler->Active())
  3855. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3856. ProfileScope("OBSBasic::ResetVideo");
  3857. struct obs_video_info ovi;
  3858. int ret;
  3859. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3860. const char *colorFormat =
  3861. config_get_string(basicConfig, "Video", "ColorFormat");
  3862. const char *colorSpace =
  3863. config_get_string(basicConfig, "Video", "ColorSpace");
  3864. const char *colorRange =
  3865. config_get_string(basicConfig, "Video", "ColorRange");
  3866. ovi.graphics_module = App()->GetRenderModule();
  3867. ovi.base_width =
  3868. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3869. ovi.base_height =
  3870. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3871. ovi.output_width =
  3872. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3873. ovi.output_height =
  3874. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3875. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3876. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3877. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3878. : VIDEO_RANGE_PARTIAL;
  3879. ovi.adapter =
  3880. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3881. ovi.gpu_conversion = true;
  3882. ovi.scale_type = GetScaleType(basicConfig);
  3883. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3884. ovi.base_width = 1920;
  3885. ovi.base_height = 1080;
  3886. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3887. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3888. }
  3889. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3890. ovi.output_width = ovi.base_width;
  3891. ovi.output_height = ovi.base_height;
  3892. config_set_uint(basicConfig, "Video", "OutputCX",
  3893. ovi.base_width);
  3894. config_set_uint(basicConfig, "Video", "OutputCY",
  3895. ovi.base_height);
  3896. }
  3897. ret = AttemptToResetVideo(&ovi);
  3898. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3899. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3900. blog(LOG_WARNING, "Tried to reset when "
  3901. "already active");
  3902. return ret;
  3903. }
  3904. /* Try OpenGL if DirectX fails on windows */
  3905. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3906. blog(LOG_WARNING,
  3907. "Failed to initialize obs video (%d) "
  3908. "with graphics_module='%s', retrying "
  3909. "with graphics_module='%s'",
  3910. ret, ovi.graphics_module, DL_OPENGL);
  3911. ovi.graphics_module = DL_OPENGL;
  3912. ret = AttemptToResetVideo(&ovi);
  3913. }
  3914. } else if (ret == OBS_VIDEO_SUCCESS) {
  3915. ResizePreview(ovi.base_width, ovi.base_height);
  3916. if (program)
  3917. ResizeProgram(ovi.base_width, ovi.base_height);
  3918. }
  3919. if (ret == OBS_VIDEO_SUCCESS) {
  3920. const float sdr_white_level = (float)config_get_uint(
  3921. basicConfig, "Video", "SdrWhiteLevel");
  3922. const float hdr_nominal_peak_level = (float)config_get_uint(
  3923. basicConfig, "Video", "HdrNominalPeakLevel");
  3924. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  3925. OBSBasicStats::InitializeValues();
  3926. OBSProjector::UpdateMultiviewProjectors();
  3927. }
  3928. return ret;
  3929. }
  3930. bool OBSBasic::ResetAudio()
  3931. {
  3932. ProfileScope("OBSBasic::ResetAudio");
  3933. struct obs_audio_info2 ai = {};
  3934. ai.samples_per_sec =
  3935. config_get_uint(basicConfig, "Audio", "SampleRate");
  3936. const char *channelSetupStr =
  3937. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3938. if (strcmp(channelSetupStr, "Mono") == 0)
  3939. ai.speakers = SPEAKERS_MONO;
  3940. else if (strcmp(channelSetupStr, "2.1") == 0)
  3941. ai.speakers = SPEAKERS_2POINT1;
  3942. else if (strcmp(channelSetupStr, "4.0") == 0)
  3943. ai.speakers = SPEAKERS_4POINT0;
  3944. else if (strcmp(channelSetupStr, "4.1") == 0)
  3945. ai.speakers = SPEAKERS_4POINT1;
  3946. else if (strcmp(channelSetupStr, "5.1") == 0)
  3947. ai.speakers = SPEAKERS_5POINT1;
  3948. else if (strcmp(channelSetupStr, "7.1") == 0)
  3949. ai.speakers = SPEAKERS_7POINT1;
  3950. else
  3951. ai.speakers = SPEAKERS_STEREO;
  3952. bool lowLatencyAudioBuffering = config_get_bool(
  3953. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  3954. if (lowLatencyAudioBuffering) {
  3955. ai.max_buffering_ms = 20;
  3956. ai.fixed_buffering = true;
  3957. }
  3958. return obs_reset_audio2(&ai);
  3959. }
  3960. extern char *get_new_source_name(const char *name, const char *format);
  3961. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3962. const char *deviceDesc, int channel)
  3963. {
  3964. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3965. OBSSourceAutoRelease source;
  3966. OBSDataAutoRelease settings;
  3967. source = obs_get_output_source(channel);
  3968. if (source) {
  3969. if (disable) {
  3970. obs_set_output_source(channel, nullptr);
  3971. } else {
  3972. settings = obs_source_get_settings(source);
  3973. const char *oldId =
  3974. obs_data_get_string(settings, "device_id");
  3975. if (strcmp(oldId, deviceId) != 0) {
  3976. obs_data_set_string(settings, "device_id",
  3977. deviceId);
  3978. obs_source_update(source, settings);
  3979. }
  3980. }
  3981. } else if (!disable) {
  3982. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  3983. settings = obs_data_create();
  3984. obs_data_set_string(settings, "device_id", deviceId);
  3985. source = obs_source_create(sourceId, name, settings, nullptr);
  3986. obs_set_output_source(channel, source);
  3987. }
  3988. }
  3989. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3990. {
  3991. QSize targetSize;
  3992. bool isFixedScaling;
  3993. obs_video_info ovi;
  3994. /* resize preview panel to fix to the top section of the window */
  3995. targetSize = GetPixelSize(ui->preview);
  3996. isFixedScaling = ui->preview->IsFixedScaling();
  3997. obs_get_video_info(&ovi);
  3998. if (isFixedScaling) {
  3999. ui->preview->ClampScrollingOffsets();
  4000. previewScale = ui->preview->GetScalingAmount();
  4001. GetCenterPosFromFixedScale(
  4002. int(cx), int(cy),
  4003. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4004. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  4005. previewY, previewScale);
  4006. previewX += ui->preview->GetScrollX();
  4007. previewY += ui->preview->GetScrollY();
  4008. } else {
  4009. GetScaleAndCenterPos(int(cx), int(cy),
  4010. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4011. targetSize.height() -
  4012. PREVIEW_EDGE_SIZE * 2,
  4013. previewX, previewY, previewScale);
  4014. }
  4015. previewX += float(PREVIEW_EDGE_SIZE);
  4016. previewY += float(PREVIEW_EDGE_SIZE);
  4017. }
  4018. void OBSBasic::CloseDialogs()
  4019. {
  4020. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  4021. if (!childDialogs.isEmpty()) {
  4022. for (int i = 0; i < childDialogs.size(); ++i) {
  4023. childDialogs.at(i)->close();
  4024. }
  4025. }
  4026. if (!stats.isNull())
  4027. stats->close(); //call close to save Stats geometry
  4028. if (!remux.isNull())
  4029. remux->close();
  4030. }
  4031. void OBSBasic::EnumDialogs()
  4032. {
  4033. visDialogs.clear();
  4034. modalDialogs.clear();
  4035. visMsgBoxes.clear();
  4036. /* fill list of Visible dialogs and Modal dialogs */
  4037. QList<QDialog *> dialogs = findChildren<QDialog *>();
  4038. for (QDialog *dialog : dialogs) {
  4039. if (dialog->isVisible())
  4040. visDialogs.append(dialog);
  4041. if (dialog->isModal())
  4042. modalDialogs.append(dialog);
  4043. }
  4044. /* fill list of Visible message boxes */
  4045. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  4046. for (QMessageBox *msgbox : msgBoxes) {
  4047. if (msgbox->isVisible())
  4048. visMsgBoxes.append(msgbox);
  4049. }
  4050. }
  4051. void OBSBasic::ClearProjectors()
  4052. {
  4053. for (size_t i = 0; i < projectors.size(); i++) {
  4054. if (projectors[i])
  4055. delete projectors[i];
  4056. }
  4057. projectors.clear();
  4058. }
  4059. void OBSBasic::ClearSceneData()
  4060. {
  4061. disableSaving++;
  4062. setCursor(Qt::WaitCursor);
  4063. CloseDialogs();
  4064. ClearVolumeControls();
  4065. ClearListItems(ui->scenes);
  4066. ui->sources->Clear();
  4067. ClearQuickTransitions();
  4068. ui->transitions->clear();
  4069. ClearProjectors();
  4070. for (int i = 0; i < MAX_CHANNELS; i++)
  4071. obs_set_output_source(i, nullptr);
  4072. /* Reset VCam to default to clear its private scene and any references
  4073. * it holds. It will be reconfigured during loading. */
  4074. if (vcamEnabled) {
  4075. vcamConfig.type = VCamOutputType::ProgramView;
  4076. outputHandler->UpdateVirtualCamOutputSource();
  4077. }
  4078. safeModeModuleData = nullptr;
  4079. lastScene = nullptr;
  4080. swapScene = nullptr;
  4081. programScene = nullptr;
  4082. prevFTBSource = nullptr;
  4083. clipboard.clear();
  4084. copyFiltersSource = nullptr;
  4085. copyFilter = nullptr;
  4086. auto cb = [](void *, obs_source_t *source) {
  4087. obs_source_remove(source);
  4088. return true;
  4089. };
  4090. obs_enum_scenes(cb, nullptr);
  4091. obs_enum_sources(cb, nullptr);
  4092. if (api)
  4093. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  4094. undo_s.clear();
  4095. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  4096. * that deleteLater events are processed at this point */
  4097. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  4098. do {
  4099. QApplication::sendPostedEvents(nullptr);
  4100. } while (obs_wait_for_destroy_queue());
  4101. /* Pump Qt events one final time to give remaining signals time to be
  4102. * processed (since this happens after the destroy thread finishes and
  4103. * the audio/video threads have processed their tasks). */
  4104. QApplication::sendPostedEvents(nullptr);
  4105. unsetCursor();
  4106. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  4107. * reference, they will still be in the hash table, enumerate them and
  4108. * store the names for logging purposes. */
  4109. auto cb2 = [](void *param, obs_source_t *source) {
  4110. auto orphans = static_cast<vector<string> *>(param);
  4111. orphans->push_back(obs_source_get_name(source));
  4112. return true;
  4113. };
  4114. vector<string> orphan_sources;
  4115. obs_enum_sources(cb2, &orphan_sources);
  4116. if (!orphan_sources.empty()) {
  4117. /* Avoid logging list twice in case it gets called after
  4118. * setting the flag the first time. */
  4119. if (!clearingFailed) {
  4120. /* This ugly mess exists to join a vector of strings
  4121. * with a user-defined delimiter. */
  4122. string orphan_names = std::accumulate(
  4123. orphan_sources.begin(), orphan_sources.end(),
  4124. string(""), [](string a, string b) {
  4125. return std::move(a) + "\n- " + b;
  4126. });
  4127. blog(LOG_ERROR,
  4128. "Not all sources were cleared when clearing scene data:\n%s\n",
  4129. orphan_names.c_str());
  4130. }
  4131. /* We do not decrement disableSaving here to avoid OBS
  4132. * overwriting user data with garbage. */
  4133. clearingFailed = true;
  4134. } else {
  4135. disableSaving--;
  4136. blog(LOG_INFO, "All scene data cleared");
  4137. blog(LOG_INFO,
  4138. "------------------------------------------------");
  4139. }
  4140. }
  4141. void OBSBasic::closeEvent(QCloseEvent *event)
  4142. {
  4143. /* Do not close window if inside of a temporary event loop because we
  4144. * could be inside of an Auth::LoadUI call. Keep trying once per
  4145. * second until we've exit any known sub-loops. */
  4146. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4147. QTimer::singleShot(1000, this, &OBSBasic::close);
  4148. event->ignore();
  4149. return;
  4150. }
  4151. #ifdef YOUTUBE_ENABLED
  4152. /* Also don't close the window if the youtube stream check is active */
  4153. if (youtubeStreamCheckThread) {
  4154. QTimer::singleShot(1000, this, &OBSBasic::close);
  4155. event->ignore();
  4156. return;
  4157. }
  4158. #endif
  4159. if (isVisible())
  4160. config_set_string(App()->GlobalConfig(), "BasicWindow",
  4161. "geometry",
  4162. saveGeometry().toBase64().constData());
  4163. bool confirmOnExit =
  4164. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  4165. if (confirmOnExit && outputHandler && outputHandler->Active() &&
  4166. !clearingFailed) {
  4167. SetShowing(true);
  4168. QMessageBox::StandardButton button = OBSMessageBox::question(
  4169. this, QTStr("ConfirmExit.Title"),
  4170. QTStr("ConfirmExit.Text"));
  4171. if (button == QMessageBox::No) {
  4172. event->ignore();
  4173. restart = false;
  4174. return;
  4175. }
  4176. }
  4177. if (remux && !remux->close()) {
  4178. event->ignore();
  4179. restart = false;
  4180. return;
  4181. }
  4182. QWidget::closeEvent(event);
  4183. if (!event->isAccepted())
  4184. return;
  4185. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  4186. closing = true;
  4187. if (outputHandler->VirtualCamActive())
  4188. outputHandler->StopVirtualCam();
  4189. if (introCheckThread)
  4190. introCheckThread->wait();
  4191. if (whatsNewInitThread)
  4192. whatsNewInitThread->wait();
  4193. if (updateCheckThread)
  4194. updateCheckThread->wait();
  4195. if (logUploadThread)
  4196. logUploadThread->wait();
  4197. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  4198. devicePropertiesThread->wait();
  4199. devicePropertiesThread.reset();
  4200. }
  4201. QApplication::sendPostedEvents(nullptr);
  4202. signalHandlers.clear();
  4203. Auth::Save();
  4204. SaveProjectNow();
  4205. auth.reset();
  4206. delete extraBrowsers;
  4207. ui->preview->DestroyDisplay();
  4208. if (program)
  4209. program->DestroyDisplay();
  4210. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  4211. saveState().toBase64().constData());
  4212. #ifdef BROWSER_AVAILABLE
  4213. if (cef)
  4214. SaveExtraBrowserDocks();
  4215. ClearExtraBrowserDocks();
  4216. #endif
  4217. if (api)
  4218. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  4219. disableSaving++;
  4220. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  4221. * sources, etc) so that all references are released before shutdown */
  4222. ClearSceneData();
  4223. if (api)
  4224. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  4225. // Destroys the frontend API so plugins can't continue calling it
  4226. obs_frontend_set_callbacks_internal(nullptr);
  4227. api = nullptr;
  4228. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  4229. }
  4230. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  4231. {
  4232. #ifdef _WIN32
  4233. const MSG &msg = *static_cast<MSG *>(message);
  4234. switch (msg.message) {
  4235. case WM_MOVE:
  4236. for (OBSQTDisplay *const display :
  4237. findChildren<OBSQTDisplay *>()) {
  4238. display->OnMove();
  4239. }
  4240. break;
  4241. case WM_DISPLAYCHANGE:
  4242. for (OBSQTDisplay *const display :
  4243. findChildren<OBSQTDisplay *>()) {
  4244. display->OnDisplayChange();
  4245. }
  4246. }
  4247. #else
  4248. UNUSED_PARAMETER(message);
  4249. #endif
  4250. return false;
  4251. }
  4252. void OBSBasic::changeEvent(QEvent *event)
  4253. {
  4254. if (event->type() == QEvent::WindowStateChange) {
  4255. QWindowStateChangeEvent *stateEvent =
  4256. (QWindowStateChangeEvent *)event;
  4257. if (isMinimized()) {
  4258. if (trayIcon && trayIcon->isVisible() &&
  4259. sysTrayMinimizeToTray()) {
  4260. ToggleShowHide();
  4261. return;
  4262. }
  4263. if (previewEnabled)
  4264. EnablePreviewDisplay(false);
  4265. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  4266. isVisible()) {
  4267. if (previewEnabled)
  4268. EnablePreviewDisplay(true);
  4269. }
  4270. }
  4271. }
  4272. void OBSBasic::on_actionShow_Recordings_triggered()
  4273. {
  4274. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4275. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  4276. const char *adv_path =
  4277. strcmp(type, "Standard")
  4278. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  4279. : config_get_string(basicConfig, "AdvOut",
  4280. "RecFilePath");
  4281. const char *path = strcmp(mode, "Advanced")
  4282. ? config_get_string(basicConfig,
  4283. "SimpleOutput",
  4284. "FilePath")
  4285. : adv_path;
  4286. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4287. }
  4288. void OBSBasic::on_actionRemux_triggered()
  4289. {
  4290. if (!remux.isNull()) {
  4291. remux->show();
  4292. remux->raise();
  4293. return;
  4294. }
  4295. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4296. const char *path = strcmp(mode, "Advanced")
  4297. ? config_get_string(basicConfig,
  4298. "SimpleOutput",
  4299. "FilePath")
  4300. : config_get_string(basicConfig, "AdvOut",
  4301. "RecFilePath");
  4302. OBSRemux *remuxDlg;
  4303. remuxDlg = new OBSRemux(path, this);
  4304. remuxDlg->show();
  4305. remux = remuxDlg;
  4306. }
  4307. void OBSBasic::on_action_Settings_triggered()
  4308. {
  4309. static bool settings_already_executing = false;
  4310. /* Do not load settings window if inside of a temporary event loop
  4311. * because we could be inside of an Auth::LoadUI call. Keep trying
  4312. * once per second until we've exit any known sub-loops. */
  4313. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4314. QTimer::singleShot(1000, this,
  4315. &OBSBasic::on_action_Settings_triggered);
  4316. return;
  4317. }
  4318. if (settings_already_executing) {
  4319. return;
  4320. }
  4321. settings_already_executing = true;
  4322. {
  4323. OBSBasicSettings settings(this);
  4324. settings.exec();
  4325. }
  4326. settings_already_executing = false;
  4327. if (restart) {
  4328. QMessageBox::StandardButton button = OBSMessageBox::question(
  4329. this, QTStr("Restart"), QTStr("NeedsRestart"));
  4330. if (button == QMessageBox::Yes)
  4331. close();
  4332. else
  4333. restart = false;
  4334. }
  4335. }
  4336. void OBSBasic::on_actionShowMacPermissions_triggered()
  4337. {
  4338. #ifdef __APPLE__
  4339. OBSPermissions check(this, CheckPermission(kScreenCapture),
  4340. CheckPermission(kVideoDeviceAccess),
  4341. CheckPermission(kAudioDeviceAccess),
  4342. CheckPermission(kAccessibility));
  4343. check.exec();
  4344. #endif
  4345. }
  4346. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4347. {
  4348. if (obs_missing_files_count(files) > 0) {
  4349. /* When loading the missing files dialog on launch, the
  4350. * window hasn't fully initialized by this point on macOS,
  4351. * so put this at the end of the current task queue. Fixes
  4352. * a bug where the window is behind OBS on startup. */
  4353. QTimer::singleShot(0, [this, files] {
  4354. missDialog = new OBSMissingFiles(files, this);
  4355. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4356. missDialog->show();
  4357. missDialog->raise();
  4358. });
  4359. } else {
  4360. obs_missing_files_destroy(files);
  4361. /* Only raise dialog if triggered manually */
  4362. if (!disableSaving)
  4363. OBSMessageBox::information(
  4364. this, QTStr("MissingFiles.NoMissing.Title"),
  4365. QTStr("MissingFiles.NoMissing.Text"));
  4366. }
  4367. }
  4368. void OBSBasic::on_actionShowMissingFiles_triggered()
  4369. {
  4370. obs_missing_files_t *files = obs_missing_files_create();
  4371. auto cb_sources = [](void *data, obs_source_t *source) {
  4372. AddMissingFiles(data, source);
  4373. return true;
  4374. };
  4375. obs_enum_all_sources(cb_sources, files);
  4376. ShowMissingFilesDialog(files);
  4377. }
  4378. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4379. {
  4380. if (advAudioWindow != nullptr) {
  4381. advAudioWindow->raise();
  4382. return;
  4383. }
  4384. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4385. "BasicWindow", "ShowSourceIcons");
  4386. advAudioWindow = new OBSBasicAdvAudio(this);
  4387. advAudioWindow->show();
  4388. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4389. advAudioWindow->SetIconsVisible(iconsVisible);
  4390. }
  4391. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4392. {
  4393. on_actionAdvAudioProperties_triggered();
  4394. }
  4395. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4396. {
  4397. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4398. connect(&unhideAllAction, &QAction::triggered, this,
  4399. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4400. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4401. toggleControlLayoutAction.setCheckable(true);
  4402. toggleControlLayoutAction.setChecked(config_get_bool(
  4403. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4404. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4405. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4406. QMenu popup;
  4407. popup.addAction(&unhideAllAction);
  4408. popup.addSeparator();
  4409. popup.addAction(&toggleControlLayoutAction);
  4410. popup.exec(QCursor::pos());
  4411. }
  4412. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4413. QListWidgetItem *)
  4414. {
  4415. OBSSource source;
  4416. if (current) {
  4417. OBSScene scene = GetOBSRef<OBSScene>(current);
  4418. source = obs_scene_get_source(scene);
  4419. currentScene = scene;
  4420. } else {
  4421. currentScene = NULL;
  4422. }
  4423. SetCurrentScene(source);
  4424. if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput)
  4425. outputHandler->UpdateVirtualCamOutputSource();
  4426. if (api)
  4427. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4428. UpdateContextBar();
  4429. }
  4430. void OBSBasic::EditSceneName()
  4431. {
  4432. ui->scenesDock->removeAction(renameScene);
  4433. QListWidgetItem *item = ui->scenes->currentItem();
  4434. Qt::ItemFlags flags = item->flags();
  4435. item->setFlags(flags | Qt::ItemIsEditable);
  4436. ui->scenes->editItem(item);
  4437. item->setFlags(flags);
  4438. }
  4439. QList<QString> OBSBasic::GetProjectorMenuMonitorsFormatted()
  4440. {
  4441. QList<QString> projectorsFormatted;
  4442. QList<QScreen *> screens = QGuiApplication::screens();
  4443. for (int i = 0; i < screens.size(); i++) {
  4444. QScreen *screen = screens[i];
  4445. QRect screenGeometry = screen->geometry();
  4446. qreal ratio = screen->devicePixelRatio();
  4447. QString name = "";
  4448. #if defined(_WIN32) && QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
  4449. QTextStream fullname(&name);
  4450. fullname << GetMonitorName(screen->name());
  4451. fullname << " (";
  4452. fullname << (i + 1);
  4453. fullname << ")";
  4454. #elif defined(__APPLE__) || defined(_WIN32)
  4455. name = screen->name();
  4456. #else
  4457. name = screen->model().simplified();
  4458. if (name.length() > 1 && name.endsWith("-"))
  4459. name.chop(1);
  4460. #endif
  4461. name = name.simplified();
  4462. if (name.length() == 0) {
  4463. name = QString("%1 %2")
  4464. .arg(QTStr("Display"))
  4465. .arg(QString::number(i + 1));
  4466. }
  4467. QString str =
  4468. QString("%1: %2x%3 @ %4,%5")
  4469. .arg(name,
  4470. QString::number(screenGeometry.width() *
  4471. ratio),
  4472. QString::number(screenGeometry.height() *
  4473. ratio),
  4474. QString::number(screenGeometry.x()),
  4475. QString::number(screenGeometry.y()));
  4476. projectorsFormatted.push_back(str);
  4477. }
  4478. return projectorsFormatted;
  4479. }
  4480. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4481. {
  4482. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4483. QMenu popup(this);
  4484. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4485. popup.addAction(QTStr("Add"), this,
  4486. &OBSBasic::on_actionAddScene_triggered);
  4487. if (item) {
  4488. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4489. copyFilters->setEnabled(false);
  4490. connect(copyFilters, &QAction::triggered, this,
  4491. &OBSBasic::SceneCopyFilters);
  4492. QAction *pasteFilters =
  4493. new QAction(QTStr("Paste.Filters"), this);
  4494. pasteFilters->setEnabled(
  4495. !obs_weak_source_expired(copyFiltersSource));
  4496. connect(pasteFilters, &QAction::triggered, this,
  4497. &OBSBasic::ScenePasteFilters);
  4498. popup.addSeparator();
  4499. popup.addAction(QTStr("Duplicate"), this,
  4500. &OBSBasic::DuplicateSelectedScene);
  4501. popup.addAction(copyFilters);
  4502. popup.addAction(pasteFilters);
  4503. popup.addSeparator();
  4504. popup.addAction(renameScene);
  4505. popup.addAction(ui->actionRemoveScene);
  4506. popup.addSeparator();
  4507. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4508. &OBSBasic::on_actionSceneUp_triggered);
  4509. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4510. this, &OBSBasic::on_actionSceneDown_triggered);
  4511. order.addSeparator();
  4512. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4513. this, &OBSBasic::MoveSceneToTop);
  4514. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4515. this, &OBSBasic::MoveSceneToBottom);
  4516. popup.addMenu(&order);
  4517. popup.addSeparator();
  4518. delete sceneProjectorMenu;
  4519. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4520. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4521. &OBSBasic::OpenSceneProjector);
  4522. popup.addMenu(sceneProjectorMenu);
  4523. QAction *sceneWindow = popup.addAction(
  4524. QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow);
  4525. popup.addAction(sceneWindow);
  4526. popup.addAction(QTStr("Screenshot.Scene"), this,
  4527. &OBSBasic::ScreenshotScene);
  4528. popup.addSeparator();
  4529. popup.addAction(QTStr("Filters"), this,
  4530. &OBSBasic::OpenSceneFilters);
  4531. popup.addSeparator();
  4532. delete perSceneTransitionMenu;
  4533. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4534. popup.addMenu(perSceneTransitionMenu);
  4535. /* ---------------------- */
  4536. QAction *multiviewAction =
  4537. popup.addAction(QTStr("ShowInMultiview"));
  4538. OBSSource source = GetCurrentSceneSource();
  4539. OBSDataAutoRelease data =
  4540. obs_source_get_private_settings(source);
  4541. obs_data_set_default_bool(data, "show_in_multiview", true);
  4542. bool show = obs_data_get_bool(data, "show_in_multiview");
  4543. multiviewAction->setCheckable(true);
  4544. multiviewAction->setChecked(show);
  4545. auto showInMultiview = [](OBSData data) {
  4546. bool show =
  4547. obs_data_get_bool(data, "show_in_multiview");
  4548. obs_data_set_bool(data, "show_in_multiview", !show);
  4549. OBSProjector::UpdateMultiviewProjectors();
  4550. };
  4551. connect(multiviewAction, &QAction::triggered,
  4552. std::bind(showInMultiview, data.Get()));
  4553. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4554. }
  4555. popup.addSeparator();
  4556. bool grid = ui->scenes->GetGridMode();
  4557. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4558. : QTStr("Basic.Main.GridMode"),
  4559. this);
  4560. connect(gridAction, &QAction::triggered, this,
  4561. &OBSBasic::GridActionClicked);
  4562. popup.addAction(gridAction);
  4563. popup.exec(QCursor::pos());
  4564. }
  4565. void OBSBasic::on_actionSceneListMode_triggered()
  4566. {
  4567. ui->scenes->SetGridMode(false);
  4568. }
  4569. void OBSBasic::on_actionSceneGridMode_triggered()
  4570. {
  4571. ui->scenes->SetGridMode(true);
  4572. }
  4573. void OBSBasic::GridActionClicked()
  4574. {
  4575. bool gridMode = !ui->scenes->GetGridMode();
  4576. ui->scenes->SetGridMode(gridMode);
  4577. if (gridMode)
  4578. ui->actionSceneGridMode->setChecked(true);
  4579. else
  4580. ui->actionSceneListMode->setChecked(true);
  4581. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4582. gridMode);
  4583. }
  4584. void OBSBasic::on_actionAddScene_triggered()
  4585. {
  4586. string name;
  4587. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4588. int i = 2;
  4589. QString placeHolderText = format.arg(i);
  4590. OBSSourceAutoRelease source = nullptr;
  4591. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4592. placeHolderText = format.arg(++i);
  4593. }
  4594. bool accepted = NameDialog::AskForName(
  4595. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4596. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4597. if (accepted) {
  4598. if (name.empty()) {
  4599. OBSMessageBox::warning(this,
  4600. QTStr("NoNameEntered.Title"),
  4601. QTStr("NoNameEntered.Text"));
  4602. on_actionAddScene_triggered();
  4603. return;
  4604. }
  4605. OBSSourceAutoRelease source =
  4606. obs_get_source_by_name(name.c_str());
  4607. if (source) {
  4608. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4609. QTStr("NameExists.Text"));
  4610. on_actionAddScene_triggered();
  4611. return;
  4612. }
  4613. auto undo_fn = [](const std::string &data) {
  4614. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4615. if (t) {
  4616. obs_source_remove(t);
  4617. obs_source_release(t);
  4618. }
  4619. };
  4620. auto redo_fn = [this](const std::string &data) {
  4621. OBSSceneAutoRelease scene =
  4622. obs_scene_create(data.c_str());
  4623. obs_source_t *source = obs_scene_get_source(scene);
  4624. SetCurrentScene(source, true);
  4625. };
  4626. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4627. undo_fn, redo_fn, name, name);
  4628. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4629. obs_source_t *scene_source = obs_scene_get_source(scene);
  4630. SetCurrentScene(scene_source);
  4631. }
  4632. }
  4633. void OBSBasic::on_actionRemoveScene_triggered()
  4634. {
  4635. RemoveSelectedScene();
  4636. }
  4637. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4638. {
  4639. int idx = ui->scenes->currentRow();
  4640. if (idx == -1 || idx == invalidIdx)
  4641. return;
  4642. ui->scenes->blockSignals(true);
  4643. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4644. if (!relative)
  4645. idx = 0;
  4646. ui->scenes->insertItem(idx + offset, item);
  4647. ui->scenes->setCurrentRow(idx + offset);
  4648. item->setSelected(true);
  4649. currentScene = GetOBSRef<OBSScene>(item).Get();
  4650. ui->scenes->blockSignals(false);
  4651. OBSProjector::UpdateMultiviewProjectors();
  4652. }
  4653. void OBSBasic::on_actionSceneUp_triggered()
  4654. {
  4655. ChangeSceneIndex(true, -1, 0);
  4656. }
  4657. void OBSBasic::on_actionSceneDown_triggered()
  4658. {
  4659. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4660. }
  4661. void OBSBasic::MoveSceneToTop()
  4662. {
  4663. ChangeSceneIndex(false, 0, 0);
  4664. }
  4665. void OBSBasic::MoveSceneToBottom()
  4666. {
  4667. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4668. ui->scenes->count() - 1);
  4669. }
  4670. void OBSBasic::EditSceneItemName()
  4671. {
  4672. int idx = GetTopSelectedSourceItem();
  4673. ui->sources->Edit(idx);
  4674. }
  4675. void OBSBasic::SetDeinterlacingMode()
  4676. {
  4677. QAction *action = reinterpret_cast<QAction *>(sender());
  4678. obs_deinterlace_mode mode =
  4679. (obs_deinterlace_mode)action->property("mode").toInt();
  4680. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4681. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4682. obs_source_set_deinterlace_mode(source, mode);
  4683. }
  4684. void OBSBasic::SetDeinterlacingOrder()
  4685. {
  4686. QAction *action = reinterpret_cast<QAction *>(sender());
  4687. obs_deinterlace_field_order order =
  4688. (obs_deinterlace_field_order)action->property("order").toInt();
  4689. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4690. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4691. obs_source_set_deinterlace_field_order(source, order);
  4692. }
  4693. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4694. {
  4695. obs_deinterlace_mode deinterlaceMode =
  4696. obs_source_get_deinterlace_mode(source);
  4697. obs_deinterlace_field_order deinterlaceOrder =
  4698. obs_source_get_deinterlace_field_order(source);
  4699. QAction *action;
  4700. #define ADD_MODE(name, mode) \
  4701. action = menu->addAction(QTStr("" name), this, \
  4702. &OBSBasic::SetDeinterlacingMode); \
  4703. action->setProperty("mode", (int)mode); \
  4704. action->setCheckable(true); \
  4705. action->setChecked(deinterlaceMode == mode);
  4706. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4707. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4708. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4709. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4710. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4711. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4712. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4713. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4714. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4715. #undef ADD_MODE
  4716. menu->addSeparator();
  4717. #define ADD_ORDER(name, order) \
  4718. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4719. &OBSBasic::SetDeinterlacingOrder); \
  4720. action->setProperty("order", (int)order); \
  4721. action->setCheckable(true); \
  4722. action->setChecked(deinterlaceOrder == order);
  4723. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4724. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4725. #undef ADD_ORDER
  4726. return menu;
  4727. }
  4728. void OBSBasic::SetScaleFilter()
  4729. {
  4730. QAction *action = reinterpret_cast<QAction *>(sender());
  4731. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4732. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4733. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4734. }
  4735. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4736. {
  4737. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4738. QAction *action;
  4739. #define ADD_MODE(name, mode) \
  4740. action = menu->addAction(QTStr("" name), this, \
  4741. &OBSBasic::SetScaleFilter); \
  4742. action->setProperty("mode", (int)mode); \
  4743. action->setCheckable(true); \
  4744. action->setChecked(scaleFilter == mode);
  4745. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4746. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4747. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4748. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4749. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4750. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4751. #undef ADD_MODE
  4752. return menu;
  4753. }
  4754. void OBSBasic::SetBlendingMethod()
  4755. {
  4756. QAction *action = reinterpret_cast<QAction *>(sender());
  4757. obs_blending_method method =
  4758. (obs_blending_method)action->property("method").toInt();
  4759. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4760. obs_sceneitem_set_blending_method(sceneItem, method);
  4761. }
  4762. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4763. {
  4764. obs_blending_method blendingMethod =
  4765. obs_sceneitem_get_blending_method(item);
  4766. QAction *action;
  4767. #define ADD_MODE(name, method) \
  4768. action = menu->addAction(QTStr("" name), this, \
  4769. &OBSBasic::SetBlendingMethod); \
  4770. action->setProperty("method", (int)method); \
  4771. action->setCheckable(true); \
  4772. action->setChecked(blendingMethod == method);
  4773. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4774. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4775. #undef ADD_MODE
  4776. return menu;
  4777. }
  4778. void OBSBasic::SetBlendingMode()
  4779. {
  4780. QAction *action = reinterpret_cast<QAction *>(sender());
  4781. obs_blending_type mode =
  4782. (obs_blending_type)action->property("mode").toInt();
  4783. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4784. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4785. }
  4786. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4787. {
  4788. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4789. QAction *action;
  4790. #define ADD_MODE(name, mode) \
  4791. action = menu->addAction(QTStr("" name), this, \
  4792. &OBSBasic::SetBlendingMode); \
  4793. action->setProperty("mode", (int)mode); \
  4794. action->setCheckable(true); \
  4795. action->setChecked(blendingMode == mode);
  4796. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4797. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4798. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4799. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4800. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4801. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4802. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4803. #undef ADD_MODE
  4804. return menu;
  4805. }
  4806. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4807. QWidgetAction *widgetAction,
  4808. ColorSelect *select,
  4809. obs_sceneitem_t *item)
  4810. {
  4811. QAction *action;
  4812. menu->setStyleSheet(QString(
  4813. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4814. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4815. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4816. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4817. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4818. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4819. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4820. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4821. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4822. obs_data_release(privData);
  4823. obs_data_set_default_int(privData, "color-preset", 0);
  4824. int preset = obs_data_get_int(privData, "color-preset");
  4825. action = menu->addAction(QTStr("Clear"), this, &OBSBasic::ColorChange);
  4826. action->setCheckable(true);
  4827. action->setProperty("bgColor", 0);
  4828. action->setChecked(preset == 0);
  4829. action = menu->addAction(QTStr("CustomColor"), this,
  4830. &OBSBasic::ColorChange);
  4831. action->setCheckable(true);
  4832. action->setProperty("bgColor", 1);
  4833. action->setChecked(preset == 1);
  4834. menu->addSeparator();
  4835. widgetAction->setDefaultWidget(select);
  4836. for (int i = 1; i < 9; i++) {
  4837. stringstream button;
  4838. button << "preset" << i;
  4839. QPushButton *colorButton =
  4840. select->findChild<QPushButton *>(button.str().c_str());
  4841. if (preset == i + 1)
  4842. colorButton->setStyleSheet("border: 2px solid black");
  4843. colorButton->setProperty("bgColor", i);
  4844. select->connect(colorButton, &QPushButton::released, this,
  4845. &OBSBasic::ColorChange);
  4846. }
  4847. menu->addAction(widgetAction);
  4848. return menu;
  4849. }
  4850. ColorSelect::ColorSelect(QWidget *parent)
  4851. : QWidget(parent),
  4852. ui(new Ui::ColorSelect)
  4853. {
  4854. ui->setupUi(this);
  4855. }
  4856. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4857. {
  4858. QMenu popup(this);
  4859. delete previewProjectorSource;
  4860. delete sourceProjector;
  4861. delete scaleFilteringMenu;
  4862. delete blendingMethodMenu;
  4863. delete blendingModeMenu;
  4864. delete colorMenu;
  4865. delete colorWidgetAction;
  4866. delete colorSelect;
  4867. delete deinterlaceMenu;
  4868. if (preview) {
  4869. QAction *action = popup.addAction(
  4870. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4871. &OBSBasic::TogglePreview);
  4872. action->setCheckable(true);
  4873. action->setChecked(
  4874. obs_display_enabled(ui->preview->GetDisplay()));
  4875. if (IsPreviewProgramMode())
  4876. action->setEnabled(false);
  4877. popup.addAction(ui->actionLockPreview);
  4878. popup.addMenu(ui->scalingMenu);
  4879. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4880. AddProjectorMenuMonitors(previewProjectorSource, this,
  4881. &OBSBasic::OpenPreviewProjector);
  4882. popup.addMenu(previewProjectorSource);
  4883. QAction *previewWindow =
  4884. popup.addAction(QTStr("PreviewWindow"), this,
  4885. &OBSBasic::OpenPreviewWindow);
  4886. popup.addAction(previewWindow);
  4887. popup.addAction(QTStr("Screenshot.Preview"), this,
  4888. &OBSBasic::ScreenshotScene);
  4889. popup.addSeparator();
  4890. }
  4891. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4892. if (addSourceMenu)
  4893. popup.addMenu(addSourceMenu);
  4894. if (ui->sources->MultipleBaseSelected()) {
  4895. popup.addSeparator();
  4896. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4897. &SourceTree::GroupSelectedItems);
  4898. } else if (ui->sources->GroupsSelected()) {
  4899. popup.addSeparator();
  4900. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4901. &SourceTree::UngroupSelectedGroups);
  4902. }
  4903. popup.addSeparator();
  4904. popup.addAction(ui->actionCopySource);
  4905. popup.addAction(ui->actionPasteRef);
  4906. popup.addAction(ui->actionPasteDup);
  4907. popup.addSeparator();
  4908. popup.addSeparator();
  4909. popup.addAction(ui->actionCopyFilters);
  4910. popup.addAction(ui->actionPasteFilters);
  4911. popup.addSeparator();
  4912. if (idx != -1) {
  4913. if (addSourceMenu)
  4914. popup.addSeparator();
  4915. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4916. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4917. uint32_t flags = obs_source_get_output_flags(source);
  4918. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4919. OBS_SOURCE_ASYNC_VIDEO;
  4920. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4921. bool hasVideo = (flags & OBS_SOURCE_VIDEO) == OBS_SOURCE_VIDEO;
  4922. colorMenu = new QMenu(QTStr("ChangeBG"));
  4923. colorWidgetAction = new QWidgetAction(colorMenu);
  4924. colorSelect = new ColorSelect(colorMenu);
  4925. popup.addMenu(AddBackgroundColorMenu(
  4926. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4927. popup.addAction(renameSource);
  4928. popup.addAction(ui->actionRemoveSource);
  4929. popup.addSeparator();
  4930. popup.addMenu(ui->orderMenu);
  4931. if (hasVideo)
  4932. popup.addMenu(ui->transformMenu);
  4933. popup.addSeparator();
  4934. if (hasAudio) {
  4935. QAction *actionHideMixer =
  4936. popup.addAction(QTStr("HideMixer"), this,
  4937. &OBSBasic::ToggleHideMixer);
  4938. actionHideMixer->setCheckable(true);
  4939. actionHideMixer->setChecked(SourceMixerHidden(source));
  4940. popup.addSeparator();
  4941. }
  4942. if (hasVideo) {
  4943. QAction *resizeOutput = popup.addAction(
  4944. QTStr("ResizeOutputSizeOfSource"), this,
  4945. &OBSBasic::ResizeOutputSizeOfSource);
  4946. int width = obs_source_get_width(source);
  4947. int height = obs_source_get_height(source);
  4948. resizeOutput->setEnabled(!obs_video_active());
  4949. if (width < 8 || height < 8)
  4950. resizeOutput->setEnabled(false);
  4951. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4952. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu,
  4953. sceneItem));
  4954. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4955. popup.addMenu(AddBlendingModeMenu(blendingModeMenu,
  4956. sceneItem));
  4957. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4958. popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu,
  4959. sceneItem));
  4960. if (isAsyncVideo) {
  4961. deinterlaceMenu =
  4962. new QMenu(QTStr("Deinterlacing"));
  4963. popup.addMenu(AddDeinterlacingMenu(
  4964. deinterlaceMenu, source));
  4965. }
  4966. popup.addSeparator();
  4967. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4968. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4969. popup.addSeparator();
  4970. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4971. AddProjectorMenuMonitors(
  4972. sourceProjector, this,
  4973. &OBSBasic::OpenSourceProjector);
  4974. popup.addMenu(sourceProjector);
  4975. popup.addAction(QTStr("SourceWindow"), this,
  4976. &OBSBasic::OpenSourceWindow);
  4977. popup.addAction(QTStr("Screenshot.Source"), this,
  4978. &OBSBasic::ScreenshotSelectedSource);
  4979. }
  4980. popup.addSeparator();
  4981. if (flags & OBS_SOURCE_INTERACTION)
  4982. popup.addAction(QTStr("Interact"), this,
  4983. &OBSBasic::on_actionInteract_triggered);
  4984. popup.addAction(QTStr("Filters"), this,
  4985. [&]() { OpenFilters(); });
  4986. QAction *action = popup.addAction(
  4987. QTStr("Properties"), this,
  4988. &OBSBasic::on_actionSourceProperties_triggered);
  4989. action->setEnabled(obs_source_configurable(source));
  4990. }
  4991. popup.exec(QCursor::pos());
  4992. }
  4993. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4994. {
  4995. if (ui->scenes->count()) {
  4996. QModelIndex idx = ui->sources->indexAt(pos);
  4997. CreateSourcePopupMenu(idx.row(), false);
  4998. }
  4999. }
  5000. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  5001. {
  5002. if (!witem)
  5003. return;
  5004. if (IsPreviewProgramMode()) {
  5005. bool doubleClickSwitch =
  5006. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  5007. "TransitionOnDoubleClick");
  5008. if (doubleClickSwitch)
  5009. TransitionClicked();
  5010. }
  5011. }
  5012. static inline bool should_show_properties(obs_source_t *source, const char *id)
  5013. {
  5014. if (!source)
  5015. return false;
  5016. if (strcmp(id, "group") == 0)
  5017. return false;
  5018. if (!obs_source_configurable(source))
  5019. return false;
  5020. uint32_t caps = obs_source_get_output_flags(source);
  5021. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  5022. return false;
  5023. return true;
  5024. }
  5025. void OBSBasic::AddSource(const char *id)
  5026. {
  5027. if (id && *id) {
  5028. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  5029. sourceSelect.exec();
  5030. if (should_show_properties(sourceSelect.newSource, id)) {
  5031. CreatePropertiesWindow(sourceSelect.newSource);
  5032. }
  5033. }
  5034. }
  5035. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  5036. {
  5037. const char *unversioned_type;
  5038. const char *type;
  5039. bool foundValues = false;
  5040. bool foundDeprecated = false;
  5041. size_t idx = 0;
  5042. QMenu *popup = new QMenu(QTStr("Add"), this);
  5043. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  5044. auto getActionAfter = [](QMenu *menu, const QString &name) {
  5045. QList<QAction *> actions = menu->actions();
  5046. for (QAction *menuAction : actions) {
  5047. if (menuAction->text().compare(
  5048. name, Qt::CaseInsensitive) >= 0)
  5049. return menuAction;
  5050. }
  5051. return (QAction *)nullptr;
  5052. };
  5053. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  5054. const char *name) {
  5055. QString qname = QT_UTF8(name);
  5056. QAction *popupItem = new QAction(qname, this);
  5057. connect(popupItem, &QAction::triggered,
  5058. [this, type]() { AddSource(type); });
  5059. QIcon icon;
  5060. if (strcmp(type, "scene") == 0)
  5061. icon = GetSceneIcon();
  5062. else
  5063. icon = GetSourceIcon(type);
  5064. popupItem->setIcon(icon);
  5065. QAction *after = getActionAfter(popup, qname);
  5066. popup->insertAction(after, popupItem);
  5067. };
  5068. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  5069. const char *name = obs_source_get_display_name(type);
  5070. uint32_t caps = obs_get_source_output_flags(type);
  5071. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  5072. continue;
  5073. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  5074. addSource(popup, unversioned_type, name);
  5075. } else {
  5076. addSource(deprecated, unversioned_type, name);
  5077. foundDeprecated = true;
  5078. }
  5079. foundValues = true;
  5080. }
  5081. addSource(popup, "scene", Str("Basic.Scene"));
  5082. popup->addSeparator();
  5083. QAction *addGroup = new QAction(QTStr("Group"), this);
  5084. addGroup->setIcon(GetGroupIcon());
  5085. connect(addGroup, &QAction::triggered,
  5086. [this]() { AddSource("group"); });
  5087. popup->addAction(addGroup);
  5088. if (!foundDeprecated) {
  5089. delete deprecated;
  5090. deprecated = nullptr;
  5091. }
  5092. if (!foundValues) {
  5093. delete popup;
  5094. popup = nullptr;
  5095. } else if (foundDeprecated) {
  5096. popup->addSeparator();
  5097. popup->addMenu(deprecated);
  5098. }
  5099. return popup;
  5100. }
  5101. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  5102. {
  5103. if (!GetCurrentScene()) {
  5104. // Tell the user he needs a scene first (help beginners).
  5105. OBSMessageBox::information(
  5106. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  5107. QTStr("Basic.Main.AddSourceHelp.Text"));
  5108. return;
  5109. }
  5110. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  5111. if (popup)
  5112. popup->exec(pos);
  5113. }
  5114. void OBSBasic::on_actionAddSource_triggered()
  5115. {
  5116. AddSourcePopupMenu(QCursor::pos());
  5117. }
  5118. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5119. {
  5120. vector<OBSSceneItem> &items =
  5121. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  5122. if (obs_sceneitem_selected(item)) {
  5123. items.emplace_back(item);
  5124. } else if (obs_sceneitem_is_group(item)) {
  5125. obs_sceneitem_group_enum_items(item, remove_items, &items);
  5126. }
  5127. return true;
  5128. };
  5129. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  5130. std::vector<obs_source_t *> *sources)
  5131. {
  5132. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  5133. if (!sources) {
  5134. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  5135. } else {
  5136. for (obs_source_t *source : *sources) {
  5137. obs_data_t *source_data = obs_save_source(source);
  5138. obs_data_array_push_back(undo_array, source_data);
  5139. obs_data_release(source_data);
  5140. }
  5141. }
  5142. OBSDataAutoRelease scene_data =
  5143. obs_save_source(obs_scene_get_source(scene));
  5144. obs_data_array_push_back(undo_array, scene_data);
  5145. OBSDataAutoRelease data = obs_data_create();
  5146. obs_data_set_array(data, "array", undo_array);
  5147. obs_data_get_json(data);
  5148. return data.Get();
  5149. }
  5150. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  5151. {
  5152. auto sources = static_cast<std::vector<OBSSource> *>(p);
  5153. sources->push_back(obs_sceneitem_get_source(item));
  5154. return true;
  5155. }
  5156. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  5157. OBSData undo_data, OBSData redo_data)
  5158. {
  5159. auto undo_redo = [this](const std::string &json) {
  5160. OBSDataAutoRelease base =
  5161. obs_data_create_from_json(json.c_str());
  5162. OBSDataArrayAutoRelease array =
  5163. obs_data_get_array(base, "array");
  5164. std::vector<OBSSource> sources;
  5165. std::vector<OBSSource> old_sources;
  5166. /* create missing sources */
  5167. const size_t count = obs_data_array_count(array);
  5168. sources.reserve(count);
  5169. for (size_t i = 0; i < count; i++) {
  5170. OBSDataAutoRelease data = obs_data_array_item(array, i);
  5171. const char *name = obs_data_get_string(data, "name");
  5172. OBSSourceAutoRelease source =
  5173. obs_get_source_by_name(name);
  5174. if (!source)
  5175. source = obs_load_source(data);
  5176. sources.push_back(source.Get());
  5177. /* update scene/group settings to restore their
  5178. * contents to their saved settings */
  5179. obs_scene_t *scene =
  5180. obs_group_or_scene_from_source(source);
  5181. if (scene) {
  5182. obs_scene_enum_items(scene, add_source_enum,
  5183. &old_sources);
  5184. OBSDataAutoRelease scene_settings =
  5185. obs_data_get_obj(data, "settings");
  5186. obs_source_update(source, scene_settings);
  5187. }
  5188. }
  5189. /* actually load sources now */
  5190. for (obs_source_t *source : sources)
  5191. obs_source_load2(source);
  5192. ui->sources->RefreshItems();
  5193. };
  5194. const char *undo_json = obs_data_get_last_json(undo_data);
  5195. const char *redo_json = obs_data_get_last_json(redo_data);
  5196. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  5197. redo_json);
  5198. }
  5199. void OBSBasic::on_actionRemoveSource_triggered()
  5200. {
  5201. vector<OBSSceneItem> items;
  5202. OBSScene scene = GetCurrentScene();
  5203. obs_source_t *scene_source = obs_scene_get_source(scene);
  5204. obs_scene_enum_items(scene, remove_items, &items);
  5205. if (!items.size())
  5206. return;
  5207. /* ------------------------------------- */
  5208. /* confirm action with user */
  5209. bool confirmed = false;
  5210. if (items.size() > 1) {
  5211. QString text = QTStr("ConfirmRemove.TextMultiple")
  5212. .arg(QString::number(items.size()));
  5213. QMessageBox remove_items(this);
  5214. remove_items.setText(text);
  5215. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  5216. QMessageBox::YesRole);
  5217. remove_items.setDefaultButton(Yes);
  5218. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  5219. remove_items.setIcon(QMessageBox::Question);
  5220. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  5221. remove_items.exec();
  5222. confirmed = Yes == remove_items.clickedButton();
  5223. } else {
  5224. OBSSceneItem &item = items[0];
  5225. obs_source_t *source = obs_sceneitem_get_source(item);
  5226. if (source && QueryRemoveSource(source))
  5227. confirmed = true;
  5228. }
  5229. if (!confirmed)
  5230. return;
  5231. /* ----------------------------------------------- */
  5232. /* save undo data */
  5233. OBSData undo_data = BackupScene(scene_source);
  5234. /* ----------------------------------------------- */
  5235. /* remove items */
  5236. for (auto &item : items)
  5237. obs_sceneitem_remove(item);
  5238. /* ----------------------------------------------- */
  5239. /* save redo data */
  5240. OBSData redo_data = BackupScene(scene_source);
  5241. /* ----------------------------------------------- */
  5242. /* add undo/redo action */
  5243. QString action_name;
  5244. if (items.size() > 1) {
  5245. action_name = QTStr("Undo.Sources.Multi")
  5246. .arg(QString::number(items.size()));
  5247. } else {
  5248. QString str = QTStr("Undo.Delete");
  5249. action_name = str.arg(obs_source_get_name(
  5250. obs_sceneitem_get_source(items[0])));
  5251. }
  5252. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  5253. }
  5254. void OBSBasic::on_actionInteract_triggered()
  5255. {
  5256. OBSSceneItem item = GetCurrentSceneItem();
  5257. OBSSource source = obs_sceneitem_get_source(item);
  5258. if (source)
  5259. CreateInteractionWindow(source);
  5260. }
  5261. void OBSBasic::on_actionSourceProperties_triggered()
  5262. {
  5263. OBSSceneItem item = GetCurrentSceneItem();
  5264. OBSSource source = obs_sceneitem_get_source(item);
  5265. if (source)
  5266. CreatePropertiesWindow(source);
  5267. }
  5268. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  5269. const QString &action_name)
  5270. {
  5271. OBSSceneItem item = GetCurrentSceneItem();
  5272. obs_source_t *source = obs_sceneitem_get_source(item);
  5273. if (!source)
  5274. return;
  5275. OBSScene scene = GetCurrentScene();
  5276. std::vector<obs_source_t *> sources;
  5277. if (scene != obs_sceneitem_get_scene(item))
  5278. sources.push_back(
  5279. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  5280. OBSData undo_data = BackupScene(scene, &sources);
  5281. obs_sceneitem_set_order(item, movement);
  5282. const char *source_name = obs_source_get_name(source);
  5283. const char *scene_name =
  5284. obs_source_get_name(obs_scene_get_source(scene));
  5285. OBSData redo_data = BackupScene(scene, &sources);
  5286. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  5287. undo_data, redo_data);
  5288. }
  5289. void OBSBasic::on_actionSourceUp_triggered()
  5290. {
  5291. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5292. }
  5293. void OBSBasic::on_actionSourceDown_triggered()
  5294. {
  5295. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5296. }
  5297. void OBSBasic::on_actionMoveUp_triggered()
  5298. {
  5299. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5300. }
  5301. void OBSBasic::on_actionMoveDown_triggered()
  5302. {
  5303. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5304. }
  5305. void OBSBasic::on_actionMoveToTop_triggered()
  5306. {
  5307. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  5308. }
  5309. void OBSBasic::on_actionMoveToBottom_triggered()
  5310. {
  5311. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  5312. }
  5313. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  5314. {
  5315. char logDir[512];
  5316. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  5317. return nullptr;
  5318. string path = logDir;
  5319. path += "/";
  5320. path += log;
  5321. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  5322. if (!file)
  5323. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  5324. return file;
  5325. }
  5326. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  5327. {
  5328. BPtr<char> fileString{ReadLogFile(subdir, file)};
  5329. if (!fileString)
  5330. return;
  5331. if (!*fileString)
  5332. return;
  5333. ui->menuLogFiles->setEnabled(false);
  5334. #if defined(_WIN32)
  5335. ui->menuCrashLogs->setEnabled(false);
  5336. #endif
  5337. stringstream ss;
  5338. ss << "OBS " << App()->GetVersionString(false)
  5339. << " log file uploaded at " << CurrentDateTimeString() << "\n\n"
  5340. << fileString;
  5341. if (logUploadThread) {
  5342. logUploadThread->wait();
  5343. }
  5344. RemoteTextThread *thread = new RemoteTextThread(
  5345. "https://obsproject.com/logs/upload", "text/plain", ss.str());
  5346. logUploadThread.reset(thread);
  5347. if (crash) {
  5348. connect(thread, &RemoteTextThread::Result, this,
  5349. &OBSBasic::crashUploadFinished);
  5350. } else {
  5351. connect(thread, &RemoteTextThread::Result, this,
  5352. &OBSBasic::logUploadFinished);
  5353. }
  5354. logUploadThread->start();
  5355. }
  5356. void OBSBasic::on_actionShowLogs_triggered()
  5357. {
  5358. char logDir[512];
  5359. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5360. return;
  5361. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5362. QDesktopServices::openUrl(url);
  5363. }
  5364. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5365. {
  5366. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5367. }
  5368. void OBSBasic::on_actionUploadLastLog_triggered()
  5369. {
  5370. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5371. }
  5372. void OBSBasic::on_actionViewCurrentLog_triggered()
  5373. {
  5374. if (!logView)
  5375. logView = new OBSLogViewer();
  5376. logView->show();
  5377. logView->setWindowState(
  5378. (logView->windowState() & ~Qt::WindowMinimized) |
  5379. Qt::WindowActive);
  5380. logView->activateWindow();
  5381. logView->raise();
  5382. }
  5383. void OBSBasic::on_actionShowCrashLogs_triggered()
  5384. {
  5385. char logDir[512];
  5386. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5387. return;
  5388. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5389. QDesktopServices::openUrl(url);
  5390. }
  5391. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5392. {
  5393. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5394. }
  5395. void OBSBasic::on_actionCheckForUpdates_triggered()
  5396. {
  5397. CheckForUpdates(true);
  5398. }
  5399. void OBSBasic::on_actionRepair_triggered()
  5400. {
  5401. #if defined(_WIN32)
  5402. ui->actionCheckForUpdates->setEnabled(false);
  5403. ui->actionRepair->setEnabled(false);
  5404. if (updateCheckThread && updateCheckThread->isRunning())
  5405. return;
  5406. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5407. updateCheckThread->start();
  5408. #endif
  5409. }
  5410. void OBSBasic::on_actionRestartSafe_triggered()
  5411. {
  5412. QMessageBox::StandardButton button = OBSMessageBox::question(
  5413. this, QTStr("Restart"),
  5414. safe_mode ? QTStr("SafeMode.RestartNormal")
  5415. : QTStr("SafeMode.Restart"));
  5416. if (button == QMessageBox::Yes) {
  5417. restart = safe_mode;
  5418. restart_safe = !safe_mode;
  5419. close();
  5420. }
  5421. }
  5422. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5423. {
  5424. ui->menuLogFiles->setEnabled(true);
  5425. #if defined(_WIN32)
  5426. ui->menuCrashLogs->setEnabled(true);
  5427. #endif
  5428. if (text.isEmpty()) {
  5429. OBSMessageBox::critical(
  5430. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5431. error);
  5432. return;
  5433. }
  5434. openLogDialog(text, false);
  5435. }
  5436. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5437. {
  5438. ui->menuLogFiles->setEnabled(true);
  5439. #if defined(_WIN32)
  5440. ui->menuCrashLogs->setEnabled(true);
  5441. #endif
  5442. if (text.isEmpty()) {
  5443. OBSMessageBox::critical(
  5444. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5445. error);
  5446. return;
  5447. }
  5448. openLogDialog(text, true);
  5449. }
  5450. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5451. {
  5452. OBSDataAutoRelease returnData =
  5453. obs_data_create_from_json(QT_TO_UTF8(text));
  5454. string resURL = obs_data_get_string(returnData, "url");
  5455. QString logURL = resURL.c_str();
  5456. OBSLogReply logDialog(this, logURL, crash);
  5457. logDialog.exec();
  5458. }
  5459. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5460. obs_source_t *source, const string &name)
  5461. {
  5462. const char *prevName = obs_source_get_name(source);
  5463. if (name == prevName)
  5464. return;
  5465. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5466. QListWidgetItem *listItem = listWidget->currentItem();
  5467. if (foundSource || name.empty()) {
  5468. listItem->setText(QT_UTF8(prevName));
  5469. if (foundSource) {
  5470. OBSMessageBox::warning(parent,
  5471. QTStr("NameExists.Title"),
  5472. QTStr("NameExists.Text"));
  5473. } else if (name.empty()) {
  5474. OBSMessageBox::warning(parent,
  5475. QTStr("NoNameEntered.Title"),
  5476. QTStr("NoNameEntered.Text"));
  5477. }
  5478. } else {
  5479. auto undo = [prev = std::string(prevName)](
  5480. const std::string &data) {
  5481. OBSSourceAutoRelease source =
  5482. obs_get_source_by_uuid(data.c_str());
  5483. obs_source_set_name(source, prev.c_str());
  5484. };
  5485. auto redo = [name](const std::string &data) {
  5486. OBSSourceAutoRelease source =
  5487. obs_get_source_by_uuid(data.c_str());
  5488. obs_source_set_name(source, name.c_str());
  5489. };
  5490. std::string source_uuid(obs_source_get_uuid(source));
  5491. parent->undo_s.add_action(
  5492. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5493. source_uuid, source_uuid);
  5494. listItem->setText(QT_UTF8(name.c_str()));
  5495. obs_source_set_name(source, name.c_str());
  5496. }
  5497. }
  5498. void OBSBasic::SceneNameEdited(QWidget *editor)
  5499. {
  5500. OBSScene scene = GetCurrentScene();
  5501. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5502. string text = QT_TO_UTF8(edit->text().trimmed());
  5503. if (!scene)
  5504. return;
  5505. obs_source_t *source = obs_scene_get_source(scene);
  5506. RenameListItem(this, ui->scenes, source, text);
  5507. ui->scenesDock->addAction(renameScene);
  5508. if (api)
  5509. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5510. }
  5511. void OBSBasic::OpenFilters(OBSSource source)
  5512. {
  5513. if (source == nullptr) {
  5514. OBSSceneItem item = GetCurrentSceneItem();
  5515. source = obs_sceneitem_get_source(item);
  5516. }
  5517. CreateFiltersWindow(source);
  5518. }
  5519. void OBSBasic::OpenProperties(OBSSource source)
  5520. {
  5521. if (source == nullptr) {
  5522. OBSSceneItem item = GetCurrentSceneItem();
  5523. source = obs_sceneitem_get_source(item);
  5524. }
  5525. CreatePropertiesWindow(source);
  5526. }
  5527. void OBSBasic::OpenInteraction(OBSSource source)
  5528. {
  5529. if (source == nullptr) {
  5530. OBSSceneItem item = GetCurrentSceneItem();
  5531. source = obs_sceneitem_get_source(item);
  5532. }
  5533. CreateInteractionWindow(source);
  5534. }
  5535. void OBSBasic::OpenEditTransform(OBSSceneItem item)
  5536. {
  5537. if (!item)
  5538. item = GetCurrentSceneItem();
  5539. if (!item)
  5540. return;
  5541. CreateEditTransformWindow(item);
  5542. }
  5543. void OBSBasic::OpenSceneFilters()
  5544. {
  5545. OBSScene scene = GetCurrentScene();
  5546. OBSSource source = obs_scene_get_source(scene);
  5547. CreateFiltersWindow(source);
  5548. }
  5549. #define RECORDING_START \
  5550. "==== Recording Start ==============================================="
  5551. #define RECORDING_STOP \
  5552. "==== Recording Stop ================================================"
  5553. #define REPLAY_BUFFER_START \
  5554. "==== Replay Buffer Start ==========================================="
  5555. #define REPLAY_BUFFER_STOP \
  5556. "==== Replay Buffer Stop ============================================"
  5557. #define STREAMING_START \
  5558. "==== Streaming Start ==============================================="
  5559. #define STREAMING_STOP \
  5560. "==== Streaming Stop ================================================"
  5561. #define VIRTUAL_CAM_START \
  5562. "==== Virtual Camera Start =========================================="
  5563. #define VIRTUAL_CAM_STOP \
  5564. "==== Virtual Camera Stop ==========================================="
  5565. void OBSBasic::DisplayStreamStartError()
  5566. {
  5567. QString message = !outputHandler->lastError.empty()
  5568. ? QTStr(outputHandler->lastError.c_str())
  5569. : QTStr("Output.StartFailedGeneric");
  5570. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5571. ui->streamButton->setEnabled(true);
  5572. ui->streamButton->setChecked(false);
  5573. if (sysTrayStream) {
  5574. sysTrayStream->setText(ui->streamButton->text());
  5575. sysTrayStream->setEnabled(true);
  5576. }
  5577. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5578. }
  5579. #ifdef YOUTUBE_ENABLED
  5580. void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id,
  5581. const QString &stream_id,
  5582. const QString &key, bool autostart,
  5583. bool autostop, bool start_now)
  5584. {
  5585. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5586. obs_service_t *service_obj = GetService();
  5587. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5588. const std::string a_key = QT_TO_UTF8(key);
  5589. obs_data_set_string(settings, "key", a_key.c_str());
  5590. const std::string b_id = QT_TO_UTF8(broadcast_id);
  5591. obs_data_set_string(settings, "broadcast_id", b_id.c_str());
  5592. const std::string s_id = QT_TO_UTF8(stream_id);
  5593. obs_data_set_string(settings, "stream_id", s_id.c_str());
  5594. obs_service_update(service_obj, settings);
  5595. autoStartBroadcast = autostart;
  5596. autoStopBroadcast = autostop;
  5597. broadcastReady = true;
  5598. if (start_now)
  5599. QMetaObject::invokeMethod(this, "StartStreaming");
  5600. }
  5601. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5602. {
  5603. YoutubeApiWrappers *apiYouTube(
  5604. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5605. if (!apiYouTube) {
  5606. /* technically we should never get here -Lain */
  5607. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5608. Qt::QueuedConnection);
  5609. youtubeStreamCheckThread->deleteLater();
  5610. blog(LOG_ERROR, "==========================================");
  5611. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5612. blog(LOG_ERROR, "==========================================");
  5613. return;
  5614. }
  5615. int timeout = 0;
  5616. json11::Json json;
  5617. QString id = key.c_str();
  5618. while (StreamingActive()) {
  5619. if (timeout == 14) {
  5620. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5621. Qt::QueuedConnection);
  5622. break;
  5623. }
  5624. if (!apiYouTube->FindStream(id, json)) {
  5625. QMetaObject::invokeMethod(this,
  5626. "DisplayStreamStartError",
  5627. Qt::QueuedConnection);
  5628. QMetaObject::invokeMethod(this, "StopStreaming",
  5629. Qt::QueuedConnection);
  5630. break;
  5631. }
  5632. auto item = json["items"][0];
  5633. auto status = item["status"]["streamStatus"].string_value();
  5634. if (status == "active") {
  5635. QMetaObject::invokeMethod(ui->broadcastButton,
  5636. "setEnabled",
  5637. Q_ARG(bool, true));
  5638. break;
  5639. } else {
  5640. QThread::sleep(1);
  5641. timeout++;
  5642. }
  5643. }
  5644. youtubeStreamCheckThread->deleteLater();
  5645. }
  5646. void OBSBasic::ShowYouTubeAutoStartWarning()
  5647. {
  5648. auto msgBox = []() {
  5649. QMessageBox msgbox(App()->GetMainWindow());
  5650. msgbox.setWindowTitle(QTStr(
  5651. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5652. msgbox.setText(
  5653. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5654. msgbox.setIcon(QMessageBox::Icon::Information);
  5655. msgbox.addButton(QMessageBox::Ok);
  5656. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5657. msgbox.setCheckBox(cb);
  5658. msgbox.exec();
  5659. if (cb->isChecked()) {
  5660. config_set_bool(App()->GlobalConfig(), "General",
  5661. "WarnedAboutYouTubeAutoStart", true);
  5662. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5663. }
  5664. };
  5665. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5666. "WarnedAboutYouTubeAutoStart");
  5667. if (!warned) {
  5668. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5669. Q_ARG(VoidFunc, msgBox));
  5670. }
  5671. }
  5672. #endif
  5673. void OBSBasic::StartStreaming()
  5674. {
  5675. if (outputHandler->StreamingActive())
  5676. return;
  5677. if (disableOutputsRef)
  5678. return;
  5679. if (auth && auth->broadcastFlow()) {
  5680. if (!broadcastActive && !broadcastReady) {
  5681. ui->streamButton->setChecked(false);
  5682. QMessageBox no_broadcast(this);
  5683. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5684. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5685. QTStr("Basic.Main.SetupBroadcast"),
  5686. QMessageBox::YesRole);
  5687. no_broadcast.setDefaultButton(SetupBroadcast);
  5688. no_broadcast.addButton(QTStr("Close"),
  5689. QMessageBox::NoRole);
  5690. no_broadcast.setIcon(QMessageBox::Information);
  5691. no_broadcast.setWindowTitle(
  5692. QTStr("Output.NoBroadcast.Title"));
  5693. no_broadcast.exec();
  5694. if (no_broadcast.clickedButton() == SetupBroadcast)
  5695. QMetaObject::invokeMethod(this,
  5696. "SetupBroadcast");
  5697. return;
  5698. }
  5699. }
  5700. if (!outputHandler->SetupStreaming(service)) {
  5701. DisplayStreamStartError();
  5702. return;
  5703. }
  5704. if (api)
  5705. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5706. SaveProject();
  5707. ui->streamButton->setEnabled(false);
  5708. ui->streamButton->setChecked(false);
  5709. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5710. ui->broadcastButton->setChecked(false);
  5711. if (sysTrayStream) {
  5712. sysTrayStream->setEnabled(false);
  5713. sysTrayStream->setText(ui->streamButton->text());
  5714. }
  5715. if (!outputHandler->StartStreaming(service)) {
  5716. DisplayStreamStartError();
  5717. return;
  5718. }
  5719. if (!autoStartBroadcast) {
  5720. ui->broadcastButton->setText(
  5721. QTStr("Basic.Main.StartBroadcast"));
  5722. ui->broadcastButton->setProperty("broadcastState", "ready");
  5723. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5724. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5725. // well, we need to disable button while stream is not active
  5726. ui->broadcastButton->setEnabled(false);
  5727. } else {
  5728. if (!autoStopBroadcast) {
  5729. ui->broadcastButton->setText(
  5730. QTStr("Basic.Main.StopBroadcast"));
  5731. } else {
  5732. ui->broadcastButton->setText(
  5733. QTStr("Basic.Main.AutoStopEnabled"));
  5734. ui->broadcastButton->setEnabled(false);
  5735. }
  5736. ui->broadcastButton->setProperty("broadcastState", "active");
  5737. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5738. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5739. broadcastActive = true;
  5740. }
  5741. bool recordWhenStreaming = config_get_bool(
  5742. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5743. if (recordWhenStreaming)
  5744. StartRecording();
  5745. bool replayBufferWhileStreaming = config_get_bool(
  5746. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5747. if (replayBufferWhileStreaming)
  5748. StartReplayBuffer();
  5749. #ifdef YOUTUBE_ENABLED
  5750. if (!autoStartBroadcast)
  5751. OBSBasic::ShowYouTubeAutoStartWarning();
  5752. #endif
  5753. }
  5754. void OBSBasic::BroadcastButtonClicked()
  5755. {
  5756. if (!broadcastReady ||
  5757. (!broadcastActive && !outputHandler->StreamingActive())) {
  5758. SetupBroadcast();
  5759. if (broadcastReady)
  5760. ui->broadcastButton->setChecked(true);
  5761. return;
  5762. }
  5763. if (!autoStartBroadcast) {
  5764. #ifdef YOUTUBE_ENABLED
  5765. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5766. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5767. if (ytAuth.get()) {
  5768. if (!ytAuth->StartLatestBroadcast()) {
  5769. auto last_error = ytAuth->GetLastError();
  5770. if (last_error.isEmpty())
  5771. last_error = QTStr(
  5772. "YouTube.Actions.Error.YouTubeApi");
  5773. if (!ytAuth->GetTranslatedError(last_error))
  5774. last_error =
  5775. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5776. .arg(last_error,
  5777. ytAuth->GetBroadcastId());
  5778. OBSMessageBox::warning(
  5779. this,
  5780. QTStr("Output.BroadcastStartFailed"),
  5781. last_error, true);
  5782. ui->broadcastButton->setChecked(false);
  5783. return;
  5784. }
  5785. }
  5786. #endif
  5787. broadcastActive = true;
  5788. autoStartBroadcast = true; // and clear the flag
  5789. if (!autoStopBroadcast) {
  5790. ui->broadcastButton->setText(
  5791. QTStr("Basic.Main.StopBroadcast"));
  5792. } else {
  5793. ui->broadcastButton->setText(
  5794. QTStr("Basic.Main.AutoStopEnabled"));
  5795. ui->broadcastButton->setEnabled(false);
  5796. }
  5797. ui->broadcastButton->setProperty("broadcastState", "active");
  5798. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5799. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5800. } else if (!autoStopBroadcast) {
  5801. #ifdef YOUTUBE_ENABLED
  5802. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5803. "WarnBeforeStoppingStream");
  5804. if (confirm && isVisible()) {
  5805. QMessageBox::StandardButton button = OBSMessageBox::question(
  5806. this, QTStr("ConfirmStop.Title"),
  5807. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5808. QMessageBox::Yes | QMessageBox::No,
  5809. QMessageBox::No);
  5810. if (button == QMessageBox::No) {
  5811. ui->broadcastButton->setChecked(true);
  5812. return;
  5813. }
  5814. }
  5815. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5816. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5817. if (ytAuth.get()) {
  5818. if (!ytAuth->StopLatestBroadcast()) {
  5819. auto last_error = ytAuth->GetLastError();
  5820. if (last_error.isEmpty())
  5821. last_error = QTStr(
  5822. "YouTube.Actions.Error.YouTubeApi");
  5823. if (!ytAuth->GetTranslatedError(last_error))
  5824. last_error =
  5825. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5826. .arg(last_error,
  5827. ytAuth->GetBroadcastId());
  5828. OBSMessageBox::warning(
  5829. this,
  5830. QTStr("Output.BroadcastStopFailed"),
  5831. last_error, true);
  5832. }
  5833. }
  5834. #endif
  5835. broadcastActive = false;
  5836. broadcastReady = false;
  5837. autoStopBroadcast = true;
  5838. QMetaObject::invokeMethod(this, "StopStreaming");
  5839. SetBroadcastFlowEnabled(true);
  5840. }
  5841. }
  5842. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5843. {
  5844. ui->broadcastButton->setEnabled(enabled);
  5845. ui->broadcastButton->setVisible(enabled);
  5846. ui->broadcastButton->setChecked(broadcastReady);
  5847. ui->broadcastButton->setProperty("broadcastState", "idle");
  5848. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5849. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5850. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5851. }
  5852. void OBSBasic::SetupBroadcast()
  5853. {
  5854. #ifdef YOUTUBE_ENABLED
  5855. Auth *const auth = GetAuth();
  5856. if (IsYouTubeService(auth->service())) {
  5857. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5858. connect(&dialog, &OBSYoutubeActions::ok, this,
  5859. &OBSBasic::YouTubeActionDialogOk);
  5860. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5861. if (result != QDialog::Accepted) {
  5862. if (!broadcastReady)
  5863. ui->broadcastButton->setChecked(false);
  5864. }
  5865. }
  5866. #endif
  5867. }
  5868. #ifdef _WIN32
  5869. static inline void UpdateProcessPriority()
  5870. {
  5871. const char *priority = config_get_string(App()->GlobalConfig(),
  5872. "General", "ProcessPriority");
  5873. if (priority && strcmp(priority, "Normal") != 0)
  5874. SetProcessPriority(priority);
  5875. }
  5876. static inline void ClearProcessPriority()
  5877. {
  5878. const char *priority = config_get_string(App()->GlobalConfig(),
  5879. "General", "ProcessPriority");
  5880. if (priority && strcmp(priority, "Normal") != 0)
  5881. SetProcessPriority("Normal");
  5882. }
  5883. #else
  5884. #define UpdateProcessPriority() \
  5885. do { \
  5886. } while (false)
  5887. #define ClearProcessPriority() \
  5888. do { \
  5889. } while (false)
  5890. #endif
  5891. inline void OBSBasic::OnActivate(bool force)
  5892. {
  5893. if (ui->profileMenu->isEnabled() || force) {
  5894. ui->profileMenu->setEnabled(false);
  5895. ui->autoConfigure->setEnabled(false);
  5896. App()->IncrementSleepInhibition();
  5897. UpdateProcessPriority();
  5898. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5899. if (trayIcon && trayIcon->isVisible()) {
  5900. #ifdef __APPLE__
  5901. QIcon trayMask =
  5902. QIcon(":/res/images/tray_active_macos.svg");
  5903. trayMask.setIsMask(true);
  5904. trayIcon->setIcon(
  5905. QIcon::fromTheme("obs-tray", trayMask));
  5906. #else
  5907. trayIcon->setIcon(QIcon::fromTheme(
  5908. "obs-tray-active",
  5909. QIcon(":/res/images/tray_active.png")));
  5910. #endif
  5911. }
  5912. }
  5913. }
  5914. extern volatile bool recording_paused;
  5915. extern volatile bool replaybuf_active;
  5916. inline void OBSBasic::OnDeactivate()
  5917. {
  5918. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5919. ui->profileMenu->setEnabled(true);
  5920. ui->autoConfigure->setEnabled(true);
  5921. App()->DecrementSleepInhibition();
  5922. ClearProcessPriority();
  5923. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5924. if (trayIcon && trayIcon->isVisible()) {
  5925. #ifdef __APPLE__
  5926. QIcon trayIconFile =
  5927. QIcon(":/res/images/obs_macos.svg");
  5928. trayIconFile.setIsMask(true);
  5929. #else
  5930. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5931. #endif
  5932. trayIcon->setIcon(
  5933. QIcon::fromTheme("obs-tray", trayIconFile));
  5934. }
  5935. } else if (outputHandler->Active() && trayIcon &&
  5936. trayIcon->isVisible()) {
  5937. if (os_atomic_load_bool(&recording_paused)) {
  5938. #ifdef __APPLE__
  5939. QIcon trayIconFile =
  5940. QIcon(":/res/images/obs_paused_macos.svg");
  5941. trayIconFile.setIsMask(true);
  5942. #else
  5943. QIcon trayIconFile =
  5944. QIcon(":/res/images/obs_paused.png");
  5945. #endif
  5946. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5947. trayIconFile));
  5948. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5949. } else {
  5950. #ifdef __APPLE__
  5951. QIcon trayIconFile =
  5952. QIcon(":/res/images/tray_active_macos.svg");
  5953. trayIconFile.setIsMask(true);
  5954. #else
  5955. QIcon trayIconFile =
  5956. QIcon(":/res/images/tray_active.png");
  5957. #endif
  5958. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5959. trayIconFile));
  5960. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5961. }
  5962. }
  5963. }
  5964. void OBSBasic::StopStreaming()
  5965. {
  5966. SaveProject();
  5967. if (outputHandler->StreamingActive())
  5968. outputHandler->StopStreaming(streamingStopping);
  5969. // special case: force reset broadcast state if
  5970. // no autostart and no autostop selected
  5971. if (!autoStartBroadcast && !broadcastActive) {
  5972. broadcastActive = false;
  5973. autoStartBroadcast = true;
  5974. autoStopBroadcast = true;
  5975. broadcastReady = false;
  5976. }
  5977. if (autoStopBroadcast) {
  5978. broadcastActive = false;
  5979. broadcastReady = false;
  5980. }
  5981. OnDeactivate();
  5982. bool recordWhenStreaming = config_get_bool(
  5983. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5984. bool keepRecordingWhenStreamStops =
  5985. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5986. "KeepRecordingWhenStreamStops");
  5987. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5988. StopRecording();
  5989. bool replayBufferWhileStreaming = config_get_bool(
  5990. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5991. bool keepReplayBufferStreamStops =
  5992. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5993. "KeepReplayBufferStreamStops");
  5994. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5995. StopReplayBuffer();
  5996. }
  5997. void OBSBasic::ForceStopStreaming()
  5998. {
  5999. SaveProject();
  6000. if (outputHandler->StreamingActive())
  6001. outputHandler->StopStreaming(true);
  6002. // special case: force reset broadcast state if
  6003. // no autostart and no autostop selected
  6004. if (!autoStartBroadcast && !broadcastActive) {
  6005. broadcastActive = false;
  6006. autoStartBroadcast = true;
  6007. autoStopBroadcast = true;
  6008. broadcastReady = false;
  6009. }
  6010. if (autoStopBroadcast) {
  6011. broadcastActive = false;
  6012. broadcastReady = false;
  6013. }
  6014. OnDeactivate();
  6015. bool recordWhenStreaming = config_get_bool(
  6016. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6017. bool keepRecordingWhenStreamStops =
  6018. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6019. "KeepRecordingWhenStreamStops");
  6020. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6021. StopRecording();
  6022. bool replayBufferWhileStreaming = config_get_bool(
  6023. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6024. bool keepReplayBufferStreamStops =
  6025. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6026. "KeepReplayBufferStreamStops");
  6027. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6028. StopReplayBuffer();
  6029. }
  6030. void OBSBasic::StreamDelayStarting(int sec)
  6031. {
  6032. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  6033. ui->streamButton->setEnabled(true);
  6034. ui->streamButton->setChecked(true);
  6035. if (sysTrayStream) {
  6036. sysTrayStream->setText(ui->streamButton->text());
  6037. sysTrayStream->setEnabled(true);
  6038. }
  6039. if (!startStreamMenu.isNull())
  6040. startStreamMenu->deleteLater();
  6041. startStreamMenu = new QMenu();
  6042. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  6043. &OBSBasic::StopStreaming);
  6044. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  6045. &OBSBasic::ForceStopStreaming);
  6046. ui->streamButton->setMenu(startStreamMenu);
  6047. ui->statusbar->StreamDelayStarting(sec);
  6048. OnActivate();
  6049. }
  6050. void OBSBasic::StreamDelayStopping(int sec)
  6051. {
  6052. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  6053. ui->streamButton->setEnabled(true);
  6054. ui->streamButton->setChecked(false);
  6055. if (sysTrayStream) {
  6056. sysTrayStream->setText(ui->streamButton->text());
  6057. sysTrayStream->setEnabled(true);
  6058. }
  6059. if (!startStreamMenu.isNull())
  6060. startStreamMenu->deleteLater();
  6061. startStreamMenu = new QMenu();
  6062. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  6063. &OBSBasic::StartStreaming);
  6064. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  6065. &OBSBasic::ForceStopStreaming);
  6066. ui->streamButton->setMenu(startStreamMenu);
  6067. ui->statusbar->StreamDelayStopping(sec);
  6068. if (api)
  6069. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6070. }
  6071. void OBSBasic::StreamingStart()
  6072. {
  6073. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  6074. ui->streamButton->setEnabled(true);
  6075. ui->streamButton->setChecked(true);
  6076. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  6077. if (sysTrayStream) {
  6078. sysTrayStream->setText(ui->streamButton->text());
  6079. sysTrayStream->setEnabled(true);
  6080. }
  6081. #ifdef YOUTUBE_ENABLED
  6082. if (!autoStartBroadcast) {
  6083. // get a current stream key
  6084. obs_service_t *service_obj = GetService();
  6085. OBSDataAutoRelease settings =
  6086. obs_service_get_settings(service_obj);
  6087. std::string key = obs_data_get_string(settings, "stream_id");
  6088. if (!key.empty() && !youtubeStreamCheckThread) {
  6089. youtubeStreamCheckThread = CreateQThread(
  6090. [this, key] { YoutubeStreamCheck(key); });
  6091. youtubeStreamCheckThread->setObjectName(
  6092. "YouTubeStreamCheckThread");
  6093. youtubeStreamCheckThread->start();
  6094. }
  6095. }
  6096. #endif
  6097. if (api)
  6098. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  6099. OnActivate();
  6100. #ifdef YOUTUBE_ENABLED
  6101. if (YouTubeAppDock::IsYTServiceSelected())
  6102. youtubeAppDock->IngestionStarted();
  6103. #endif
  6104. blog(LOG_INFO, STREAMING_START);
  6105. }
  6106. void OBSBasic::StreamStopping()
  6107. {
  6108. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  6109. if (sysTrayStream)
  6110. sysTrayStream->setText(ui->streamButton->text());
  6111. streamingStopping = true;
  6112. if (api)
  6113. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6114. }
  6115. void OBSBasic::StreamingStop(int code, QString last_error)
  6116. {
  6117. const char *errorDescription = "";
  6118. DStr errorMessage;
  6119. bool use_last_error = false;
  6120. bool encode_error = false;
  6121. switch (code) {
  6122. case OBS_OUTPUT_BAD_PATH:
  6123. errorDescription = Str("Output.ConnectFail.BadPath");
  6124. break;
  6125. case OBS_OUTPUT_CONNECT_FAILED:
  6126. use_last_error = true;
  6127. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  6128. break;
  6129. case OBS_OUTPUT_INVALID_STREAM:
  6130. errorDescription = Str("Output.ConnectFail.InvalidStream");
  6131. break;
  6132. case OBS_OUTPUT_ENCODE_ERROR:
  6133. encode_error = true;
  6134. break;
  6135. case OBS_OUTPUT_HDR_DISABLED:
  6136. errorDescription = Str("Output.ConnectFail.HdrDisabled");
  6137. break;
  6138. default:
  6139. case OBS_OUTPUT_ERROR:
  6140. use_last_error = true;
  6141. errorDescription = Str("Output.ConnectFail.Error");
  6142. break;
  6143. case OBS_OUTPUT_DISCONNECTED:
  6144. /* doesn't happen if output is set to reconnect. note that
  6145. * reconnects are handled in the output, not in the UI */
  6146. use_last_error = true;
  6147. errorDescription = Str("Output.ConnectFail.Disconnected");
  6148. }
  6149. if (use_last_error && !last_error.isEmpty())
  6150. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6151. QT_TO_UTF8(last_error));
  6152. else
  6153. dstr_copy(errorMessage, errorDescription);
  6154. ui->statusbar->StreamStopped();
  6155. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  6156. ui->streamButton->setEnabled(true);
  6157. ui->streamButton->setChecked(false);
  6158. if (sysTrayStream) {
  6159. sysTrayStream->setText(ui->streamButton->text());
  6160. sysTrayStream->setEnabled(true);
  6161. }
  6162. streamingStopping = false;
  6163. if (api)
  6164. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  6165. OnDeactivate();
  6166. #ifdef YOUTUBE_ENABLED
  6167. if (YouTubeAppDock::IsYTServiceSelected())
  6168. youtubeAppDock->IngestionStopped();
  6169. #endif
  6170. blog(LOG_INFO, STREAMING_STOP);
  6171. if (encode_error) {
  6172. QString msg =
  6173. last_error.isEmpty()
  6174. ? QTStr("Output.StreamEncodeError.Msg")
  6175. : QTStr("Output.StreamEncodeError.Msg.LastError")
  6176. .arg(last_error);
  6177. OBSMessageBox::information(
  6178. this, QTStr("Output.StreamEncodeError.Title"), msg);
  6179. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6180. OBSMessageBox::information(this,
  6181. QTStr("Output.ConnectFail.Title"),
  6182. QT_UTF8(errorMessage));
  6183. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6184. SysTrayNotify(QT_UTF8(errorDescription),
  6185. QSystemTrayIcon::Warning);
  6186. }
  6187. if (!startStreamMenu.isNull()) {
  6188. ui->streamButton->setMenu(nullptr);
  6189. startStreamMenu->deleteLater();
  6190. startStreamMenu = nullptr;
  6191. }
  6192. // Reset broadcast button state/text
  6193. if (!broadcastActive)
  6194. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  6195. }
  6196. void OBSBasic::AutoRemux(QString input, bool no_show)
  6197. {
  6198. auto config = Config();
  6199. bool autoRemux = config_get_bool(config, "Video", "AutoRemux");
  6200. if (!autoRemux)
  6201. return;
  6202. bool isSimpleMode = false;
  6203. const char *mode = config_get_string(config, "Output", "Mode");
  6204. if (!mode) {
  6205. isSimpleMode = true;
  6206. } else {
  6207. isSimpleMode = strcmp(mode, "Simple") == 0;
  6208. }
  6209. if (!isSimpleMode) {
  6210. const char *recType =
  6211. config_get_string(config, "AdvOut", "RecType");
  6212. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  6213. if (ffmpegOutput)
  6214. return;
  6215. }
  6216. if (input.isEmpty())
  6217. return;
  6218. QFileInfo fi(input);
  6219. QString suffix = fi.suffix();
  6220. /* do not remux if lossless */
  6221. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  6222. return;
  6223. }
  6224. QString path = fi.path();
  6225. QString output = input;
  6226. output.resize(output.size() - suffix.size());
  6227. const obs_encoder_t *videoEncoder =
  6228. obs_output_get_video_encoder(outputHandler->fileOutput);
  6229. const obs_encoder_t *audioEncoder =
  6230. obs_output_get_audio_encoder(outputHandler->fileOutput, 0);
  6231. const char *vCodecName = obs_encoder_get_codec(videoEncoder);
  6232. const char *aCodecName = obs_encoder_get_codec(audioEncoder);
  6233. const char *format = config_get_string(
  6234. config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2");
  6235. bool audio_is_pcm = strncmp(aCodecName, "pcm", 3) == 0;
  6236. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6237. /* FFmpeg <= 6.0 cannot remux AV1+PCM into any supported format. */
  6238. if (audio_is_pcm && strcmp(vCodecName, "av1") == 0)
  6239. return;
  6240. #endif
  6241. /* Retain original container for fMP4/fMOV */
  6242. if (strncmp(format, "fragmented", 10) == 0) {
  6243. output += "remuxed." + suffix;
  6244. } else if (strcmp(vCodecName, "prores") == 0) {
  6245. output += "mov";
  6246. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6247. } else if (audio_is_pcm) {
  6248. output += "mov";
  6249. #endif
  6250. } else {
  6251. output += "mp4";
  6252. }
  6253. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  6254. if (!no_show)
  6255. remux->show();
  6256. remux->AutoRemux(input, output);
  6257. }
  6258. void OBSBasic::StartRecording()
  6259. {
  6260. if (outputHandler->RecordingActive())
  6261. return;
  6262. if (disableOutputsRef)
  6263. return;
  6264. if (!OutputPathValid()) {
  6265. OutputPathInvalidMessage();
  6266. ui->recordButton->setChecked(false);
  6267. return;
  6268. }
  6269. if (LowDiskSpace()) {
  6270. DiskSpaceMessage();
  6271. ui->recordButton->setChecked(false);
  6272. return;
  6273. }
  6274. if (api)
  6275. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  6276. SaveProject();
  6277. if (!outputHandler->StartRecording())
  6278. ui->recordButton->setChecked(false);
  6279. }
  6280. void OBSBasic::RecordStopping()
  6281. {
  6282. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  6283. if (sysTrayRecord)
  6284. sysTrayRecord->setText(ui->recordButton->text());
  6285. recordingStopping = true;
  6286. if (api)
  6287. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  6288. }
  6289. void OBSBasic::StopRecording()
  6290. {
  6291. SaveProject();
  6292. if (outputHandler->RecordingActive())
  6293. outputHandler->StopRecording(recordingStopping);
  6294. OnDeactivate();
  6295. }
  6296. void OBSBasic::RecordingStart()
  6297. {
  6298. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  6299. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  6300. ui->recordButton->setChecked(true);
  6301. if (sysTrayRecord)
  6302. sysTrayRecord->setText(ui->recordButton->text());
  6303. recordingStopping = false;
  6304. if (api)
  6305. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  6306. if (!diskFullTimer->isActive())
  6307. diskFullTimer->start(1000);
  6308. OnActivate();
  6309. UpdatePause();
  6310. blog(LOG_INFO, RECORDING_START);
  6311. }
  6312. void OBSBasic::RecordingStop(int code, QString last_error)
  6313. {
  6314. ui->statusbar->RecordingStopped();
  6315. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  6316. ui->recordButton->setChecked(false);
  6317. if (sysTrayRecord)
  6318. sysTrayRecord->setText(ui->recordButton->text());
  6319. blog(LOG_INFO, RECORDING_STOP);
  6320. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6321. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6322. QTStr("Output.RecordFail.Unsupported"));
  6323. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  6324. QString msg =
  6325. last_error.isEmpty()
  6326. ? QTStr("Output.RecordError.EncodeErrorMsg")
  6327. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  6328. .arg(last_error);
  6329. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  6330. msg);
  6331. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6332. OBSMessageBox::warning(this,
  6333. QTStr("Output.RecordNoSpace.Title"),
  6334. QTStr("Output.RecordNoSpace.Msg"));
  6335. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6336. const char *errorDescription;
  6337. DStr errorMessage;
  6338. bool use_last_error = true;
  6339. errorDescription = Str("Output.RecordError.Msg");
  6340. if (use_last_error && !last_error.isEmpty())
  6341. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6342. QT_TO_UTF8(last_error));
  6343. else
  6344. dstr_copy(errorMessage, errorDescription);
  6345. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6346. QT_UTF8(errorMessage));
  6347. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6348. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6349. QSystemTrayIcon::Warning);
  6350. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6351. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6352. QSystemTrayIcon::Warning);
  6353. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6354. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6355. QSystemTrayIcon::Warning);
  6356. } else if (code == OBS_OUTPUT_SUCCESS) {
  6357. if (outputHandler) {
  6358. std::string path = outputHandler->lastRecordingPath;
  6359. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6360. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  6361. }
  6362. }
  6363. if (api)
  6364. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  6365. if (diskFullTimer->isActive())
  6366. diskFullTimer->stop();
  6367. AutoRemux(outputHandler->lastRecordingPath.c_str());
  6368. OnDeactivate();
  6369. UpdatePause(false);
  6370. }
  6371. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  6372. {
  6373. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6374. ShowStatusBarMessage(str.arg(lastRecordingPath));
  6375. AutoRemux(lastRecordingPath, true);
  6376. }
  6377. void OBSBasic::ShowReplayBufferPauseWarning()
  6378. {
  6379. auto msgBox = []() {
  6380. QMessageBox msgbox(App()->GetMainWindow());
  6381. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  6382. "PauseWarning.Title"));
  6383. msgbox.setText(QTStr("Output.ReplayBuffer."
  6384. "PauseWarning.Text"));
  6385. msgbox.setIcon(QMessageBox::Icon::Information);
  6386. msgbox.addButton(QMessageBox::Ok);
  6387. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  6388. msgbox.setCheckBox(cb);
  6389. msgbox.exec();
  6390. if (cb->isChecked()) {
  6391. config_set_bool(App()->GlobalConfig(), "General",
  6392. "WarnedAboutReplayBufferPausing", true);
  6393. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  6394. }
  6395. };
  6396. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  6397. "WarnedAboutReplayBufferPausing");
  6398. if (!warned) {
  6399. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  6400. Q_ARG(VoidFunc, msgBox));
  6401. }
  6402. }
  6403. void OBSBasic::StartReplayBuffer()
  6404. {
  6405. if (!outputHandler || !outputHandler->replayBuffer)
  6406. return;
  6407. if (outputHandler->ReplayBufferActive())
  6408. return;
  6409. if (disableOutputsRef)
  6410. return;
  6411. if (!UIValidation::NoSourcesConfirmation(this)) {
  6412. replayBufferButton->first()->setChecked(false);
  6413. return;
  6414. }
  6415. if (!OutputPathValid()) {
  6416. OutputPathInvalidMessage();
  6417. replayBufferButton->first()->setChecked(false);
  6418. return;
  6419. }
  6420. if (LowDiskSpace()) {
  6421. DiskSpaceMessage();
  6422. replayBufferButton->first()->setChecked(false);
  6423. return;
  6424. }
  6425. if (api)
  6426. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6427. SaveProject();
  6428. if (!outputHandler->StartReplayBuffer()) {
  6429. replayBufferButton->first()->setChecked(false);
  6430. } else if (os_atomic_load_bool(&recording_paused)) {
  6431. ShowReplayBufferPauseWarning();
  6432. }
  6433. }
  6434. void OBSBasic::ReplayBufferStopping()
  6435. {
  6436. if (!outputHandler || !outputHandler->replayBuffer)
  6437. return;
  6438. replayBufferButton->first()->setText(
  6439. QTStr("Basic.Main.StoppingReplayBuffer"));
  6440. if (sysTrayReplayBuffer)
  6441. sysTrayReplayBuffer->setText(
  6442. replayBufferButton->first()->text());
  6443. replayBufferStopping = true;
  6444. if (api)
  6445. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6446. }
  6447. void OBSBasic::StopReplayBuffer()
  6448. {
  6449. if (!outputHandler || !outputHandler->replayBuffer)
  6450. return;
  6451. SaveProject();
  6452. if (outputHandler->ReplayBufferActive())
  6453. outputHandler->StopReplayBuffer(replayBufferStopping);
  6454. OnDeactivate();
  6455. }
  6456. void OBSBasic::ReplayBufferStart()
  6457. {
  6458. if (!outputHandler || !outputHandler->replayBuffer)
  6459. return;
  6460. replayBufferButton->first()->setText(
  6461. QTStr("Basic.Main.StopReplayBuffer"));
  6462. replayBufferButton->first()->setChecked(true);
  6463. if (sysTrayReplayBuffer)
  6464. sysTrayReplayBuffer->setText(
  6465. replayBufferButton->first()->text());
  6466. replayBufferStopping = false;
  6467. if (api)
  6468. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6469. OnActivate();
  6470. UpdateReplayBuffer();
  6471. blog(LOG_INFO, REPLAY_BUFFER_START);
  6472. }
  6473. void OBSBasic::ReplayBufferSave()
  6474. {
  6475. if (!outputHandler || !outputHandler->replayBuffer)
  6476. return;
  6477. if (!outputHandler->ReplayBufferActive())
  6478. return;
  6479. calldata_t cd = {0};
  6480. proc_handler_t *ph =
  6481. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6482. proc_handler_call(ph, "save", &cd);
  6483. calldata_free(&cd);
  6484. }
  6485. void OBSBasic::ReplayBufferSaved()
  6486. {
  6487. if (!outputHandler || !outputHandler->replayBuffer)
  6488. return;
  6489. if (!outputHandler->ReplayBufferActive())
  6490. return;
  6491. calldata_t cd = {0};
  6492. proc_handler_t *ph =
  6493. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6494. proc_handler_call(ph, "get_last_replay", &cd);
  6495. std::string path = calldata_string(&cd, "path");
  6496. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo")
  6497. .arg(QT_UTF8(path.c_str()));
  6498. ShowStatusBarMessage(msg);
  6499. lastReplay = path;
  6500. calldata_free(&cd);
  6501. if (api)
  6502. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6503. AutoRemux(QT_UTF8(path.c_str()));
  6504. }
  6505. void OBSBasic::ReplayBufferStop(int code)
  6506. {
  6507. if (!outputHandler || !outputHandler->replayBuffer)
  6508. return;
  6509. replayBufferButton->first()->setText(
  6510. QTStr("Basic.Main.StartReplayBuffer"));
  6511. replayBufferButton->first()->setChecked(false);
  6512. if (sysTrayReplayBuffer)
  6513. sysTrayReplayBuffer->setText(
  6514. replayBufferButton->first()->text());
  6515. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6516. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6517. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6518. QTStr("Output.RecordFail.Unsupported"));
  6519. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6520. OBSMessageBox::warning(this,
  6521. QTStr("Output.RecordNoSpace.Title"),
  6522. QTStr("Output.RecordNoSpace.Msg"));
  6523. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6524. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6525. QTStr("Output.RecordError.Msg"));
  6526. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6527. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6528. QSystemTrayIcon::Warning);
  6529. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6530. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6531. QSystemTrayIcon::Warning);
  6532. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6533. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6534. QSystemTrayIcon::Warning);
  6535. }
  6536. if (api)
  6537. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6538. OnDeactivate();
  6539. UpdateReplayBuffer(false);
  6540. }
  6541. void OBSBasic::StartVirtualCam()
  6542. {
  6543. if (!outputHandler || !outputHandler->virtualCam)
  6544. return;
  6545. if (outputHandler->VirtualCamActive())
  6546. return;
  6547. if (disableOutputsRef)
  6548. return;
  6549. SaveProject();
  6550. if (!outputHandler->StartVirtualCam()) {
  6551. vcamButton->first()->setChecked(false);
  6552. }
  6553. }
  6554. void OBSBasic::StopVirtualCam()
  6555. {
  6556. if (!outputHandler || !outputHandler->virtualCam)
  6557. return;
  6558. SaveProject();
  6559. if (outputHandler->VirtualCamActive())
  6560. outputHandler->StopVirtualCam();
  6561. OnDeactivate();
  6562. }
  6563. void OBSBasic::OnVirtualCamStart()
  6564. {
  6565. if (!outputHandler || !outputHandler->virtualCam)
  6566. return;
  6567. vcamButton->first()->setText(QTStr("Basic.Main.StopVirtualCam"));
  6568. if (sysTrayVirtualCam)
  6569. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6570. vcamButton->first()->setChecked(true);
  6571. if (api)
  6572. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6573. OnActivate();
  6574. blog(LOG_INFO, VIRTUAL_CAM_START);
  6575. }
  6576. void OBSBasic::OnVirtualCamStop(int)
  6577. {
  6578. if (!outputHandler || !outputHandler->virtualCam)
  6579. return;
  6580. vcamButton->first()->setText(QTStr("Basic.Main.StartVirtualCam"));
  6581. if (sysTrayVirtualCam)
  6582. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6583. vcamButton->first()->setChecked(false);
  6584. if (api)
  6585. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6586. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6587. OnDeactivate();
  6588. if (!restartingVCam)
  6589. return;
  6590. /* Restarting needs to be delayed to make sure that the virtual camera
  6591. * implementation is stopped and avoid race condition. */
  6592. QTimer::singleShot(100, this, &OBSBasic::RestartingVirtualCam);
  6593. }
  6594. void OBSBasic::on_streamButton_clicked()
  6595. {
  6596. if (outputHandler->StreamingActive()) {
  6597. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6598. "WarnBeforeStoppingStream");
  6599. #ifdef YOUTUBE_ENABLED
  6600. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6601. autoStopBroadcast) {
  6602. QMessageBox::StandardButton button = OBSMessageBox::question(
  6603. this, QTStr("ConfirmStop.Title"),
  6604. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6605. QMessageBox::Yes | QMessageBox::No,
  6606. QMessageBox::No);
  6607. if (button == QMessageBox::No) {
  6608. ui->streamButton->setChecked(true);
  6609. return;
  6610. }
  6611. confirm = false;
  6612. }
  6613. #endif
  6614. if (confirm && isVisible()) {
  6615. QMessageBox::StandardButton button =
  6616. OBSMessageBox::question(
  6617. this, QTStr("ConfirmStop.Title"),
  6618. QTStr("ConfirmStop.Text"),
  6619. QMessageBox::Yes | QMessageBox::No,
  6620. QMessageBox::No);
  6621. if (button == QMessageBox::No) {
  6622. ui->streamButton->setChecked(true);
  6623. return;
  6624. }
  6625. }
  6626. StopStreaming();
  6627. } else {
  6628. if (!UIValidation::NoSourcesConfirmation(this)) {
  6629. ui->streamButton->setChecked(false);
  6630. return;
  6631. }
  6632. Auth *auth = GetAuth();
  6633. auto action =
  6634. (auth && auth->external())
  6635. ? StreamSettingsAction::ContinueStream
  6636. : UIValidation::StreamSettingsConfirmation(
  6637. this, service);
  6638. switch (action) {
  6639. case StreamSettingsAction::ContinueStream:
  6640. break;
  6641. case StreamSettingsAction::OpenSettings:
  6642. on_action_Settings_triggered();
  6643. ui->streamButton->setChecked(false);
  6644. return;
  6645. case StreamSettingsAction::Cancel:
  6646. ui->streamButton->setChecked(false);
  6647. return;
  6648. }
  6649. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6650. "WarnBeforeStartingStream");
  6651. bool bwtest = false;
  6652. if (this->auth) {
  6653. OBSDataAutoRelease settings =
  6654. obs_service_get_settings(service);
  6655. bwtest = obs_data_get_bool(settings, "bwtest");
  6656. // Disable confirmation if this is going to open broadcast setup
  6657. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6658. !broadcastActive)
  6659. confirm = false;
  6660. }
  6661. if (bwtest && isVisible()) {
  6662. QMessageBox::StandardButton button =
  6663. OBSMessageBox::question(
  6664. this, QTStr("ConfirmBWTest.Title"),
  6665. QTStr("ConfirmBWTest.Text"));
  6666. if (button == QMessageBox::No) {
  6667. ui->streamButton->setChecked(false);
  6668. return;
  6669. }
  6670. } else if (confirm && isVisible()) {
  6671. QMessageBox::StandardButton button =
  6672. OBSMessageBox::question(
  6673. this, QTStr("ConfirmStart.Title"),
  6674. QTStr("ConfirmStart.Text"),
  6675. QMessageBox::Yes | QMessageBox::No,
  6676. QMessageBox::No);
  6677. if (button == QMessageBox::No) {
  6678. ui->streamButton->setChecked(false);
  6679. return;
  6680. }
  6681. }
  6682. StartStreaming();
  6683. }
  6684. }
  6685. void OBSBasic::on_recordButton_clicked()
  6686. {
  6687. if (outputHandler->RecordingActive()) {
  6688. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6689. "WarnBeforeStoppingRecord");
  6690. if (confirm && isVisible()) {
  6691. QMessageBox::StandardButton button =
  6692. OBSMessageBox::question(
  6693. this, QTStr("ConfirmStopRecord.Title"),
  6694. QTStr("ConfirmStopRecord.Text"),
  6695. QMessageBox::Yes | QMessageBox::No,
  6696. QMessageBox::No);
  6697. if (button == QMessageBox::No) {
  6698. ui->recordButton->setChecked(true);
  6699. return;
  6700. }
  6701. }
  6702. StopRecording();
  6703. } else {
  6704. if (!UIValidation::NoSourcesConfirmation(this)) {
  6705. ui->recordButton->setChecked(false);
  6706. return;
  6707. }
  6708. StartRecording();
  6709. }
  6710. }
  6711. void OBSBasic::VCamButtonClicked()
  6712. {
  6713. if (outputHandler->VirtualCamActive()) {
  6714. StopVirtualCam();
  6715. } else {
  6716. if (!UIValidation::NoSourcesConfirmation(this)) {
  6717. vcamButton->first()->setChecked(false);
  6718. return;
  6719. }
  6720. StartVirtualCam();
  6721. }
  6722. }
  6723. void OBSBasic::VCamConfigButtonClicked()
  6724. {
  6725. OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(),
  6726. this);
  6727. connect(&dialog, &OBSBasicVCamConfig::Accepted, this,
  6728. &OBSBasic::UpdateVirtualCamConfig);
  6729. connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this,
  6730. &OBSBasic::RestartVirtualCam);
  6731. dialog.exec();
  6732. }
  6733. void OBSBasic::UpdateVirtualCamConfig(const VCamConfig &config)
  6734. {
  6735. vcamConfig = config;
  6736. outputHandler->UpdateVirtualCamOutputSource();
  6737. }
  6738. void OBSBasic::RestartVirtualCam(const VCamConfig &config)
  6739. {
  6740. restartingVCam = true;
  6741. StopVirtualCam();
  6742. vcamConfig = config;
  6743. }
  6744. void OBSBasic::RestartingVirtualCam()
  6745. {
  6746. if (!restartingVCam)
  6747. return;
  6748. outputHandler->UpdateVirtualCamOutputSource();
  6749. StartVirtualCam();
  6750. restartingVCam = false;
  6751. }
  6752. void OBSBasic::on_settingsButton_clicked()
  6753. {
  6754. on_action_Settings_triggered();
  6755. }
  6756. void OBSBasic::on_actionHelpPortal_triggered()
  6757. {
  6758. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6759. QDesktopServices::openUrl(url);
  6760. }
  6761. void OBSBasic::on_actionWebsite_triggered()
  6762. {
  6763. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6764. QDesktopServices::openUrl(url);
  6765. }
  6766. void OBSBasic::on_actionDiscord_triggered()
  6767. {
  6768. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6769. QDesktopServices::openUrl(url);
  6770. }
  6771. void OBSBasic::on_actionShowWhatsNew_triggered()
  6772. {
  6773. #ifdef WHATSNEW_ENABLED
  6774. if (introCheckThread && introCheckThread->isRunning())
  6775. return;
  6776. if (!cef)
  6777. return;
  6778. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement", -1);
  6779. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  6780. connect(wnit, &WhatsNewInfoThread::Result, this,
  6781. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  6782. introCheckThread.reset(wnit);
  6783. introCheckThread->start();
  6784. #endif
  6785. }
  6786. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6787. {
  6788. char path[512];
  6789. int ret = GetConfigPath(path, 512, "obs-studio");
  6790. if (ret <= 0)
  6791. return;
  6792. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6793. }
  6794. void OBSBasic::on_actionShowProfileFolder_triggered()
  6795. {
  6796. char path[512];
  6797. int ret = GetProfilePath(path, 512, "");
  6798. if (ret <= 0)
  6799. return;
  6800. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6801. }
  6802. int OBSBasic::GetTopSelectedSourceItem()
  6803. {
  6804. QModelIndexList selectedItems =
  6805. ui->sources->selectionModel()->selectedIndexes();
  6806. return selectedItems.count() ? selectedItems[0].row() : -1;
  6807. }
  6808. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6809. {
  6810. return ui->sources->selectionModel()->selectedIndexes();
  6811. }
  6812. void OBSBasic::on_preview_customContextMenuRequested()
  6813. {
  6814. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6815. }
  6816. void OBSBasic::ProgramViewContextMenuRequested()
  6817. {
  6818. QMenu popup(this);
  6819. QPointer<QMenu> studioProgramProjector;
  6820. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6821. AddProjectorMenuMonitors(studioProgramProjector, this,
  6822. &OBSBasic::OpenStudioProgramProjector);
  6823. popup.addMenu(studioProgramProjector);
  6824. QAction *studioProgramWindow =
  6825. popup.addAction(QTStr("StudioProgramWindow"), this,
  6826. &OBSBasic::OpenStudioProgramWindow);
  6827. popup.addAction(studioProgramWindow);
  6828. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6829. &OBSBasic::ScreenshotProgram);
  6830. popup.exec(QCursor::pos());
  6831. }
  6832. void OBSBasic::on_previewDisabledWidget_customContextMenuRequested()
  6833. {
  6834. QMenu popup(this);
  6835. delete previewProjectorMain;
  6836. QAction *action =
  6837. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6838. this, &OBSBasic::TogglePreview);
  6839. action->setCheckable(true);
  6840. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6841. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6842. AddProjectorMenuMonitors(previewProjectorMain, this,
  6843. &OBSBasic::OpenPreviewProjector);
  6844. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6845. &OBSBasic::OpenPreviewWindow);
  6846. popup.addMenu(previewProjectorMain);
  6847. popup.addAction(previewWindow);
  6848. popup.exec(QCursor::pos());
  6849. }
  6850. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6851. {
  6852. #ifndef _WIN32
  6853. /* Make sure all dialogs are safely and successfully closed before
  6854. * switching the always on top mode due to the fact that windows all
  6855. * have to be recreated, so queue the actual toggle to happen after
  6856. * all events related to closing the dialogs have finished */
  6857. CloseDialogs();
  6858. #endif
  6859. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6860. Qt::QueuedConnection);
  6861. }
  6862. void OBSBasic::ToggleAlwaysOnTop()
  6863. {
  6864. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6865. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6866. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6867. show();
  6868. }
  6869. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6870. {
  6871. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6872. if (strcmp(val, "10") == 0) {
  6873. num = 10;
  6874. den = 1;
  6875. } else if (strcmp(val, "20") == 0) {
  6876. num = 20;
  6877. den = 1;
  6878. } else if (strcmp(val, "24 NTSC") == 0) {
  6879. num = 24000;
  6880. den = 1001;
  6881. } else if (strcmp(val, "25 PAL") == 0) {
  6882. num = 25;
  6883. den = 1;
  6884. } else if (strcmp(val, "29.97") == 0) {
  6885. num = 30000;
  6886. den = 1001;
  6887. } else if (strcmp(val, "48") == 0) {
  6888. num = 48;
  6889. den = 1;
  6890. } else if (strcmp(val, "50 PAL") == 0) {
  6891. num = 50;
  6892. den = 1;
  6893. } else if (strcmp(val, "59.94") == 0) {
  6894. num = 60000;
  6895. den = 1001;
  6896. } else if (strcmp(val, "60") == 0) {
  6897. num = 60;
  6898. den = 1;
  6899. } else {
  6900. num = 30;
  6901. den = 1;
  6902. }
  6903. }
  6904. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6905. {
  6906. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6907. den = 1;
  6908. }
  6909. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6910. {
  6911. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6912. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6913. }
  6914. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6915. {
  6916. num = 1000000000;
  6917. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6918. }
  6919. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6920. {
  6921. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6922. if (type == 1) //"Integer"
  6923. GetFPSInteger(num, den);
  6924. else if (type == 2) //"Fraction"
  6925. GetFPSFraction(num, den);
  6926. /*
  6927. * else if (false) //"Nanoseconds", currently not implemented
  6928. * GetFPSNanoseconds(num, den);
  6929. */
  6930. else
  6931. GetFPSCommon(num, den);
  6932. }
  6933. config_t *OBSBasic::Config() const
  6934. {
  6935. return basicConfig;
  6936. }
  6937. #ifdef YOUTUBE_ENABLED
  6938. YouTubeAppDock *OBSBasic::GetYouTubeAppDock()
  6939. {
  6940. return youtubeAppDock;
  6941. }
  6942. void OBSBasic::NewYouTubeAppDock()
  6943. {
  6944. if (!cef_js_avail)
  6945. return;
  6946. if (youtubeAppDock)
  6947. RemoveDockWidget(youtubeAppDock->objectName());
  6948. youtubeAppDock = new YouTubeAppDock();
  6949. }
  6950. void OBSBasic::DeleteYouTubeAppDock()
  6951. {
  6952. if (!cef_js_avail)
  6953. return;
  6954. if (youtubeAppDock)
  6955. RemoveDockWidget(youtubeAppDock->objectName());
  6956. youtubeAppDock = nullptr;
  6957. }
  6958. #endif
  6959. void OBSBasic::UpdateEditMenu()
  6960. {
  6961. QModelIndexList items = GetAllSelectedSourceItems();
  6962. int count = items.count();
  6963. size_t filter_count = 0;
  6964. if (count == 1) {
  6965. OBSSceneItem sceneItem =
  6966. ui->sources->Get(GetTopSelectedSourceItem());
  6967. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6968. filter_count = obs_source_filter_count(source);
  6969. }
  6970. bool allowPastingDuplicate = !!clipboard.size();
  6971. for (size_t i = clipboard.size(); i > 0; i--) {
  6972. const size_t idx = i - 1;
  6973. OBSWeakSource &weak = clipboard[idx].weak_source;
  6974. if (obs_weak_source_expired(weak)) {
  6975. clipboard.erase(clipboard.begin() + idx);
  6976. continue;
  6977. }
  6978. OBSSourceAutoRelease strong =
  6979. obs_weak_source_get_source(weak.Get());
  6980. if (allowPastingDuplicate &&
  6981. obs_source_get_output_flags(strong) &
  6982. OBS_SOURCE_DO_NOT_DUPLICATE)
  6983. allowPastingDuplicate = false;
  6984. }
  6985. ui->actionCopySource->setEnabled(count > 0);
  6986. ui->actionEditTransform->setEnabled(count == 1);
  6987. ui->actionCopyTransform->setEnabled(count == 1);
  6988. ui->actionPasteTransform->setEnabled(hasCopiedTransform && count > 0);
  6989. ui->actionCopyFilters->setEnabled(filter_count > 0);
  6990. ui->actionPasteFilters->setEnabled(
  6991. !obs_weak_source_expired(copyFiltersSource) && count > 0);
  6992. ui->actionPasteRef->setEnabled(!!clipboard.size());
  6993. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6994. ui->actionMoveUp->setEnabled(count > 0);
  6995. ui->actionMoveDown->setEnabled(count > 0);
  6996. ui->actionMoveToTop->setEnabled(count > 0);
  6997. ui->actionMoveToBottom->setEnabled(count > 0);
  6998. bool canTransform = false;
  6999. for (int i = 0; i < count; i++) {
  7000. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  7001. if (!obs_sceneitem_locked(item))
  7002. canTransform = true;
  7003. }
  7004. ui->actionResetTransform->setEnabled(canTransform);
  7005. ui->actionRotate90CW->setEnabled(canTransform);
  7006. ui->actionRotate90CCW->setEnabled(canTransform);
  7007. ui->actionRotate180->setEnabled(canTransform);
  7008. ui->actionFlipHorizontal->setEnabled(canTransform);
  7009. ui->actionFlipVertical->setEnabled(canTransform);
  7010. ui->actionFitToScreen->setEnabled(canTransform);
  7011. ui->actionStretchToScreen->setEnabled(canTransform);
  7012. ui->actionCenterToScreen->setEnabled(canTransform);
  7013. ui->actionVerticalCenter->setEnabled(canTransform);
  7014. ui->actionHorizontalCenter->setEnabled(canTransform);
  7015. }
  7016. void OBSBasic::on_actionEditTransform_triggered()
  7017. {
  7018. const auto item = GetCurrentSceneItem();
  7019. if (!item)
  7020. return;
  7021. CreateEditTransformWindow(item);
  7022. }
  7023. void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item)
  7024. {
  7025. if (transformWindow)
  7026. transformWindow->close();
  7027. transformWindow = new OBSBasicTransform(item, this);
  7028. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  7029. &OBSBasicTransform::OnSceneChanged);
  7030. transformWindow->show();
  7031. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  7032. }
  7033. void OBSBasic::on_actionCopyTransform_triggered()
  7034. {
  7035. OBSSceneItem item = GetCurrentSceneItem();
  7036. obs_sceneitem_get_info(item, &copiedTransformInfo);
  7037. obs_sceneitem_get_crop(item, &copiedCropInfo);
  7038. ui->actionPasteTransform->setEnabled(true);
  7039. hasCopiedTransform = true;
  7040. }
  7041. void undo_redo(const std::string &data)
  7042. {
  7043. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  7044. OBSSourceAutoRelease source =
  7045. obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid"));
  7046. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  7047. ->SetCurrentScene(source.Get(), true);
  7048. obs_scene_load_transform_states(data.c_str());
  7049. }
  7050. void OBSBasic::on_actionPasteTransform_triggered()
  7051. {
  7052. OBSDataAutoRelease wrapper =
  7053. obs_scene_save_transform_states(GetCurrentScene(), false);
  7054. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  7055. if (!obs_sceneitem_selected(item))
  7056. return true;
  7057. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  7058. obs_sceneitem_defer_update_begin(item);
  7059. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  7060. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  7061. obs_sceneitem_defer_update_end(item);
  7062. return true;
  7063. };
  7064. obs_scene_enum_items(GetCurrentScene(), func, this);
  7065. OBSDataAutoRelease rwrapper =
  7066. obs_scene_save_transform_states(GetCurrentScene(), false);
  7067. std::string undo_data(obs_data_get_json(wrapper));
  7068. std::string redo_data(obs_data_get_json(rwrapper));
  7069. undo_s.add_action(
  7070. QTStr("Undo.Transform.Paste")
  7071. .arg(obs_source_get_name(GetCurrentSceneSource())),
  7072. undo_redo, undo_redo, undo_data, redo_data);
  7073. }
  7074. static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *)
  7075. {
  7076. if (obs_sceneitem_is_group(item))
  7077. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  7078. if (!obs_sceneitem_selected(item))
  7079. return true;
  7080. if (obs_sceneitem_locked(item))
  7081. return true;
  7082. obs_sceneitem_defer_update_begin(item);
  7083. obs_transform_info info;
  7084. vec2_set(&info.pos, 0.0f, 0.0f);
  7085. vec2_set(&info.scale, 1.0f, 1.0f);
  7086. info.rot = 0.0f;
  7087. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  7088. info.bounds_type = OBS_BOUNDS_NONE;
  7089. info.bounds_alignment = OBS_ALIGN_CENTER;
  7090. vec2_set(&info.bounds, 0.0f, 0.0f);
  7091. obs_sceneitem_set_info(item, &info);
  7092. obs_sceneitem_crop crop = {};
  7093. obs_sceneitem_set_crop(item, &crop);
  7094. obs_sceneitem_defer_update_end(item);
  7095. return true;
  7096. }
  7097. void OBSBasic::on_actionResetTransform_triggered()
  7098. {
  7099. OBSScene scene = GetCurrentScene();
  7100. OBSDataAutoRelease wrapper =
  7101. obs_scene_save_transform_states(scene, false);
  7102. obs_scene_enum_items(scene, reset_tr, nullptr);
  7103. OBSDataAutoRelease rwrapper =
  7104. obs_scene_save_transform_states(scene, false);
  7105. std::string undo_data(obs_data_get_json(wrapper));
  7106. std::string redo_data(obs_data_get_json(rwrapper));
  7107. undo_s.add_action(
  7108. QTStr("Undo.Transform.Reset")
  7109. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  7110. undo_redo, undo_redo, undo_data, redo_data);
  7111. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  7112. }
  7113. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  7114. {
  7115. matrix4 boxTransform;
  7116. obs_sceneitem_get_box_transform(item, &boxTransform);
  7117. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  7118. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  7119. auto GetMinPos = [&](float x, float y) {
  7120. vec3 pos;
  7121. vec3_set(&pos, x, y, 0.0f);
  7122. vec3_transform(&pos, &pos, &boxTransform);
  7123. vec3_min(&tl, &tl, &pos);
  7124. vec3_max(&br, &br, &pos);
  7125. };
  7126. GetMinPos(0.0f, 0.0f);
  7127. GetMinPos(1.0f, 0.0f);
  7128. GetMinPos(0.0f, 1.0f);
  7129. GetMinPos(1.0f, 1.0f);
  7130. }
  7131. static vec3 GetItemTL(obs_sceneitem_t *item)
  7132. {
  7133. vec3 tl, br;
  7134. GetItemBox(item, tl, br);
  7135. return tl;
  7136. }
  7137. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  7138. {
  7139. vec3 newTL;
  7140. vec2 pos;
  7141. obs_sceneitem_get_pos(item, &pos);
  7142. newTL = GetItemTL(item);
  7143. pos.x += tl.x - newTL.x;
  7144. pos.y += tl.y - newTL.y;
  7145. obs_sceneitem_set_pos(item, &pos);
  7146. }
  7147. static bool RotateSelectedSources(obs_scene_t * /* scene */,
  7148. obs_sceneitem_t *item, void *param)
  7149. {
  7150. if (obs_sceneitem_is_group(item))
  7151. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  7152. param);
  7153. if (!obs_sceneitem_selected(item))
  7154. return true;
  7155. if (obs_sceneitem_locked(item))
  7156. return true;
  7157. float rot = *reinterpret_cast<float *>(param);
  7158. vec3 tl = GetItemTL(item);
  7159. rot += obs_sceneitem_get_rot(item);
  7160. if (rot >= 360.0f)
  7161. rot -= 360.0f;
  7162. else if (rot <= -360.0f)
  7163. rot += 360.0f;
  7164. obs_sceneitem_set_rot(item, rot);
  7165. obs_sceneitem_force_update_transform(item);
  7166. SetItemTL(item, tl);
  7167. return true;
  7168. };
  7169. void OBSBasic::on_actionRotate90CW_triggered()
  7170. {
  7171. float f90CW = 90.0f;
  7172. OBSDataAutoRelease wrapper =
  7173. obs_scene_save_transform_states(GetCurrentScene(), false);
  7174. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  7175. OBSDataAutoRelease rwrapper =
  7176. obs_scene_save_transform_states(GetCurrentScene(), false);
  7177. std::string undo_data(obs_data_get_json(wrapper));
  7178. std::string redo_data(obs_data_get_json(rwrapper));
  7179. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7180. .arg(obs_source_get_name(obs_scene_get_source(
  7181. GetCurrentScene()))),
  7182. undo_redo, undo_redo, undo_data, redo_data);
  7183. }
  7184. void OBSBasic::on_actionRotate90CCW_triggered()
  7185. {
  7186. float f90CCW = -90.0f;
  7187. OBSDataAutoRelease wrapper =
  7188. obs_scene_save_transform_states(GetCurrentScene(), false);
  7189. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  7190. OBSDataAutoRelease rwrapper =
  7191. obs_scene_save_transform_states(GetCurrentScene(), false);
  7192. std::string undo_data(obs_data_get_json(wrapper));
  7193. std::string redo_data(obs_data_get_json(rwrapper));
  7194. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7195. .arg(obs_source_get_name(obs_scene_get_source(
  7196. GetCurrentScene()))),
  7197. undo_redo, undo_redo, undo_data, redo_data);
  7198. }
  7199. void OBSBasic::on_actionRotate180_triggered()
  7200. {
  7201. float f180 = 180.0f;
  7202. OBSDataAutoRelease wrapper =
  7203. obs_scene_save_transform_states(GetCurrentScene(), false);
  7204. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  7205. OBSDataAutoRelease rwrapper =
  7206. obs_scene_save_transform_states(GetCurrentScene(), false);
  7207. std::string undo_data(obs_data_get_json(wrapper));
  7208. std::string redo_data(obs_data_get_json(rwrapper));
  7209. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7210. .arg(obs_source_get_name(obs_scene_get_source(
  7211. GetCurrentScene()))),
  7212. undo_redo, undo_redo, undo_data, redo_data);
  7213. }
  7214. static bool MultiplySelectedItemScale(obs_scene_t * /* scene */,
  7215. obs_sceneitem_t *item, void *param)
  7216. {
  7217. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  7218. if (obs_sceneitem_is_group(item))
  7219. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  7220. param);
  7221. if (!obs_sceneitem_selected(item))
  7222. return true;
  7223. if (obs_sceneitem_locked(item))
  7224. return true;
  7225. vec3 tl = GetItemTL(item);
  7226. vec2 scale;
  7227. obs_sceneitem_get_scale(item, &scale);
  7228. vec2_mul(&scale, &scale, &mul);
  7229. obs_sceneitem_set_scale(item, &scale);
  7230. obs_sceneitem_force_update_transform(item);
  7231. SetItemTL(item, tl);
  7232. return true;
  7233. }
  7234. void OBSBasic::on_actionFlipHorizontal_triggered()
  7235. {
  7236. vec2 scale;
  7237. vec2_set(&scale, -1.0f, 1.0f);
  7238. OBSDataAutoRelease wrapper =
  7239. obs_scene_save_transform_states(GetCurrentScene(), false);
  7240. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7241. &scale);
  7242. OBSDataAutoRelease rwrapper =
  7243. obs_scene_save_transform_states(GetCurrentScene(), false);
  7244. std::string undo_data(obs_data_get_json(wrapper));
  7245. std::string redo_data(obs_data_get_json(rwrapper));
  7246. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  7247. .arg(obs_source_get_name(obs_scene_get_source(
  7248. GetCurrentScene()))),
  7249. undo_redo, undo_redo, undo_data, redo_data);
  7250. }
  7251. void OBSBasic::on_actionFlipVertical_triggered()
  7252. {
  7253. vec2 scale;
  7254. vec2_set(&scale, 1.0f, -1.0f);
  7255. OBSDataAutoRelease wrapper =
  7256. obs_scene_save_transform_states(GetCurrentScene(), false);
  7257. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7258. &scale);
  7259. OBSDataAutoRelease rwrapper =
  7260. obs_scene_save_transform_states(GetCurrentScene(), false);
  7261. std::string undo_data(obs_data_get_json(wrapper));
  7262. std::string redo_data(obs_data_get_json(rwrapper));
  7263. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  7264. .arg(obs_source_get_name(obs_scene_get_source(
  7265. GetCurrentScene()))),
  7266. undo_redo, undo_redo, undo_data, redo_data);
  7267. }
  7268. static bool CenterAlignSelectedItems(obs_scene_t * /* scene */,
  7269. obs_sceneitem_t *item, void *param)
  7270. {
  7271. obs_bounds_type boundsType =
  7272. *reinterpret_cast<obs_bounds_type *>(param);
  7273. if (obs_sceneitem_is_group(item))
  7274. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  7275. param);
  7276. if (!obs_sceneitem_selected(item))
  7277. return true;
  7278. if (obs_sceneitem_locked(item))
  7279. return true;
  7280. obs_video_info ovi;
  7281. obs_get_video_info(&ovi);
  7282. obs_transform_info itemInfo;
  7283. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  7284. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  7285. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  7286. itemInfo.rot = 0.0f;
  7287. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  7288. float(ovi.base_height));
  7289. itemInfo.bounds_type = boundsType;
  7290. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  7291. obs_sceneitem_set_info(item, &itemInfo);
  7292. return true;
  7293. }
  7294. void OBSBasic::on_actionFitToScreen_triggered()
  7295. {
  7296. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  7297. OBSDataAutoRelease wrapper =
  7298. obs_scene_save_transform_states(GetCurrentScene(), false);
  7299. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7300. &boundsType);
  7301. OBSDataAutoRelease rwrapper =
  7302. obs_scene_save_transform_states(GetCurrentScene(), false);
  7303. std::string undo_data(obs_data_get_json(wrapper));
  7304. std::string redo_data(obs_data_get_json(rwrapper));
  7305. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  7306. .arg(obs_source_get_name(obs_scene_get_source(
  7307. GetCurrentScene()))),
  7308. undo_redo, undo_redo, undo_data, redo_data);
  7309. }
  7310. void OBSBasic::on_actionStretchToScreen_triggered()
  7311. {
  7312. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  7313. OBSDataAutoRelease wrapper =
  7314. obs_scene_save_transform_states(GetCurrentScene(), false);
  7315. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7316. &boundsType);
  7317. OBSDataAutoRelease rwrapper =
  7318. obs_scene_save_transform_states(GetCurrentScene(), false);
  7319. std::string undo_data(obs_data_get_json(wrapper));
  7320. std::string redo_data(obs_data_get_json(rwrapper));
  7321. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  7322. .arg(obs_source_get_name(obs_scene_get_source(
  7323. GetCurrentScene()))),
  7324. undo_redo, undo_redo, undo_data, redo_data);
  7325. }
  7326. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  7327. {
  7328. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  7329. if (!selectedItems.count())
  7330. return;
  7331. vector<OBSSceneItem> items;
  7332. // Filter out items that have no size
  7333. for (int x = 0; x < selectedItems.count(); x++) {
  7334. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  7335. obs_transform_info oti;
  7336. obs_sceneitem_get_info(item, &oti);
  7337. obs_source_t *source = obs_sceneitem_get_source(item);
  7338. float width = float(obs_source_get_width(source)) * oti.scale.x;
  7339. float height =
  7340. float(obs_source_get_height(source)) * oti.scale.y;
  7341. if (width == 0.0f || height == 0.0f)
  7342. continue;
  7343. items.emplace_back(item);
  7344. }
  7345. if (!items.size())
  7346. return;
  7347. // Get center x, y coordinates of items
  7348. vec3 center;
  7349. float top = M_INFINITE;
  7350. float left = M_INFINITE;
  7351. float right = 0.0f;
  7352. float bottom = 0.0f;
  7353. for (auto &item : items) {
  7354. vec3 tl, br;
  7355. GetItemBox(item, tl, br);
  7356. left = (std::min)(tl.x, left);
  7357. top = (std::min)(tl.y, top);
  7358. right = (std::max)(br.x, right);
  7359. bottom = (std::max)(br.y, bottom);
  7360. }
  7361. center.x = (right + left) / 2.0f;
  7362. center.y = (top + bottom) / 2.0f;
  7363. center.z = 0.0f;
  7364. // Get coordinates of screen center
  7365. obs_video_info ovi;
  7366. obs_get_video_info(&ovi);
  7367. vec3 screenCenter;
  7368. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  7369. 0.0f);
  7370. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  7371. // Calculate difference between screen center and item center
  7372. vec3 offset;
  7373. vec3_sub(&offset, &screenCenter, &center);
  7374. // Shift items by offset
  7375. for (auto &item : items) {
  7376. vec3 tl, br;
  7377. GetItemBox(item, tl, br);
  7378. vec3_add(&tl, &tl, &offset);
  7379. vec3 itemTL = GetItemTL(item);
  7380. if (centerType == CenterType::Vertical)
  7381. tl.x = itemTL.x;
  7382. else if (centerType == CenterType::Horizontal)
  7383. tl.y = itemTL.y;
  7384. SetItemTL(item, tl);
  7385. }
  7386. }
  7387. void OBSBasic::on_actionCenterToScreen_triggered()
  7388. {
  7389. CenterType centerType = CenterType::Scene;
  7390. OBSDataAutoRelease wrapper =
  7391. obs_scene_save_transform_states(GetCurrentScene(), false);
  7392. CenterSelectedSceneItems(centerType);
  7393. OBSDataAutoRelease rwrapper =
  7394. obs_scene_save_transform_states(GetCurrentScene(), false);
  7395. std::string undo_data(obs_data_get_json(wrapper));
  7396. std::string redo_data(obs_data_get_json(rwrapper));
  7397. undo_s.add_action(QTStr("Undo.Transform.Center")
  7398. .arg(obs_source_get_name(obs_scene_get_source(
  7399. GetCurrentScene()))),
  7400. undo_redo, undo_redo, undo_data, redo_data);
  7401. }
  7402. void OBSBasic::on_actionVerticalCenter_triggered()
  7403. {
  7404. CenterType centerType = CenterType::Vertical;
  7405. OBSDataAutoRelease wrapper =
  7406. obs_scene_save_transform_states(GetCurrentScene(), false);
  7407. CenterSelectedSceneItems(centerType);
  7408. OBSDataAutoRelease rwrapper =
  7409. obs_scene_save_transform_states(GetCurrentScene(), false);
  7410. std::string undo_data(obs_data_get_json(wrapper));
  7411. std::string redo_data(obs_data_get_json(rwrapper));
  7412. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  7413. .arg(obs_source_get_name(obs_scene_get_source(
  7414. GetCurrentScene()))),
  7415. undo_redo, undo_redo, undo_data, redo_data);
  7416. }
  7417. void OBSBasic::on_actionHorizontalCenter_triggered()
  7418. {
  7419. CenterType centerType = CenterType::Horizontal;
  7420. OBSDataAutoRelease wrapper =
  7421. obs_scene_save_transform_states(GetCurrentScene(), false);
  7422. CenterSelectedSceneItems(centerType);
  7423. OBSDataAutoRelease rwrapper =
  7424. obs_scene_save_transform_states(GetCurrentScene(), false);
  7425. std::string undo_data(obs_data_get_json(wrapper));
  7426. std::string redo_data(obs_data_get_json(rwrapper));
  7427. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  7428. .arg(obs_source_get_name(obs_scene_get_source(
  7429. GetCurrentScene()))),
  7430. undo_redo, undo_redo, undo_data, redo_data);
  7431. }
  7432. void OBSBasic::EnablePreviewDisplay(bool enable)
  7433. {
  7434. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  7435. ui->preview->setVisible(enable);
  7436. ui->previewDisabledWidget->setVisible(!enable);
  7437. }
  7438. void OBSBasic::TogglePreview()
  7439. {
  7440. previewEnabled = !previewEnabled;
  7441. EnablePreviewDisplay(previewEnabled);
  7442. }
  7443. void OBSBasic::EnablePreview()
  7444. {
  7445. if (previewProgramMode)
  7446. return;
  7447. previewEnabled = true;
  7448. EnablePreviewDisplay(true);
  7449. }
  7450. void OBSBasic::DisablePreview()
  7451. {
  7452. if (previewProgramMode)
  7453. return;
  7454. previewEnabled = false;
  7455. EnablePreviewDisplay(false);
  7456. }
  7457. void OBSBasic::EnablePreviewProgram()
  7458. {
  7459. SetPreviewProgramMode(true);
  7460. }
  7461. void OBSBasic::DisablePreviewProgram()
  7462. {
  7463. SetPreviewProgramMode(false);
  7464. }
  7465. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  7466. {
  7467. if (obs_sceneitem_locked(item))
  7468. return true;
  7469. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  7470. struct vec2 pos;
  7471. if (!obs_sceneitem_selected(item)) {
  7472. if (obs_sceneitem_is_group(item)) {
  7473. struct vec3 offset3;
  7474. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  7475. struct matrix4 matrix;
  7476. obs_sceneitem_get_draw_transform(item, &matrix);
  7477. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  7478. matrix4_inv(&matrix, &matrix);
  7479. vec3_transform(&offset3, &offset3, &matrix);
  7480. struct vec2 new_offset;
  7481. vec2_set(&new_offset, offset3.x, offset3.y);
  7482. obs_sceneitem_group_enum_items(item, nudge_callback,
  7483. &new_offset);
  7484. }
  7485. return true;
  7486. }
  7487. obs_sceneitem_get_pos(item, &pos);
  7488. vec2_add(&pos, &pos, &offset);
  7489. obs_sceneitem_set_pos(item, &pos);
  7490. return true;
  7491. }
  7492. void OBSBasic::Nudge(int dist, MoveDir dir)
  7493. {
  7494. if (ui->preview->Locked())
  7495. return;
  7496. struct vec2 offset;
  7497. vec2_set(&offset, 0.0f, 0.0f);
  7498. switch (dir) {
  7499. case MoveDir::Up:
  7500. offset.y = (float)-dist;
  7501. break;
  7502. case MoveDir::Down:
  7503. offset.y = (float)dist;
  7504. break;
  7505. case MoveDir::Left:
  7506. offset.x = (float)-dist;
  7507. break;
  7508. case MoveDir::Right:
  7509. offset.x = (float)dist;
  7510. break;
  7511. }
  7512. if (!recent_nudge) {
  7513. recent_nudge = true;
  7514. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7515. GetCurrentScene(), true);
  7516. std::string undo_data(obs_data_get_json(wrapper));
  7517. nudge_timer = new QTimer;
  7518. QObject::connect(
  7519. nudge_timer, &QTimer::timeout,
  7520. [this, &recent_nudge = recent_nudge, undo_data]() {
  7521. OBSDataAutoRelease rwrapper =
  7522. obs_scene_save_transform_states(
  7523. GetCurrentScene(), true);
  7524. std::string redo_data(
  7525. obs_data_get_json(rwrapper));
  7526. undo_s.add_action(
  7527. QTStr("Undo.Transform")
  7528. .arg(obs_source_get_name(
  7529. GetCurrentSceneSource())),
  7530. undo_redo, undo_redo, undo_data,
  7531. redo_data);
  7532. recent_nudge = false;
  7533. });
  7534. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7535. &QTimer::deleteLater);
  7536. nudge_timer->setSingleShot(true);
  7537. }
  7538. if (nudge_timer) {
  7539. nudge_timer->stop();
  7540. nudge_timer->start(1000);
  7541. } else {
  7542. blog(LOG_ERROR, "No nudge timer!");
  7543. }
  7544. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7545. }
  7546. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7547. {
  7548. for (size_t i = 0; i < projectors.size(); i++) {
  7549. if (projectors[i] == projector) {
  7550. projectors[i]->deleteLater();
  7551. projectors.erase(projectors.begin() + i);
  7552. break;
  7553. }
  7554. }
  7555. }
  7556. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7557. ProjectorType type)
  7558. {
  7559. /* seriously? 10 monitors? */
  7560. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7561. return nullptr;
  7562. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7563. "CloseExistingProjectors");
  7564. if (closeProjectors && monitor > -1) {
  7565. for (size_t i = projectors.size(); i > 0; i--) {
  7566. size_t idx = i - 1;
  7567. if (projectors[idx]->GetMonitor() == monitor)
  7568. DeleteProjector(projectors[idx]);
  7569. }
  7570. }
  7571. OBSProjector *projector =
  7572. new OBSProjector(nullptr, source, monitor, type);
  7573. projectors.emplace_back(projector);
  7574. return projector;
  7575. }
  7576. void OBSBasic::OpenStudioProgramProjector()
  7577. {
  7578. int monitor = sender()->property("monitor").toInt();
  7579. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7580. }
  7581. void OBSBasic::OpenPreviewProjector()
  7582. {
  7583. int monitor = sender()->property("monitor").toInt();
  7584. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7585. }
  7586. void OBSBasic::OpenSourceProjector()
  7587. {
  7588. int monitor = sender()->property("monitor").toInt();
  7589. OBSSceneItem item = GetCurrentSceneItem();
  7590. if (!item)
  7591. return;
  7592. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7593. ProjectorType::Source);
  7594. }
  7595. void OBSBasic::OpenMultiviewProjector()
  7596. {
  7597. int monitor = sender()->property("monitor").toInt();
  7598. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7599. }
  7600. void OBSBasic::OpenSceneProjector()
  7601. {
  7602. int monitor = sender()->property("monitor").toInt();
  7603. OBSScene scene = GetCurrentScene();
  7604. if (!scene)
  7605. return;
  7606. OpenProjector(obs_scene_get_source(scene), monitor,
  7607. ProjectorType::Scene);
  7608. }
  7609. void OBSBasic::OpenStudioProgramWindow()
  7610. {
  7611. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7612. }
  7613. void OBSBasic::OpenPreviewWindow()
  7614. {
  7615. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7616. }
  7617. void OBSBasic::OpenSourceWindow()
  7618. {
  7619. OBSSceneItem item = GetCurrentSceneItem();
  7620. if (!item)
  7621. return;
  7622. OBSSource source = obs_sceneitem_get_source(item);
  7623. OpenProjector(obs_sceneitem_get_source(item), -1,
  7624. ProjectorType::Source);
  7625. }
  7626. void OBSBasic::OpenSceneWindow()
  7627. {
  7628. OBSScene scene = GetCurrentScene();
  7629. if (!scene)
  7630. return;
  7631. OBSSource source = obs_scene_get_source(scene);
  7632. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7633. }
  7634. void OBSBasic::OpenSavedProjectors()
  7635. {
  7636. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7637. OpenSavedProjector(info);
  7638. }
  7639. }
  7640. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7641. {
  7642. if (info) {
  7643. OBSProjector *projector = nullptr;
  7644. switch (info->type) {
  7645. case ProjectorType::Source:
  7646. case ProjectorType::Scene: {
  7647. OBSSourceAutoRelease source =
  7648. obs_get_source_by_name(info->name.c_str());
  7649. if (!source)
  7650. return;
  7651. projector = OpenProjector(source, info->monitor,
  7652. info->type);
  7653. break;
  7654. }
  7655. default: {
  7656. projector = OpenProjector(nullptr, info->monitor,
  7657. info->type);
  7658. break;
  7659. }
  7660. }
  7661. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7662. QByteArray byteArray = QByteArray::fromBase64(
  7663. QByteArray(info->geometry.c_str()));
  7664. projector->restoreGeometry(byteArray);
  7665. if (!WindowPositionValid(projector->normalGeometry())) {
  7666. QRect rect = QGuiApplication::primaryScreen()
  7667. ->geometry();
  7668. projector->setGeometry(QStyle::alignedRect(
  7669. Qt::LeftToRight, Qt::AlignCenter,
  7670. size(), rect));
  7671. }
  7672. if (info->alwaysOnTopOverridden)
  7673. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7674. true);
  7675. }
  7676. }
  7677. }
  7678. void OBSBasic::on_actionFullscreenInterface_triggered()
  7679. {
  7680. if (!isFullScreen())
  7681. showFullScreen();
  7682. else
  7683. showNormal();
  7684. }
  7685. void OBSBasic::UpdateTitleBar()
  7686. {
  7687. stringstream name;
  7688. const char *profile =
  7689. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7690. const char *sceneCollection = config_get_string(
  7691. App()->GlobalConfig(), "Basic", "SceneCollection");
  7692. name << "OBS ";
  7693. if (previewProgramMode)
  7694. name << "Studio ";
  7695. name << App()->GetVersionString(false);
  7696. if (safe_mode)
  7697. name << " (" << Str("TitleBar.SafeMode") << ")";
  7698. if (App()->IsPortableMode())
  7699. name << " - " << Str("TitleBar.PortableMode");
  7700. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7701. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7702. setWindowTitle(QT_UTF8(name.str().c_str()));
  7703. }
  7704. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7705. {
  7706. char profiles_path[512];
  7707. const char *profile =
  7708. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7709. int ret;
  7710. if (!profile)
  7711. return -1;
  7712. if (!path)
  7713. return -1;
  7714. if (!file)
  7715. file = "";
  7716. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7717. if (ret <= 0)
  7718. return ret;
  7719. if (!*file)
  7720. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7721. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7722. }
  7723. void OBSBasic::on_resetDocks_triggered(bool force)
  7724. {
  7725. /* prune deleted extra docks */
  7726. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7727. if (!oldExtraDocks[i]) {
  7728. oldExtraDocks.removeAt(i);
  7729. oldExtraDockNames.removeAt(i);
  7730. }
  7731. }
  7732. #ifdef BROWSER_AVAILABLE
  7733. if ((oldExtraDocks.size() || extraDocks.size() ||
  7734. extraCustomDocks.size() || extraBrowserDocks.size()) &&
  7735. !force) {
  7736. #else
  7737. if ((oldExtraDocks.size() || extraDocks.size() ||
  7738. extraCustomDocks.size()) &&
  7739. !force) {
  7740. #endif
  7741. QMessageBox::StandardButton button = QMessageBox::question(
  7742. this, QTStr("ResetUIWarning.Title"),
  7743. QTStr("ResetUIWarning.Text"));
  7744. if (button == QMessageBox::No)
  7745. return;
  7746. }
  7747. /* undock/hide/center extra docks */
  7748. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7749. if (oldExtraDocks[i]) {
  7750. oldExtraDocks[i]->setVisible(true);
  7751. oldExtraDocks[i]->setFloating(true);
  7752. oldExtraDocks[i]->move(
  7753. frameGeometry().topLeft() + rect().center() -
  7754. oldExtraDocks[i]->rect().center());
  7755. oldExtraDocks[i]->setVisible(false);
  7756. }
  7757. }
  7758. #define RESET_DOCKLIST(dockList) \
  7759. for (int i = dockList.size() - 1; i >= 0; i--) { \
  7760. dockList[i]->setVisible(true); \
  7761. dockList[i]->setFloating(true); \
  7762. dockList[i]->move(frameGeometry().topLeft() + \
  7763. rect().center() - \
  7764. dockList[i]->rect().center()); \
  7765. dockList[i]->setVisible(false); \
  7766. }
  7767. RESET_DOCKLIST(extraDocks)
  7768. RESET_DOCKLIST(extraCustomDocks)
  7769. #ifdef BROWSER_AVAILABLE
  7770. RESET_DOCKLIST(extraBrowserDocks)
  7771. #endif
  7772. #undef RESET_DOCKLIST
  7773. restoreState(startingDockLayout);
  7774. int cx = width();
  7775. int cy = height();
  7776. int cx22_5 = cx * 225 / 1000;
  7777. int cx5 = cx * 5 / 100;
  7778. int cx21 = cx * 21 / 100;
  7779. cy = cy * 225 / 1000;
  7780. int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21);
  7781. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7782. ui->mixerDock, ui->transitionsDock,
  7783. ui->controlsDock};
  7784. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx21};
  7785. ui->scenesDock->setVisible(true);
  7786. ui->sourcesDock->setVisible(true);
  7787. ui->mixerDock->setVisible(true);
  7788. ui->transitionsDock->setVisible(true);
  7789. ui->controlsDock->setVisible(true);
  7790. statsDock->setVisible(false);
  7791. statsDock->setFloating(true);
  7792. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7793. resizeDocks(docks, sizes, Qt::Horizontal);
  7794. activateWindow();
  7795. }
  7796. void OBSBasic::on_lockDocks_toggled(bool lock)
  7797. {
  7798. QDockWidget::DockWidgetFeatures features =
  7799. lock ? QDockWidget::NoDockWidgetFeatures
  7800. : (QDockWidget::DockWidgetClosable |
  7801. QDockWidget::DockWidgetMovable |
  7802. QDockWidget::DockWidgetFloatable);
  7803. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7804. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7805. ui->scenesDock->setFeatures(mainFeatures);
  7806. ui->sourcesDock->setFeatures(mainFeatures);
  7807. ui->mixerDock->setFeatures(mainFeatures);
  7808. ui->transitionsDock->setFeatures(mainFeatures);
  7809. ui->controlsDock->setFeatures(mainFeatures);
  7810. statsDock->setFeatures(features);
  7811. for (int i = extraDocks.size() - 1; i >= 0; i--)
  7812. extraDocks[i]->setFeatures(features);
  7813. for (int i = extraCustomDocks.size() - 1; i >= 0; i--)
  7814. extraCustomDocks[i]->setFeatures(features);
  7815. #ifdef BROWSER_AVAILABLE
  7816. for (int i = extraBrowserDocks.size() - 1; i >= 0; i--)
  7817. extraBrowserDocks[i]->setFeatures(features);
  7818. #endif
  7819. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7820. if (!oldExtraDocks[i]) {
  7821. oldExtraDocks.removeAt(i);
  7822. oldExtraDockNames.removeAt(i);
  7823. } else {
  7824. oldExtraDocks[i]->setFeatures(features);
  7825. }
  7826. }
  7827. }
  7828. void OBSBasic::on_sideDocks_toggled(bool side)
  7829. {
  7830. if (side) {
  7831. setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
  7832. setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
  7833. setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
  7834. setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
  7835. } else {
  7836. setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea);
  7837. setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
  7838. setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
  7839. setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
  7840. }
  7841. }
  7842. void OBSBasic::on_resetUI_triggered()
  7843. {
  7844. on_resetDocks_triggered();
  7845. ui->toggleListboxToolbars->setChecked(true);
  7846. ui->toggleContextBar->setChecked(true);
  7847. ui->toggleSourceIcons->setChecked(true);
  7848. ui->toggleStatusBar->setChecked(true);
  7849. ui->scenes->SetGridMode(false);
  7850. ui->actionSceneListMode->setChecked(true);
  7851. }
  7852. void OBSBasic::on_multiviewProjectorWindowed_triggered()
  7853. {
  7854. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7855. }
  7856. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7857. {
  7858. ui->sourcesToolbar->setVisible(visible);
  7859. ui->scenesToolbar->setVisible(visible);
  7860. ui->mixerToolbar->setVisible(visible);
  7861. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7862. "ShowListboxToolbars", visible);
  7863. }
  7864. void OBSBasic::ShowContextBar()
  7865. {
  7866. on_toggleContextBar_toggled(true);
  7867. ui->toggleContextBar->setChecked(true);
  7868. }
  7869. void OBSBasic::HideContextBar()
  7870. {
  7871. on_toggleContextBar_toggled(false);
  7872. ui->toggleContextBar->setChecked(false);
  7873. }
  7874. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7875. {
  7876. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7877. "ShowContextToolbars", visible);
  7878. this->ui->contextContainer->setVisible(visible);
  7879. UpdateContextBar(true);
  7880. }
  7881. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7882. {
  7883. ui->statusbar->setVisible(visible);
  7884. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7885. visible);
  7886. }
  7887. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7888. {
  7889. ui->sources->SetIconsVisible(visible);
  7890. if (advAudioWindow != nullptr)
  7891. advAudioWindow->SetIconsVisible(visible);
  7892. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7893. visible);
  7894. }
  7895. void OBSBasic::on_actionLockPreview_triggered()
  7896. {
  7897. ui->preview->ToggleLocked();
  7898. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7899. }
  7900. void OBSBasic::on_scalingMenu_aboutToShow()
  7901. {
  7902. obs_video_info ovi;
  7903. obs_get_video_info(&ovi);
  7904. QAction *action = ui->actionScaleCanvas;
  7905. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7906. text = text.arg(QString::number(ovi.base_width),
  7907. QString::number(ovi.base_height));
  7908. action->setText(text);
  7909. action = ui->actionScaleOutput;
  7910. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7911. text = text.arg(QString::number(ovi.output_width),
  7912. QString::number(ovi.output_height));
  7913. action->setText(text);
  7914. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7915. ovi.output_height == ovi.base_height));
  7916. UpdatePreviewScalingMenu();
  7917. }
  7918. void OBSBasic::on_actionScaleWindow_triggered()
  7919. {
  7920. ui->preview->SetFixedScaling(false);
  7921. ui->preview->ResetScrollingOffset();
  7922. emit ui->preview->DisplayResized();
  7923. }
  7924. void OBSBasic::on_actionScaleCanvas_triggered()
  7925. {
  7926. ui->preview->SetFixedScaling(true);
  7927. ui->preview->SetScalingLevel(0);
  7928. emit ui->preview->DisplayResized();
  7929. }
  7930. void OBSBasic::on_actionScaleOutput_triggered()
  7931. {
  7932. obs_video_info ovi;
  7933. obs_get_video_info(&ovi);
  7934. ui->preview->SetFixedScaling(true);
  7935. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7936. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7937. int32_t approxScalingLevel =
  7938. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7939. ui->preview->SetScalingLevel(approxScalingLevel);
  7940. ui->preview->SetScalingAmount(scalingAmount);
  7941. emit ui->preview->DisplayResized();
  7942. }
  7943. void OBSBasic::SetShowing(bool showing)
  7944. {
  7945. if (!showing && isVisible()) {
  7946. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7947. "geometry",
  7948. saveGeometry().toBase64().constData());
  7949. /* hide all visible child dialogs */
  7950. visDlgPositions.clear();
  7951. if (!visDialogs.isEmpty()) {
  7952. for (QDialog *dlg : visDialogs) {
  7953. visDlgPositions.append(dlg->pos());
  7954. dlg->hide();
  7955. }
  7956. }
  7957. if (showHide)
  7958. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7959. QTimer::singleShot(0, this, &OBSBasic::hide);
  7960. if (previewEnabled)
  7961. EnablePreviewDisplay(false);
  7962. #ifdef __APPLE__
  7963. EnableOSXDockIcon(false);
  7964. #endif
  7965. } else if (showing && !isVisible()) {
  7966. if (showHide)
  7967. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7968. QTimer::singleShot(0, this, &OBSBasic::show);
  7969. if (previewEnabled)
  7970. EnablePreviewDisplay(true);
  7971. #ifdef __APPLE__
  7972. EnableOSXDockIcon(true);
  7973. #endif
  7974. /* raise and activate window to ensure it is on top */
  7975. raise();
  7976. activateWindow();
  7977. /* show all child dialogs that was visible earlier */
  7978. if (!visDialogs.isEmpty()) {
  7979. for (int i = 0; i < visDialogs.size(); ++i) {
  7980. QDialog *dlg = visDialogs[i];
  7981. dlg->move(visDlgPositions[i]);
  7982. dlg->show();
  7983. }
  7984. }
  7985. /* Unminimize window if it was hidden to tray instead of task
  7986. * bar. */
  7987. if (sysTrayMinimizeToTray()) {
  7988. Qt::WindowStates state;
  7989. state = windowState() & ~Qt::WindowMinimized;
  7990. state |= Qt::WindowActive;
  7991. setWindowState(state);
  7992. }
  7993. }
  7994. }
  7995. void OBSBasic::ToggleShowHide()
  7996. {
  7997. bool showing = isVisible();
  7998. if (showing) {
  7999. /* check for modal dialogs */
  8000. EnumDialogs();
  8001. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  8002. return;
  8003. }
  8004. SetShowing(!showing);
  8005. }
  8006. void OBSBasic::SystemTrayInit()
  8007. {
  8008. #ifdef __APPLE__
  8009. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  8010. trayIconFile.setIsMask(true);
  8011. #else
  8012. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  8013. #endif
  8014. trayIcon.reset(new QSystemTrayIcon(
  8015. QIcon::fromTheme("obs-tray", trayIconFile), this));
  8016. trayIcon->setToolTip("OBS Studio");
  8017. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  8018. sysTrayStream = new QAction(
  8019. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  8020. : QTStr("Basic.Main.StartStreaming"),
  8021. trayIcon.data());
  8022. sysTrayRecord = new QAction(
  8023. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  8024. : QTStr("Basic.Main.StartRecording"),
  8025. trayIcon.data());
  8026. sysTrayReplayBuffer = new QAction(
  8027. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  8028. : QTStr("Basic.Main.StartReplayBuffer"),
  8029. trayIcon.data());
  8030. sysTrayVirtualCam = new QAction(
  8031. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  8032. : QTStr("Basic.Main.StartVirtualCam"),
  8033. trayIcon.data());
  8034. exit = new QAction(QTStr("Exit"), trayIcon.data());
  8035. trayMenu = new QMenu;
  8036. previewProjector = new QMenu(QTStr("PreviewProjector"));
  8037. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  8038. AddProjectorMenuMonitors(previewProjector, this,
  8039. &OBSBasic::OpenPreviewProjector);
  8040. AddProjectorMenuMonitors(studioProgramProjector, this,
  8041. &OBSBasic::OpenStudioProgramProjector);
  8042. trayMenu->addAction(showHide);
  8043. trayMenu->addSeparator();
  8044. trayMenu->addMenu(previewProjector);
  8045. trayMenu->addMenu(studioProgramProjector);
  8046. trayMenu->addSeparator();
  8047. trayMenu->addAction(sysTrayStream);
  8048. trayMenu->addAction(sysTrayRecord);
  8049. trayMenu->addAction(sysTrayReplayBuffer);
  8050. trayMenu->addAction(sysTrayVirtualCam);
  8051. trayMenu->addSeparator();
  8052. trayMenu->addAction(exit);
  8053. trayIcon->setContextMenu(trayMenu);
  8054. trayIcon->show();
  8055. if (outputHandler && !outputHandler->replayBuffer)
  8056. sysTrayReplayBuffer->setEnabled(false);
  8057. sysTrayVirtualCam->setEnabled(vcamEnabled);
  8058. if (Active())
  8059. OnActivate(true);
  8060. connect(trayIcon.data(), &QSystemTrayIcon::activated, this,
  8061. &OBSBasic::IconActivated);
  8062. connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide);
  8063. connect(sysTrayStream, &QAction::triggered, this,
  8064. &OBSBasic::on_streamButton_clicked);
  8065. connect(sysTrayRecord, &QAction::triggered, this,
  8066. &OBSBasic::on_recordButton_clicked);
  8067. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  8068. &OBSBasic::ReplayBufferClicked);
  8069. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  8070. &OBSBasic::VCamButtonClicked);
  8071. connect(exit, &QAction::triggered, this, &OBSBasic::close);
  8072. }
  8073. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  8074. {
  8075. // Refresh projector list
  8076. previewProjector->clear();
  8077. studioProgramProjector->clear();
  8078. AddProjectorMenuMonitors(previewProjector, this,
  8079. &OBSBasic::OpenPreviewProjector);
  8080. AddProjectorMenuMonitors(studioProgramProjector, this,
  8081. &OBSBasic::OpenStudioProgramProjector);
  8082. #ifdef __APPLE__
  8083. UNUSED_PARAMETER(reason);
  8084. #else
  8085. if (reason == QSystemTrayIcon::Trigger) {
  8086. EnablePreviewDisplay(previewEnabled && !isVisible());
  8087. ToggleShowHide();
  8088. }
  8089. #endif
  8090. }
  8091. void OBSBasic::SysTrayNotify(const QString &text,
  8092. QSystemTrayIcon::MessageIcon n)
  8093. {
  8094. if (trayIcon && trayIcon->isVisible() &&
  8095. QSystemTrayIcon::supportsMessages()) {
  8096. QSystemTrayIcon::MessageIcon icon =
  8097. QSystemTrayIcon::MessageIcon(n);
  8098. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  8099. }
  8100. }
  8101. void OBSBasic::SystemTray(bool firstStarted)
  8102. {
  8103. if (!QSystemTrayIcon::isSystemTrayAvailable())
  8104. return;
  8105. if (!trayIcon && !firstStarted)
  8106. return;
  8107. bool sysTrayWhenStarted = config_get_bool(
  8108. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  8109. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  8110. "SysTrayEnabled");
  8111. if (firstStarted)
  8112. SystemTrayInit();
  8113. if (!sysTrayEnabled) {
  8114. trayIcon->hide();
  8115. } else {
  8116. trayIcon->show();
  8117. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  8118. EnablePreviewDisplay(false);
  8119. #ifdef __APPLE__
  8120. EnableOSXDockIcon(false);
  8121. #endif
  8122. opt_minimize_tray = false;
  8123. }
  8124. }
  8125. if (isVisible())
  8126. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8127. else
  8128. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8129. }
  8130. bool OBSBasic::sysTrayMinimizeToTray()
  8131. {
  8132. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  8133. "SysTrayMinimizeToTray");
  8134. }
  8135. void OBSBasic::on_actionMainUndo_triggered()
  8136. {
  8137. undo_s.undo();
  8138. }
  8139. void OBSBasic::on_actionMainRedo_triggered()
  8140. {
  8141. undo_s.redo();
  8142. }
  8143. void OBSBasic::on_actionCopySource_triggered()
  8144. {
  8145. clipboard.clear();
  8146. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  8147. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  8148. if (!item)
  8149. continue;
  8150. OBSSource source = obs_sceneitem_get_source(item);
  8151. SourceCopyInfo copyInfo;
  8152. copyInfo.weak_source = OBSGetWeakRef(source);
  8153. obs_sceneitem_get_info(item, &copyInfo.transform);
  8154. obs_sceneitem_get_crop(item, &copyInfo.crop);
  8155. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  8156. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  8157. copyInfo.visible = obs_sceneitem_visible(item);
  8158. clipboard.push_back(copyInfo);
  8159. }
  8160. UpdateEditMenu();
  8161. }
  8162. void OBSBasic::on_actionPasteRef_triggered()
  8163. {
  8164. OBSSource scene_source = GetCurrentSceneSource();
  8165. OBSData undo_data = BackupScene(scene_source);
  8166. OBSScene scene = GetCurrentScene();
  8167. undo_s.push_disabled();
  8168. for (size_t i = clipboard.size(); i > 0; i--) {
  8169. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8170. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  8171. if (!source)
  8172. continue;
  8173. const char *name = obs_source_get_name(source);
  8174. /* do not allow duplicate refs of the same group in the same
  8175. * scene */
  8176. if (!!obs_scene_get_group(scene, name)) {
  8177. continue;
  8178. }
  8179. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  8180. }
  8181. undo_s.pop_disabled();
  8182. QString action_name = QTStr("Undo.PasteSourceRef");
  8183. const char *scene_name = obs_source_get_name(scene_source);
  8184. OBSData redo_data = BackupScene(scene_source);
  8185. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8186. redo_data);
  8187. }
  8188. void OBSBasic::on_actionPasteDup_triggered()
  8189. {
  8190. OBSSource scene_source = GetCurrentSceneSource();
  8191. OBSData undo_data = BackupScene(scene_source);
  8192. undo_s.push_disabled();
  8193. for (size_t i = clipboard.size(); i > 0; i--) {
  8194. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8195. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  8196. }
  8197. undo_s.pop_disabled();
  8198. QString action_name = QTStr("Undo.PasteSource");
  8199. const char *scene_name = obs_source_get_name(scene_source);
  8200. OBSData redo_data = BackupScene(scene_source);
  8201. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8202. redo_data);
  8203. }
  8204. void OBSBasic::AudioMixerCopyFilters()
  8205. {
  8206. QAction *action = reinterpret_cast<QAction *>(sender());
  8207. VolControl *vol = action->property("volControl").value<VolControl *>();
  8208. obs_source_t *source = vol->GetSource();
  8209. copyFiltersSource = obs_source_get_weak_source(source);
  8210. }
  8211. void OBSBasic::AudioMixerPasteFilters()
  8212. {
  8213. QAction *action = reinterpret_cast<QAction *>(sender());
  8214. VolControl *vol = action->property("volControl").value<VolControl *>();
  8215. obs_source_t *dstSource = vol->GetSource();
  8216. OBSSourceAutoRelease source =
  8217. obs_weak_source_get_source(copyFiltersSource);
  8218. if (source == dstSource)
  8219. return;
  8220. obs_source_copy_filters(dstSource, source);
  8221. }
  8222. void OBSBasic::SceneCopyFilters()
  8223. {
  8224. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  8225. }
  8226. void OBSBasic::ScenePasteFilters()
  8227. {
  8228. OBSSourceAutoRelease source =
  8229. obs_weak_source_get_source(copyFiltersSource);
  8230. OBSSource dstSource = GetCurrentSceneSource();
  8231. if (source == dstSource)
  8232. return;
  8233. obs_source_copy_filters(dstSource, source);
  8234. }
  8235. void OBSBasic::on_actionCopyFilters_triggered()
  8236. {
  8237. OBSSceneItem item = GetCurrentSceneItem();
  8238. if (!item)
  8239. return;
  8240. OBSSource source = obs_sceneitem_get_source(item);
  8241. copyFiltersSource = obs_source_get_weak_source(source);
  8242. ui->actionPasteFilters->setEnabled(true);
  8243. }
  8244. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  8245. obs_source_t *source,
  8246. obs_data_array_t *undo_array,
  8247. obs_data_array_t *redo_array)
  8248. {
  8249. auto undo_redo = [this](const std::string &json) {
  8250. OBSDataAutoRelease data =
  8251. obs_data_create_from_json(json.c_str());
  8252. OBSDataArrayAutoRelease array =
  8253. obs_data_get_array(data, "array");
  8254. OBSSourceAutoRelease source = obs_get_source_by_uuid(
  8255. obs_data_get_string(data, "uuid"));
  8256. obs_source_restore_filters(source, array);
  8257. if (filters)
  8258. filters->UpdateSource(source);
  8259. };
  8260. const char *uuid = obs_source_get_uuid(source);
  8261. OBSDataAutoRelease undo_data = obs_data_create();
  8262. OBSDataAutoRelease redo_data = obs_data_create();
  8263. obs_data_set_array(undo_data, "array", undo_array);
  8264. obs_data_set_array(redo_data, "array", redo_array);
  8265. obs_data_set_string(undo_data, "uuid", uuid);
  8266. obs_data_set_string(redo_data, "uuid", uuid);
  8267. undo_s.add_action(text, undo_redo, undo_redo,
  8268. obs_data_get_json(undo_data),
  8269. obs_data_get_json(redo_data));
  8270. }
  8271. void OBSBasic::on_actionPasteFilters_triggered()
  8272. {
  8273. OBSSourceAutoRelease source =
  8274. obs_weak_source_get_source(copyFiltersSource);
  8275. OBSSceneItem sceneItem = GetCurrentSceneItem();
  8276. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  8277. if (source == dstSource)
  8278. return;
  8279. OBSDataArrayAutoRelease undo_array =
  8280. obs_source_backup_filters(dstSource);
  8281. obs_source_copy_filters(dstSource, source);
  8282. OBSDataArrayAutoRelease redo_array =
  8283. obs_source_backup_filters(dstSource);
  8284. const char *srcName = obs_source_get_name(source);
  8285. const char *dstName = obs_source_get_name(dstSource);
  8286. QString text =
  8287. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  8288. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  8289. redo_array);
  8290. }
  8291. static void ConfirmColor(SourceTree *sources, const QColor &color,
  8292. QModelIndexList selectedItems)
  8293. {
  8294. for (int x = 0; x < selectedItems.count(); x++) {
  8295. SourceTreeItem *treeItem =
  8296. sources->GetItemWidget(selectedItems[x].row());
  8297. treeItem->setStyleSheet("background: " +
  8298. color.name(QColor::HexArgb));
  8299. treeItem->style()->unpolish(treeItem);
  8300. treeItem->style()->polish(treeItem);
  8301. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  8302. OBSDataAutoRelease privData =
  8303. obs_sceneitem_get_private_settings(sceneItem);
  8304. obs_data_set_int(privData, "color-preset", 1);
  8305. obs_data_set_string(privData, "color",
  8306. QT_TO_UTF8(color.name(QColor::HexArgb)));
  8307. }
  8308. }
  8309. void OBSBasic::ColorChange()
  8310. {
  8311. QModelIndexList selectedItems =
  8312. ui->sources->selectionModel()->selectedIndexes();
  8313. QAction *action = qobject_cast<QAction *>(sender());
  8314. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  8315. if (selectedItems.count() == 0)
  8316. return;
  8317. if (colorButton) {
  8318. int preset = colorButton->property("bgColor").value<int>();
  8319. for (int x = 0; x < selectedItems.count(); x++) {
  8320. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  8321. selectedItems[x].row());
  8322. treeItem->setStyleSheet("");
  8323. treeItem->setProperty("bgColor", preset);
  8324. treeItem->style()->unpolish(treeItem);
  8325. treeItem->style()->polish(treeItem);
  8326. OBSSceneItem sceneItem =
  8327. ui->sources->Get(selectedItems[x].row());
  8328. OBSDataAutoRelease privData =
  8329. obs_sceneitem_get_private_settings(sceneItem);
  8330. obs_data_set_int(privData, "color-preset", preset + 1);
  8331. obs_data_set_string(privData, "color", "");
  8332. }
  8333. for (int i = 1; i < 9; i++) {
  8334. stringstream button;
  8335. button << "preset" << i;
  8336. QPushButton *cButton =
  8337. colorButton->parentWidget()
  8338. ->findChild<QPushButton *>(
  8339. button.str().c_str());
  8340. cButton->setStyleSheet("border: 1px solid black");
  8341. }
  8342. colorButton->setStyleSheet("border: 2px solid black");
  8343. } else if (action) {
  8344. int preset = action->property("bgColor").value<int>();
  8345. if (preset == 1) {
  8346. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  8347. SourceTreeItem *curTreeItem =
  8348. GetItemWidgetFromSceneItem(curSceneItem);
  8349. OBSDataAutoRelease curPrivData =
  8350. obs_sceneitem_get_private_settings(
  8351. curSceneItem);
  8352. int oldPreset =
  8353. obs_data_get_int(curPrivData, "color-preset");
  8354. const QString oldSheet = curTreeItem->styleSheet();
  8355. auto liveChangeColor = [=](const QColor &color) {
  8356. if (color.isValid()) {
  8357. curTreeItem->setStyleSheet(
  8358. "background: " +
  8359. color.name(QColor::HexArgb));
  8360. }
  8361. };
  8362. auto changedColor = [=](const QColor &color) {
  8363. if (color.isValid()) {
  8364. ConfirmColor(ui->sources, color,
  8365. selectedItems);
  8366. }
  8367. };
  8368. auto rejected = [=]() {
  8369. if (oldPreset == 1) {
  8370. curTreeItem->setStyleSheet(oldSheet);
  8371. curTreeItem->setProperty("bgColor", 0);
  8372. } else if (oldPreset == 0) {
  8373. curTreeItem->setStyleSheet(
  8374. "background: none");
  8375. curTreeItem->setProperty("bgColor", 0);
  8376. } else {
  8377. curTreeItem->setStyleSheet("");
  8378. curTreeItem->setProperty("bgColor",
  8379. oldPreset - 1);
  8380. }
  8381. curTreeItem->style()->unpolish(curTreeItem);
  8382. curTreeItem->style()->polish(curTreeItem);
  8383. };
  8384. QColorDialog::ColorDialogOptions options =
  8385. QColorDialog::ShowAlphaChannel;
  8386. const char *oldColor =
  8387. obs_data_get_string(curPrivData, "color");
  8388. const char *customColor = *oldColor != 0 ? oldColor
  8389. : "#55FF0000";
  8390. #ifdef __linux__
  8391. // TODO: Revisit hang on Ubuntu with native dialog
  8392. options |= QColorDialog::DontUseNativeDialog;
  8393. #endif
  8394. QColorDialog *colorDialog = new QColorDialog(this);
  8395. colorDialog->setOptions(options);
  8396. colorDialog->setCurrentColor(QColor(customColor));
  8397. connect(colorDialog, &QColorDialog::currentColorChanged,
  8398. liveChangeColor);
  8399. connect(colorDialog, &QColorDialog::colorSelected,
  8400. changedColor);
  8401. connect(colorDialog, &QColorDialog::rejected, rejected);
  8402. colorDialog->open();
  8403. } else {
  8404. for (int x = 0; x < selectedItems.count(); x++) {
  8405. SourceTreeItem *treeItem =
  8406. ui->sources->GetItemWidget(
  8407. selectedItems[x].row());
  8408. treeItem->setStyleSheet("background: none");
  8409. treeItem->setProperty("bgColor", preset);
  8410. treeItem->style()->unpolish(treeItem);
  8411. treeItem->style()->polish(treeItem);
  8412. OBSSceneItem sceneItem = ui->sources->Get(
  8413. selectedItems[x].row());
  8414. OBSDataAutoRelease privData =
  8415. obs_sceneitem_get_private_settings(
  8416. sceneItem);
  8417. obs_data_set_int(privData, "color-preset",
  8418. preset);
  8419. obs_data_set_string(privData, "color", "");
  8420. }
  8421. }
  8422. }
  8423. }
  8424. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  8425. {
  8426. int i = 0;
  8427. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  8428. OBSSceneItem item = ui->sources->Get(i);
  8429. int64_t id = obs_sceneitem_get_id(sceneItem);
  8430. while (treeItem && obs_sceneitem_get_id(item) != id) {
  8431. i++;
  8432. treeItem = ui->sources->GetItemWidget(i);
  8433. item = ui->sources->Get(i);
  8434. }
  8435. if (treeItem)
  8436. return treeItem;
  8437. return nullptr;
  8438. }
  8439. void OBSBasic::on_autoConfigure_triggered()
  8440. {
  8441. AutoConfig test(this);
  8442. test.setModal(true);
  8443. test.show();
  8444. test.exec();
  8445. }
  8446. void OBSBasic::on_stats_triggered()
  8447. {
  8448. if (!stats.isNull()) {
  8449. stats->show();
  8450. stats->raise();
  8451. return;
  8452. }
  8453. OBSBasicStats *statsDlg;
  8454. statsDlg = new OBSBasicStats(nullptr);
  8455. statsDlg->show();
  8456. stats = statsDlg;
  8457. }
  8458. void OBSBasic::on_actionShowAbout_triggered()
  8459. {
  8460. if (about)
  8461. about->close();
  8462. about = new OBSAbout(this);
  8463. about->show();
  8464. about->setAttribute(Qt::WA_DeleteOnClose, true);
  8465. }
  8466. void OBSBasic::ResizeOutputSizeOfSource()
  8467. {
  8468. if (obs_video_active())
  8469. return;
  8470. QMessageBox resize_output(this);
  8471. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  8472. QTStr("ResizeOutputSizeOfSource.Continue"));
  8473. QAbstractButton *Yes =
  8474. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  8475. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  8476. resize_output.setIcon(QMessageBox::Warning);
  8477. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  8478. resize_output.exec();
  8479. if (resize_output.clickedButton() != Yes)
  8480. return;
  8481. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  8482. int width = obs_source_get_width(source);
  8483. int height = obs_source_get_height(source);
  8484. config_set_uint(basicConfig, "Video", "BaseCX", width);
  8485. config_set_uint(basicConfig, "Video", "BaseCY", height);
  8486. config_set_uint(basicConfig, "Video", "OutputCX", width);
  8487. config_set_uint(basicConfig, "Video", "OutputCY", height);
  8488. ResetVideo();
  8489. ResetOutputs();
  8490. config_save_safe(basicConfig, "tmp", nullptr);
  8491. on_actionFitToScreen_triggered();
  8492. }
  8493. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  8494. {
  8495. // Prevent the object name from being changed
  8496. connect(dock, &QObject::objectNameChanged, this,
  8497. &OBSBasic::RepairOldExtraDockName);
  8498. #ifdef BROWSER_AVAILABLE
  8499. QAction *action = new QAction(dock->windowTitle(), ui->menuDocks);
  8500. if (!extraBrowserMenuDocksSeparator.isNull())
  8501. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8502. action);
  8503. else
  8504. ui->menuDocks->addAction(action);
  8505. #else
  8506. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  8507. #endif
  8508. action->setCheckable(true);
  8509. assignDockToggle(dock, action);
  8510. oldExtraDocks.push_back(dock);
  8511. oldExtraDockNames.push_back(dock->objectName());
  8512. bool lock = ui->lockDocks->isChecked();
  8513. QDockWidget::DockWidgetFeatures features =
  8514. lock ? QDockWidget::NoDockWidgetFeatures
  8515. : (QDockWidget::DockWidgetClosable |
  8516. QDockWidget::DockWidgetMovable |
  8517. QDockWidget::DockWidgetFloatable);
  8518. dock->setFeatures(features);
  8519. /* prune deleted docks */
  8520. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  8521. if (!oldExtraDocks[i]) {
  8522. oldExtraDocks.removeAt(i);
  8523. oldExtraDockNames.removeAt(i);
  8524. }
  8525. }
  8526. return action;
  8527. }
  8528. void OBSBasic::RepairOldExtraDockName()
  8529. {
  8530. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8531. int idx = oldExtraDocks.indexOf(dock);
  8532. QSignalBlocker block(dock);
  8533. if (idx == -1) {
  8534. blog(LOG_WARNING, "A dock got its object name changed");
  8535. return;
  8536. }
  8537. blog(LOG_WARNING, "The dock '%s' got its object name restored",
  8538. QT_TO_UTF8(oldExtraDockNames[idx]));
  8539. dock->setObjectName(oldExtraDockNames[idx]);
  8540. }
  8541. void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area,
  8542. bool extraBrowser)
  8543. {
  8544. if (dock->objectName().isEmpty())
  8545. return;
  8546. bool lock = ui->lockDocks->isChecked();
  8547. QDockWidget::DockWidgetFeatures features =
  8548. lock ? QDockWidget::NoDockWidgetFeatures
  8549. : (QDockWidget::DockWidgetClosable |
  8550. QDockWidget::DockWidgetMovable |
  8551. QDockWidget::DockWidgetFloatable);
  8552. setupDockAction(dock);
  8553. dock->setFeatures(features);
  8554. addDockWidget(area, dock);
  8555. #ifdef BROWSER_AVAILABLE
  8556. if (extraBrowser && extraBrowserMenuDocksSeparator.isNull())
  8557. extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator();
  8558. if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull())
  8559. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8560. dock->toggleViewAction());
  8561. else
  8562. ui->menuDocks->addAction(dock->toggleViewAction());
  8563. if (extraBrowser)
  8564. return;
  8565. #else
  8566. UNUSED_PARAMETER(extraBrowser);
  8567. ui->menuDocks->addAction(dock->toggleViewAction());
  8568. #endif
  8569. extraDockNames.push_back(dock->objectName());
  8570. extraDocks.push_back(QSharedPointer<QDockWidget>(dock));
  8571. }
  8572. void OBSBasic::RemoveDockWidget(const QString &name)
  8573. {
  8574. if (extraDockNames.contains(name)) {
  8575. int idx = extraDockNames.indexOf(name);
  8576. extraDockNames.removeAt(idx);
  8577. extraDocks[idx].clear();
  8578. extraDocks.removeAt(idx);
  8579. } else if (extraCustomDockNames.contains(name)) {
  8580. int idx = extraCustomDockNames.indexOf(name);
  8581. extraCustomDockNames.removeAt(idx);
  8582. removeDockWidget(extraCustomDocks[idx]);
  8583. extraCustomDocks.removeAt(idx);
  8584. }
  8585. }
  8586. bool OBSBasic::IsDockObjectNameUsed(const QString &name)
  8587. {
  8588. QStringList list;
  8589. list << "scenesDock"
  8590. << "sourcesDock"
  8591. << "mixerDock"
  8592. << "transitionsDock"
  8593. << "controlsDock"
  8594. << "statsDock";
  8595. list << oldExtraDockNames;
  8596. list << extraDockNames;
  8597. list << extraCustomDockNames;
  8598. return list.contains(name);
  8599. }
  8600. void OBSBasic::AddCustomDockWidget(QDockWidget *dock)
  8601. {
  8602. // Prevent the object name from being changed
  8603. connect(dock, &QObject::objectNameChanged, this,
  8604. &OBSBasic::RepairCustomExtraDockName);
  8605. bool lock = ui->lockDocks->isChecked();
  8606. QDockWidget::DockWidgetFeatures features =
  8607. lock ? QDockWidget::NoDockWidgetFeatures
  8608. : (QDockWidget::DockWidgetClosable |
  8609. QDockWidget::DockWidgetMovable |
  8610. QDockWidget::DockWidgetFloatable);
  8611. dock->setFeatures(features);
  8612. addDockWidget(Qt::RightDockWidgetArea, dock);
  8613. extraCustomDockNames.push_back(dock->objectName());
  8614. extraCustomDocks.push_back(dock);
  8615. }
  8616. void OBSBasic::RepairCustomExtraDockName()
  8617. {
  8618. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8619. int idx = extraCustomDocks.indexOf(dock);
  8620. QSignalBlocker block(dock);
  8621. if (idx == -1) {
  8622. blog(LOG_WARNING, "A custom dock got its object name changed");
  8623. return;
  8624. }
  8625. blog(LOG_WARNING, "The custom dock '%s' got its object name restored",
  8626. QT_TO_UTF8(extraCustomDockNames[idx]));
  8627. dock->setObjectName(extraCustomDockNames[idx]);
  8628. }
  8629. OBSBasic *OBSBasic::Get()
  8630. {
  8631. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  8632. }
  8633. bool OBSBasic::StreamingActive()
  8634. {
  8635. if (!outputHandler)
  8636. return false;
  8637. return outputHandler->StreamingActive();
  8638. }
  8639. bool OBSBasic::RecordingActive()
  8640. {
  8641. if (!outputHandler)
  8642. return false;
  8643. return outputHandler->RecordingActive();
  8644. }
  8645. bool OBSBasic::ReplayBufferActive()
  8646. {
  8647. if (!outputHandler)
  8648. return false;
  8649. return outputHandler->ReplayBufferActive();
  8650. }
  8651. bool OBSBasic::VirtualCamActive()
  8652. {
  8653. if (!outputHandler)
  8654. return false;
  8655. return outputHandler->VirtualCamActive();
  8656. }
  8657. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  8658. : QStyledItemDelegate(parent)
  8659. {
  8660. }
  8661. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8662. const QModelIndex &index) const
  8663. {
  8664. QStyledItemDelegate::setEditorData(editor, index);
  8665. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8666. if (lineEdit)
  8667. lineEdit->selectAll();
  8668. }
  8669. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8670. {
  8671. if (event->type() == QEvent::KeyPress) {
  8672. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8673. if (keyEvent->key() == Qt::Key_Escape) {
  8674. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8675. if (lineEdit)
  8676. lineEdit->undo();
  8677. }
  8678. }
  8679. return QStyledItemDelegate::eventFilter(editor, event);
  8680. }
  8681. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8682. {
  8683. if (!error.isEmpty())
  8684. return;
  8685. patronJson = QT_TO_UTF8(text);
  8686. }
  8687. void OBSBasic::PauseRecording()
  8688. {
  8689. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8690. os_atomic_load_bool(&recording_paused))
  8691. return;
  8692. obs_output_t *output = outputHandler->fileOutput;
  8693. if (obs_output_pause(output, true)) {
  8694. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  8695. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  8696. pause->blockSignals(true);
  8697. pause->setChecked(true);
  8698. pause->blockSignals(false);
  8699. ui->statusbar->RecordingPaused();
  8700. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8701. if (trayIcon && trayIcon->isVisible()) {
  8702. #ifdef __APPLE__
  8703. QIcon trayIconFile =
  8704. QIcon(":/res/images/obs_paused_macos.svg");
  8705. trayIconFile.setIsMask(true);
  8706. #else
  8707. QIcon trayIconFile =
  8708. QIcon(":/res/images/obs_paused.png");
  8709. #endif
  8710. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8711. trayIconFile));
  8712. }
  8713. os_atomic_set_bool(&recording_paused, true);
  8714. auto replay = replayBufferButton ? replayBufferButton->second()
  8715. : nullptr;
  8716. if (replay)
  8717. replay->setEnabled(false);
  8718. if (api)
  8719. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8720. if (os_atomic_load_bool(&replaybuf_active))
  8721. ShowReplayBufferPauseWarning();
  8722. }
  8723. }
  8724. void OBSBasic::UnpauseRecording()
  8725. {
  8726. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8727. !os_atomic_load_bool(&recording_paused))
  8728. return;
  8729. obs_output_t *output = outputHandler->fileOutput;
  8730. if (obs_output_pause(output, false)) {
  8731. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8732. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8733. pause->blockSignals(true);
  8734. pause->setChecked(false);
  8735. pause->blockSignals(false);
  8736. ui->statusbar->RecordingUnpaused();
  8737. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8738. if (trayIcon && trayIcon->isVisible()) {
  8739. #ifdef __APPLE__
  8740. QIcon trayIconFile =
  8741. QIcon(":/res/images/tray_active_macos.svg");
  8742. trayIconFile.setIsMask(true);
  8743. #else
  8744. QIcon trayIconFile =
  8745. QIcon(":/res/images/tray_active.png");
  8746. #endif
  8747. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8748. trayIconFile));
  8749. }
  8750. os_atomic_set_bool(&recording_paused, false);
  8751. auto replay = replayBufferButton ? replayBufferButton->second()
  8752. : nullptr;
  8753. if (replay)
  8754. replay->setEnabled(true);
  8755. if (api)
  8756. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8757. }
  8758. }
  8759. void OBSBasic::PauseToggled()
  8760. {
  8761. if (!pause || !outputHandler || !outputHandler->fileOutput)
  8762. return;
  8763. obs_output_t *output = outputHandler->fileOutput;
  8764. bool enable = !obs_output_paused(output);
  8765. if (enable)
  8766. PauseRecording();
  8767. else
  8768. UnpauseRecording();
  8769. }
  8770. void OBSBasic::UpdatePause(bool activate)
  8771. {
  8772. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  8773. pause.reset();
  8774. return;
  8775. }
  8776. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8777. bool adv = astrcmpi(mode, "Advanced") == 0;
  8778. bool shared;
  8779. if (adv) {
  8780. const char *recType =
  8781. config_get_string(basicConfig, "AdvOut", "RecType");
  8782. if (astrcmpi(recType, "FFmpeg") == 0) {
  8783. shared = config_get_bool(basicConfig, "AdvOut",
  8784. "FFOutputToFile");
  8785. } else {
  8786. const char *recordEncoder = config_get_string(
  8787. basicConfig, "AdvOut", "RecEncoder");
  8788. shared = astrcmpi(recordEncoder, "none") == 0;
  8789. }
  8790. } else {
  8791. const char *quality = config_get_string(
  8792. basicConfig, "SimpleOutput", "RecQuality");
  8793. shared = strcmp(quality, "Stream") == 0;
  8794. }
  8795. if (!shared) {
  8796. pause.reset(new QPushButton());
  8797. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8798. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8799. pause->setCheckable(true);
  8800. pause->setChecked(false);
  8801. pause->setProperty("themeID",
  8802. QVariant(QStringLiteral("pauseIconSmall")));
  8803. QSizePolicy sp;
  8804. sp.setHeightForWidth(true);
  8805. pause->setSizePolicy(sp);
  8806. connect(pause.data(), &QAbstractButton::clicked, this,
  8807. &OBSBasic::PauseToggled);
  8808. ui->recordingLayout->addWidget(pause.data());
  8809. } else {
  8810. pause.reset();
  8811. }
  8812. }
  8813. void OBSBasic::UpdateReplayBuffer(bool activate)
  8814. {
  8815. if (!activate || !outputHandler ||
  8816. !outputHandler->ReplayBufferActive()) {
  8817. replayBufferButton->removeIcon();
  8818. return;
  8819. }
  8820. replayBufferButton->addIcon(QTStr("Basic.Main.SaveReplay"),
  8821. QStringLiteral("replayIconSmall"),
  8822. &OBSBasic::ReplayBufferSave);
  8823. }
  8824. #define MBYTE (1024ULL * 1024ULL)
  8825. #define MBYTES_LEFT_STOP_REC 50ULL
  8826. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8827. const char *OBSBasic::GetCurrentOutputPath()
  8828. {
  8829. const char *path = nullptr;
  8830. const char *mode = config_get_string(Config(), "Output", "Mode");
  8831. if (strcmp(mode, "Advanced") == 0) {
  8832. const char *advanced_mode =
  8833. config_get_string(Config(), "AdvOut", "RecType");
  8834. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8835. path = config_get_string(Config(), "AdvOut",
  8836. "FFFilePath");
  8837. } else {
  8838. path = config_get_string(Config(), "AdvOut",
  8839. "RecFilePath");
  8840. }
  8841. } else {
  8842. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8843. }
  8844. return path;
  8845. }
  8846. void OBSBasic::OutputPathInvalidMessage()
  8847. {
  8848. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8849. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8850. QTStr("Output.BadPath.Text"));
  8851. }
  8852. bool OBSBasic::OutputPathValid()
  8853. {
  8854. const char *mode = config_get_string(Config(), "Output", "Mode");
  8855. if (strcmp(mode, "Advanced") == 0) {
  8856. const char *advanced_mode =
  8857. config_get_string(Config(), "AdvOut", "RecType");
  8858. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8859. bool is_local = config_get_bool(Config(), "AdvOut",
  8860. "FFOutputToFile");
  8861. if (!is_local)
  8862. return true;
  8863. }
  8864. }
  8865. const char *path = GetCurrentOutputPath();
  8866. return path && *path && QDir(path).exists();
  8867. }
  8868. void OBSBasic::DiskSpaceMessage()
  8869. {
  8870. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8871. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8872. QTStr("Output.RecordNoSpace.Msg"));
  8873. }
  8874. bool OBSBasic::LowDiskSpace()
  8875. {
  8876. const char *path;
  8877. path = GetCurrentOutputPath();
  8878. if (!path)
  8879. return false;
  8880. uint64_t num_bytes = os_get_free_disk_space(path);
  8881. if (num_bytes < (MAX_BYTES_LEFT))
  8882. return true;
  8883. else
  8884. return false;
  8885. }
  8886. void OBSBasic::CheckDiskSpaceRemaining()
  8887. {
  8888. if (LowDiskSpace()) {
  8889. StopRecording();
  8890. StopReplayBuffer();
  8891. DiskSpaceMessage();
  8892. }
  8893. }
  8894. void OBSBasic::ResetStatsHotkey()
  8895. {
  8896. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8897. foreach(OBSBasicStats * s, list) s->Reset();
  8898. }
  8899. void OBSBasic::on_OBSBasic_customContextMenuRequested(const QPoint &pos)
  8900. {
  8901. QWidget *widget = childAt(pos);
  8902. const char *className = nullptr;
  8903. QString objName;
  8904. if (widget != nullptr) {
  8905. className = widget->metaObject()->className();
  8906. objName = widget->objectName();
  8907. }
  8908. QPoint globalPos = mapToGlobal(pos);
  8909. if (className && strstr(className, "Dock") != nullptr &&
  8910. !objName.isEmpty()) {
  8911. if (objName.compare("scenesDock") == 0) {
  8912. ui->scenes->customContextMenuRequested(globalPos);
  8913. } else if (objName.compare("sourcesDock") == 0) {
  8914. ui->sources->customContextMenuRequested(globalPos);
  8915. } else if (objName.compare("mixerDock") == 0) {
  8916. StackedMixerAreaContextMenuRequested();
  8917. }
  8918. } else if (!className) {
  8919. ui->menuDocks->exec(globalPos);
  8920. }
  8921. }
  8922. void OBSBasic::UpdateProjectorHideCursor()
  8923. {
  8924. for (size_t i = 0; i < projectors.size(); i++)
  8925. projectors[i]->SetHideCursor();
  8926. }
  8927. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8928. {
  8929. for (size_t i = 0; i < projectors.size(); i++)
  8930. SetAlwaysOnTop(projectors[i], top);
  8931. }
  8932. void OBSBasic::ResetProjectors()
  8933. {
  8934. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8935. ClearProjectors();
  8936. LoadSavedProjectors(savedProjectorList);
  8937. OpenSavedProjectors();
  8938. }
  8939. void OBSBasic::on_sourcePropertiesButton_clicked()
  8940. {
  8941. on_actionSourceProperties_triggered();
  8942. }
  8943. void OBSBasic::on_sourceFiltersButton_clicked()
  8944. {
  8945. OpenFilters();
  8946. }
  8947. void OBSBasic::on_actionSceneFilters_triggered()
  8948. {
  8949. OBSSource sceneSource = GetCurrentSceneSource();
  8950. if (sceneSource)
  8951. OpenFilters(sceneSource);
  8952. }
  8953. void OBSBasic::on_sourceInteractButton_clicked()
  8954. {
  8955. on_actionInteract_triggered();
  8956. }
  8957. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8958. {
  8959. ui->statusbar->clearMessage();
  8960. ui->statusbar->showMessage(message, 10000);
  8961. }
  8962. void OBSBasic::UpdatePreviewSafeAreas()
  8963. {
  8964. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8965. "ShowSafeAreas");
  8966. }
  8967. void OBSBasic::UpdatePreviewOverflowSettings()
  8968. {
  8969. bool hidden = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8970. "OverflowHidden");
  8971. bool select = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8972. "OverflowSelectionHidden");
  8973. bool always = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8974. "OverflowAlwaysVisible");
  8975. ui->preview->SetOverflowHidden(hidden);
  8976. ui->preview->SetOverflowSelectionHidden(select);
  8977. ui->preview->SetOverflowAlwaysVisible(always);
  8978. }
  8979. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8980. {
  8981. if (!SetDisplayAffinitySupported())
  8982. return;
  8983. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8984. "BasicWindow",
  8985. "HideOBSWindowsFromCapture");
  8986. // Don't hide projectors, those are designed to be visible / captured
  8987. if (window->property("isOBSProjectorWindow") == true)
  8988. return;
  8989. #ifdef _WIN32
  8990. HWND hwnd = (HWND)window->winId();
  8991. DWORD curAffinity;
  8992. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  8993. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  8994. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  8995. else if (!hideFromCapture && curAffinity != WDA_NONE)
  8996. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  8997. }
  8998. #else
  8999. // TODO: Implement for other platforms if possible. Don't forget to
  9000. // implement SetDisplayAffinitySupported too!
  9001. UNUSED_PARAMETER(hideFromCapture);
  9002. #endif
  9003. }
  9004. static inline QColor color_from_int(long long val)
  9005. {
  9006. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  9007. (val >> 24) & 0xff);
  9008. }
  9009. QColor OBSBasic::GetSelectionColor() const
  9010. {
  9011. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9012. "OverrideColors")) {
  9013. return color_from_int(config_get_int(
  9014. GetGlobalConfig(), "Accessibility", "SelectRed"));
  9015. } else {
  9016. return QColor::fromRgb(255, 0, 0);
  9017. }
  9018. }
  9019. QColor OBSBasic::GetCropColor() const
  9020. {
  9021. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9022. "OverrideColors")) {
  9023. return color_from_int(config_get_int(
  9024. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  9025. } else {
  9026. return QColor::fromRgb(0, 255, 0);
  9027. }
  9028. }
  9029. QColor OBSBasic::GetHoverColor() const
  9030. {
  9031. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9032. "OverrideColors")) {
  9033. return color_from_int(config_get_int(
  9034. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  9035. } else {
  9036. return QColor::fromRgb(0, 127, 255);
  9037. }
  9038. }
  9039. void OBSBasic::UpdatePreviewSpacingHelpers()
  9040. {
  9041. drawSpacingHelpers = config_get_bool(
  9042. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  9043. }
  9044. float OBSBasic::GetDevicePixelRatio()
  9045. {
  9046. return dpi;
  9047. }
  9048. void OBSBasic::ThemeChanged()
  9049. {
  9050. /* Since volume/media sliders are using QProxyStyle, they are not
  9051. * updated when themes are changed, so re-initialize them. */
  9052. vector<OBSSource> sources;
  9053. for (size_t i = 0; i != volumes.size(); i++)
  9054. sources.emplace_back(volumes[i]->GetSource());
  9055. ClearVolumeControls();
  9056. for (const auto &source : sources)
  9057. ActivateAudioSource(source);
  9058. UpdateContextBar(true);
  9059. if (api)
  9060. api->on_event(OBS_FRONTEND_EVENT_THEME_CHANGED);
  9061. }