window-basic-main.cpp 304 KB

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