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