window-basic-main.cpp 301 KB

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