window-basic-main.cpp 301 KB

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