window-basic-main.cpp 298 KB

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