window-basic-main.cpp 301 KB

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