window-basic-main.cpp 287 KB

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