window-basic-main.cpp 281 KB

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