window-basic-main.cpp 279 KB

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