window-basic-main.cpp 272 KB

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