window-basic-main.cpp 281 KB

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