window-basic-main.cpp 277 KB

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