window-basic-main.cpp 282 KB

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