window-basic-main.cpp 287 KB

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