window-basic-main.cpp 275 KB

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