1
0

window-basic-main.cpp 292 KB

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