window-basic-main.cpp 302 KB

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