window-basic-main.cpp 273 KB

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