window-basic-main.cpp 281 KB

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