window-basic-main.cpp 303 KB

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