window-basic-main.cpp 280 KB

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