window-basic-main.cpp 274 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086
  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 save_audio_source(int channel, obs_data_t *save)
  3985. {
  3986. OBSSourceAutoRelease source = obs_get_output_source(channel);
  3987. if (!source)
  3988. return;
  3989. OBSDataAutoRelease obj = obs_data_create();
  3990. obs_data_set_double(obj, "vol", obs_source_get_volume(source));
  3991. obs_data_set_double(obj, "balance",
  3992. obs_source_get_balance_value(source));
  3993. obs_data_set_double(obj, "mixers", obs_source_get_audio_mixers(source));
  3994. obs_data_set_double(obj, "sync", obs_source_get_sync_offset(source));
  3995. obs_data_set_double(obj, "flags", obs_source_get_flags(source));
  3996. obs_data_set_obj(save, std::to_string(channel).c_str(), obj);
  3997. }
  3998. void load_audio_source(int channel, obs_data_t *data)
  3999. {
  4000. OBSSourceAutoRelease source = obs_get_output_source(channel);
  4001. if (!source)
  4002. return;
  4003. OBSDataAutoRelease save =
  4004. obs_data_get_obj(data, std::to_string(channel).c_str());
  4005. obs_source_set_volume(source, obs_data_get_double(save, "vol"));
  4006. obs_source_set_balance_value(source,
  4007. obs_data_get_double(save, "balance"));
  4008. obs_source_set_audio_mixers(source,
  4009. obs_data_get_double(save, "mixers"));
  4010. obs_source_set_sync_offset(source, obs_data_get_double(save, "sync"));
  4011. obs_source_set_flags(source, obs_data_get_double(save, "flags"));
  4012. }
  4013. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4014. {
  4015. if (advAudioWindow != nullptr) {
  4016. advAudioWindow->raise();
  4017. return;
  4018. }
  4019. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4020. "BasicWindow", "ShowSourceIcons");
  4021. advAudioWindow = new OBSBasicAdvAudio(this);
  4022. advAudioWindow->show();
  4023. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4024. advAudioWindow->SetIconsVisible(iconsVisible);
  4025. }
  4026. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4027. QListWidgetItem *prev)
  4028. {
  4029. obs_source_t *source = NULL;
  4030. if (current) {
  4031. obs_scene_t *scene;
  4032. scene = GetOBSRef<OBSScene>(current);
  4033. source = obs_scene_get_source(scene);
  4034. currentScene = scene;
  4035. } else {
  4036. currentScene = NULL;
  4037. }
  4038. SetCurrentScene(source);
  4039. if (api)
  4040. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4041. UpdateContextBar();
  4042. UNUSED_PARAMETER(prev);
  4043. }
  4044. void OBSBasic::EditSceneName()
  4045. {
  4046. ui->scenesDock->removeAction(renameScene);
  4047. QListWidgetItem *item = ui->scenes->currentItem();
  4048. Qt::ItemFlags flags = item->flags();
  4049. item->setFlags(flags | Qt::ItemIsEditable);
  4050. ui->scenes->editItem(item);
  4051. item->setFlags(flags);
  4052. }
  4053. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  4054. const char *slot)
  4055. {
  4056. QAction *action;
  4057. QList<QScreen *> screens = QGuiApplication::screens();
  4058. for (int i = 0; i < screens.size(); i++) {
  4059. QScreen *screen = screens[i];
  4060. QRect screenGeometry = screen->geometry();
  4061. qreal ratio = screen->devicePixelRatio();
  4062. QString name = "";
  4063. #ifdef _WIN32
  4064. QTextStream fullname(&name);
  4065. fullname << GetMonitorName(screen->name());
  4066. fullname << " (";
  4067. fullname << (i + 1);
  4068. fullname << ")";
  4069. #elif defined(__APPLE__)
  4070. name = screen->name();
  4071. #else
  4072. name = screen->model().simplified();
  4073. if (name.length() > 1 && name.endsWith("-"))
  4074. name.chop(1);
  4075. #endif
  4076. name = name.simplified();
  4077. if (name.length() == 0) {
  4078. name = QString("%1 %2")
  4079. .arg(QTStr("Display"))
  4080. .arg(QString::number(i + 1));
  4081. }
  4082. QString str =
  4083. QString("%1: %2x%3 @ %4,%5")
  4084. .arg(name,
  4085. QString::number(screenGeometry.width() *
  4086. ratio),
  4087. QString::number(screenGeometry.height() *
  4088. ratio),
  4089. QString::number(screenGeometry.x()),
  4090. QString::number(screenGeometry.y()));
  4091. action = parent->addAction(str, target, slot);
  4092. action->setProperty("monitor", i);
  4093. }
  4094. }
  4095. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4096. {
  4097. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4098. QMenu popup(this);
  4099. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4100. popup.addAction(QTStr("Add"), this,
  4101. SLOT(on_actionAddScene_triggered()));
  4102. if (item) {
  4103. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4104. copyFilters->setEnabled(false);
  4105. connect(copyFilters, SIGNAL(triggered()), this,
  4106. SLOT(SceneCopyFilters()));
  4107. QAction *pasteFilters =
  4108. new QAction(QTStr("Paste.Filters"), this);
  4109. pasteFilters->setEnabled(
  4110. !obs_weak_source_expired(copyFiltersSource));
  4111. connect(pasteFilters, SIGNAL(triggered()), this,
  4112. SLOT(ScenePasteFilters()));
  4113. popup.addSeparator();
  4114. popup.addAction(QTStr("Duplicate"), this,
  4115. SLOT(DuplicateSelectedScene()));
  4116. popup.addAction(copyFilters);
  4117. popup.addAction(pasteFilters);
  4118. popup.addSeparator();
  4119. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  4120. popup.addAction(QTStr("Remove"), this,
  4121. SLOT(RemoveSelectedScene()));
  4122. popup.addSeparator();
  4123. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4124. SLOT(on_actionSceneUp_triggered()));
  4125. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4126. this, SLOT(on_actionSceneDown_triggered()));
  4127. order.addSeparator();
  4128. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4129. this, SLOT(MoveSceneToTop()));
  4130. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4131. this, SLOT(MoveSceneToBottom()));
  4132. popup.addMenu(&order);
  4133. popup.addSeparator();
  4134. delete sceneProjectorMenu;
  4135. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4136. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4137. SLOT(OpenSceneProjector()));
  4138. popup.addMenu(sceneProjectorMenu);
  4139. QAction *sceneWindow = popup.addAction(
  4140. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  4141. popup.addAction(sceneWindow);
  4142. popup.addAction(QTStr("Screenshot.Scene"), this,
  4143. SLOT(ScreenshotScene()));
  4144. popup.addSeparator();
  4145. popup.addAction(QTStr("Filters"), this,
  4146. SLOT(OpenSceneFilters()));
  4147. popup.addSeparator();
  4148. delete perSceneTransitionMenu;
  4149. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4150. popup.addMenu(perSceneTransitionMenu);
  4151. /* ---------------------- */
  4152. QAction *multiviewAction =
  4153. popup.addAction(QTStr("ShowInMultiview"));
  4154. OBSSource source = GetCurrentSceneSource();
  4155. OBSDataAutoRelease data =
  4156. obs_source_get_private_settings(source);
  4157. obs_data_set_default_bool(data, "show_in_multiview", true);
  4158. bool show = obs_data_get_bool(data, "show_in_multiview");
  4159. multiviewAction->setCheckable(true);
  4160. multiviewAction->setChecked(show);
  4161. auto showInMultiview = [](OBSData data) {
  4162. bool show =
  4163. obs_data_get_bool(data, "show_in_multiview");
  4164. obs_data_set_bool(data, "show_in_multiview", !show);
  4165. OBSProjector::UpdateMultiviewProjectors();
  4166. };
  4167. connect(multiviewAction, &QAction::triggered,
  4168. std::bind(showInMultiview, data.Get()));
  4169. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4170. }
  4171. popup.addSeparator();
  4172. bool grid = ui->scenes->GetGridMode();
  4173. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4174. : QTStr("Basic.Main.GridMode"),
  4175. this);
  4176. connect(gridAction, SIGNAL(triggered()), this,
  4177. SLOT(GridActionClicked()));
  4178. popup.addAction(gridAction);
  4179. popup.exec(QCursor::pos());
  4180. }
  4181. void OBSBasic::GridActionClicked()
  4182. {
  4183. bool gridMode = !ui->scenes->GetGridMode();
  4184. ui->scenes->SetGridMode(gridMode);
  4185. }
  4186. void OBSBasic::on_actionAddScene_triggered()
  4187. {
  4188. string name;
  4189. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4190. int i = 2;
  4191. QString placeHolderText = format.arg(i);
  4192. OBSSourceAutoRelease source = nullptr;
  4193. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4194. placeHolderText = format.arg(++i);
  4195. }
  4196. bool accepted = NameDialog::AskForName(
  4197. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4198. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4199. if (accepted) {
  4200. if (name.empty()) {
  4201. OBSMessageBox::warning(this,
  4202. QTStr("NoNameEntered.Title"),
  4203. QTStr("NoNameEntered.Text"));
  4204. on_actionAddScene_triggered();
  4205. return;
  4206. }
  4207. OBSSourceAutoRelease source =
  4208. obs_get_source_by_name(name.c_str());
  4209. if (source) {
  4210. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4211. QTStr("NameExists.Text"));
  4212. on_actionAddScene_triggered();
  4213. return;
  4214. }
  4215. auto undo_fn = [](const std::string &data) {
  4216. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4217. if (t) {
  4218. obs_source_release(t);
  4219. obs_source_remove(t);
  4220. }
  4221. };
  4222. auto redo_fn = [this](const std::string &data) {
  4223. OBSSceneAutoRelease scene =
  4224. obs_scene_create(data.c_str());
  4225. obs_source_t *source = obs_scene_get_source(scene);
  4226. SetCurrentScene(source, true);
  4227. };
  4228. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4229. undo_fn, redo_fn, name, name);
  4230. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4231. obs_source_t *scene_source = obs_scene_get_source(scene);
  4232. SetCurrentScene(scene_source);
  4233. }
  4234. }
  4235. void OBSBasic::on_actionRemoveScene_triggered()
  4236. {
  4237. RemoveSelectedScene();
  4238. }
  4239. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4240. {
  4241. int idx = ui->scenes->currentRow();
  4242. if (idx == -1 || idx == invalidIdx)
  4243. return;
  4244. ui->scenes->blockSignals(true);
  4245. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4246. if (!relative)
  4247. idx = 0;
  4248. ui->scenes->insertItem(idx + offset, item);
  4249. ui->scenes->setCurrentRow(idx + offset);
  4250. item->setSelected(true);
  4251. currentScene = GetOBSRef<OBSScene>(item).Get();
  4252. ui->scenes->blockSignals(false);
  4253. OBSProjector::UpdateMultiviewProjectors();
  4254. }
  4255. void OBSBasic::on_actionSceneUp_triggered()
  4256. {
  4257. ChangeSceneIndex(true, -1, 0);
  4258. }
  4259. void OBSBasic::on_actionSceneDown_triggered()
  4260. {
  4261. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4262. }
  4263. void OBSBasic::MoveSceneToTop()
  4264. {
  4265. ChangeSceneIndex(false, 0, 0);
  4266. }
  4267. void OBSBasic::MoveSceneToBottom()
  4268. {
  4269. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4270. ui->scenes->count() - 1);
  4271. }
  4272. void OBSBasic::EditSceneItemName()
  4273. {
  4274. int idx = GetTopSelectedSourceItem();
  4275. ui->sources->Edit(idx);
  4276. }
  4277. void OBSBasic::SetDeinterlacingMode()
  4278. {
  4279. QAction *action = reinterpret_cast<QAction *>(sender());
  4280. obs_deinterlace_mode mode =
  4281. (obs_deinterlace_mode)action->property("mode").toInt();
  4282. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4283. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4284. obs_source_set_deinterlace_mode(source, mode);
  4285. }
  4286. void OBSBasic::SetDeinterlacingOrder()
  4287. {
  4288. QAction *action = reinterpret_cast<QAction *>(sender());
  4289. obs_deinterlace_field_order order =
  4290. (obs_deinterlace_field_order)action->property("order").toInt();
  4291. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4292. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4293. obs_source_set_deinterlace_field_order(source, order);
  4294. }
  4295. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4296. {
  4297. obs_deinterlace_mode deinterlaceMode =
  4298. obs_source_get_deinterlace_mode(source);
  4299. obs_deinterlace_field_order deinterlaceOrder =
  4300. obs_source_get_deinterlace_field_order(source);
  4301. QAction *action;
  4302. #define ADD_MODE(name, mode) \
  4303. action = menu->addAction(QTStr("" name), this, \
  4304. SLOT(SetDeinterlacingMode())); \
  4305. action->setProperty("mode", (int)mode); \
  4306. action->setCheckable(true); \
  4307. action->setChecked(deinterlaceMode == mode);
  4308. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4309. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4310. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4311. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4312. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4313. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4314. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4315. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4316. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4317. #undef ADD_MODE
  4318. menu->addSeparator();
  4319. #define ADD_ORDER(name, order) \
  4320. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4321. SLOT(SetDeinterlacingOrder())); \
  4322. action->setProperty("order", (int)order); \
  4323. action->setCheckable(true); \
  4324. action->setChecked(deinterlaceOrder == order);
  4325. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4326. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4327. #undef ADD_ORDER
  4328. return menu;
  4329. }
  4330. void OBSBasic::SetScaleFilter()
  4331. {
  4332. QAction *action = reinterpret_cast<QAction *>(sender());
  4333. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4334. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4335. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4336. }
  4337. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4338. {
  4339. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4340. QAction *action;
  4341. #define ADD_MODE(name, mode) \
  4342. action = \
  4343. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  4344. action->setProperty("mode", (int)mode); \
  4345. action->setCheckable(true); \
  4346. action->setChecked(scaleFilter == mode);
  4347. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4348. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4349. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4350. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4351. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4352. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4353. #undef ADD_MODE
  4354. return menu;
  4355. }
  4356. void OBSBasic::SetBlendingMethod()
  4357. {
  4358. QAction *action = reinterpret_cast<QAction *>(sender());
  4359. obs_blending_method method =
  4360. (obs_blending_method)action->property("method").toInt();
  4361. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4362. obs_sceneitem_set_blending_method(sceneItem, method);
  4363. }
  4364. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4365. {
  4366. obs_blending_method blendingMethod =
  4367. obs_sceneitem_get_blending_method(item);
  4368. QAction *action;
  4369. #define ADD_MODE(name, method) \
  4370. action = menu->addAction(QTStr("" name), this, \
  4371. SLOT(SetBlendingMethod())); \
  4372. action->setProperty("method", (int)method); \
  4373. action->setCheckable(true); \
  4374. action->setChecked(blendingMethod == method);
  4375. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4376. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4377. #undef ADD_MODE
  4378. return menu;
  4379. }
  4380. void OBSBasic::SetBlendingMode()
  4381. {
  4382. QAction *action = reinterpret_cast<QAction *>(sender());
  4383. obs_blending_type mode =
  4384. (obs_blending_type)action->property("mode").toInt();
  4385. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4386. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4387. }
  4388. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4389. {
  4390. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4391. QAction *action;
  4392. #define ADD_MODE(name, mode) \
  4393. action = menu->addAction(QTStr("" name), this, \
  4394. SLOT(SetBlendingMode())); \
  4395. action->setProperty("mode", (int)mode); \
  4396. action->setCheckable(true); \
  4397. action->setChecked(blendingMode == mode);
  4398. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4399. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4400. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4401. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4402. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4403. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4404. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4405. #undef ADD_MODE
  4406. return menu;
  4407. }
  4408. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4409. QWidgetAction *widgetAction,
  4410. ColorSelect *select,
  4411. obs_sceneitem_t *item)
  4412. {
  4413. QAction *action;
  4414. menu->setStyleSheet(QString(
  4415. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4416. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4417. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4418. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4419. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4420. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4421. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4422. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4423. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4424. obs_data_release(privData);
  4425. obs_data_set_default_int(privData, "color-preset", 0);
  4426. int preset = obs_data_get_int(privData, "color-preset");
  4427. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  4428. action->setCheckable(true);
  4429. action->setProperty("bgColor", 0);
  4430. action->setChecked(preset == 0);
  4431. action = menu->addAction(QTStr("CustomColor"), this,
  4432. +SLOT(ColorChange()));
  4433. action->setCheckable(true);
  4434. action->setProperty("bgColor", 1);
  4435. action->setChecked(preset == 1);
  4436. menu->addSeparator();
  4437. widgetAction->setDefaultWidget(select);
  4438. for (int i = 1; i < 9; i++) {
  4439. stringstream button;
  4440. button << "preset" << i;
  4441. QPushButton *colorButton =
  4442. select->findChild<QPushButton *>(button.str().c_str());
  4443. if (preset == i + 1)
  4444. colorButton->setStyleSheet("border: 2px solid black");
  4445. colorButton->setProperty("bgColor", i);
  4446. select->connect(colorButton, SIGNAL(released()), this,
  4447. SLOT(ColorChange()));
  4448. }
  4449. menu->addAction(widgetAction);
  4450. return menu;
  4451. }
  4452. ColorSelect::ColorSelect(QWidget *parent)
  4453. : QWidget(parent), ui(new Ui::ColorSelect)
  4454. {
  4455. ui->setupUi(this);
  4456. }
  4457. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4458. {
  4459. QMenu popup(this);
  4460. delete previewProjectorSource;
  4461. delete sourceProjector;
  4462. delete scaleFilteringMenu;
  4463. delete blendingMethodMenu;
  4464. delete blendingModeMenu;
  4465. delete colorMenu;
  4466. delete colorWidgetAction;
  4467. delete colorSelect;
  4468. delete deinterlaceMenu;
  4469. if (preview) {
  4470. QAction *action = popup.addAction(
  4471. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4472. SLOT(TogglePreview()));
  4473. action->setCheckable(true);
  4474. action->setChecked(
  4475. obs_display_enabled(ui->preview->GetDisplay()));
  4476. if (IsPreviewProgramMode())
  4477. action->setEnabled(false);
  4478. popup.addAction(ui->actionLockPreview);
  4479. popup.addMenu(ui->scalingMenu);
  4480. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4481. AddProjectorMenuMonitors(previewProjectorSource, this,
  4482. SLOT(OpenPreviewProjector()));
  4483. popup.addMenu(previewProjectorSource);
  4484. QAction *previewWindow =
  4485. popup.addAction(QTStr("PreviewWindow"), this,
  4486. SLOT(OpenPreviewWindow()));
  4487. popup.addAction(previewWindow);
  4488. popup.addAction(QTStr("Screenshot.Preview"), this,
  4489. SLOT(ScreenshotScene()));
  4490. popup.addSeparator();
  4491. }
  4492. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4493. if (addSourceMenu)
  4494. popup.addMenu(addSourceMenu);
  4495. if (ui->sources->MultipleBaseSelected()) {
  4496. popup.addSeparator();
  4497. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4498. SLOT(GroupSelectedItems()));
  4499. } else if (ui->sources->GroupsSelected()) {
  4500. popup.addSeparator();
  4501. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4502. SLOT(UngroupSelectedGroups()));
  4503. }
  4504. popup.addSeparator();
  4505. popup.addAction(ui->actionCopySource);
  4506. popup.addAction(ui->actionPasteRef);
  4507. popup.addAction(ui->actionPasteDup);
  4508. popup.addSeparator();
  4509. popup.addSeparator();
  4510. popup.addAction(ui->actionCopyFilters);
  4511. popup.addAction(ui->actionPasteFilters);
  4512. popup.addSeparator();
  4513. if (idx != -1) {
  4514. if (addSourceMenu)
  4515. popup.addSeparator();
  4516. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4517. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4518. uint32_t flags = obs_source_get_output_flags(source);
  4519. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4520. OBS_SOURCE_ASYNC_VIDEO;
  4521. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4522. colorMenu = new QMenu(QTStr("ChangeBG"));
  4523. colorWidgetAction = new QWidgetAction(colorMenu);
  4524. colorSelect = new ColorSelect(colorMenu);
  4525. popup.addMenu(AddBackgroundColorMenu(
  4526. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4527. popup.addAction(QTStr("Rename"), this,
  4528. SLOT(EditSceneItemName()));
  4529. popup.addAction(QTStr("Remove"), this,
  4530. SLOT(on_actionRemoveSource_triggered()));
  4531. popup.addSeparator();
  4532. popup.addMenu(ui->orderMenu);
  4533. popup.addMenu(ui->transformMenu);
  4534. popup.addSeparator();
  4535. if (hasAudio) {
  4536. QAction *actionHideMixer =
  4537. popup.addAction(QTStr("HideMixer"), this,
  4538. SLOT(ToggleHideMixer()));
  4539. actionHideMixer->setCheckable(true);
  4540. actionHideMixer->setChecked(SourceMixerHidden(source));
  4541. popup.addSeparator();
  4542. }
  4543. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4544. popup.addMenu(
  4545. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4546. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4547. popup.addMenu(AddBlendingModeMenu(blendingModeMenu, sceneItem));
  4548. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4549. popup.addMenu(
  4550. AddBlendingMethodMenu(blendingMethodMenu, sceneItem));
  4551. if (isAsyncVideo) {
  4552. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4553. popup.addMenu(
  4554. AddDeinterlacingMenu(deinterlaceMenu, source));
  4555. }
  4556. popup.addSeparator();
  4557. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4558. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4559. popup.addSeparator();
  4560. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4561. AddProjectorMenuMonitors(sourceProjector, this,
  4562. SLOT(OpenSourceProjector()));
  4563. popup.addMenu(sourceProjector);
  4564. popup.addAction(QTStr("SourceWindow"), this,
  4565. SLOT(OpenSourceWindow()));
  4566. popup.addAction(QTStr("Screenshot.Source"), this,
  4567. SLOT(ScreenshotSelectedSource()));
  4568. popup.addSeparator();
  4569. if (flags & OBS_SOURCE_INTERACTION)
  4570. popup.addAction(QTStr("Interact"), this,
  4571. SLOT(on_actionInteract_triggered()));
  4572. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4573. QAction *action = popup.addAction(
  4574. QTStr("Properties"), this,
  4575. SLOT(on_actionSourceProperties_triggered()));
  4576. action->setEnabled(obs_source_configurable(source));
  4577. }
  4578. popup.exec(QCursor::pos());
  4579. }
  4580. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4581. {
  4582. if (ui->scenes->count()) {
  4583. QModelIndex idx = ui->sources->indexAt(pos);
  4584. CreateSourcePopupMenu(idx.row(), false);
  4585. }
  4586. }
  4587. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4588. {
  4589. if (!witem)
  4590. return;
  4591. if (IsPreviewProgramMode()) {
  4592. bool doubleClickSwitch =
  4593. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4594. "TransitionOnDoubleClick");
  4595. if (doubleClickSwitch)
  4596. TransitionClicked();
  4597. }
  4598. }
  4599. static inline bool should_show_properties(obs_source_t *source, const char *id)
  4600. {
  4601. if (!source)
  4602. return false;
  4603. if (strcmp(id, "group") == 0)
  4604. return false;
  4605. if (!obs_source_configurable(source))
  4606. return false;
  4607. uint32_t caps = obs_source_get_output_flags(source);
  4608. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  4609. return false;
  4610. return true;
  4611. }
  4612. void OBSBasic::AddSource(const char *id)
  4613. {
  4614. if (id && *id) {
  4615. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  4616. sourceSelect.exec();
  4617. if (should_show_properties(sourceSelect.newSource, id)) {
  4618. CreatePropertiesWindow(sourceSelect.newSource);
  4619. }
  4620. }
  4621. }
  4622. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4623. {
  4624. const char *unversioned_type;
  4625. const char *type;
  4626. bool foundValues = false;
  4627. bool foundDeprecated = false;
  4628. size_t idx = 0;
  4629. QMenu *popup = new QMenu(QTStr("Add"), this);
  4630. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4631. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4632. QList<QAction *> actions = menu->actions();
  4633. for (QAction *menuAction : actions) {
  4634. if (menuAction->text().compare(name) >= 0)
  4635. return menuAction;
  4636. }
  4637. return (QAction *)nullptr;
  4638. };
  4639. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4640. const char *name) {
  4641. QString qname = QT_UTF8(name);
  4642. QAction *popupItem = new QAction(qname, this);
  4643. popupItem->setData(QT_UTF8(type));
  4644. connect(popupItem, SIGNAL(triggered(bool)), this,
  4645. SLOT(AddSourceFromAction()));
  4646. QIcon icon;
  4647. if (strcmp(type, "scene") == 0)
  4648. icon = GetSceneIcon();
  4649. else
  4650. icon = GetSourceIcon(type);
  4651. popupItem->setIcon(icon);
  4652. QAction *after = getActionAfter(popup, qname);
  4653. popup->insertAction(after, popupItem);
  4654. };
  4655. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4656. const char *name = obs_source_get_display_name(type);
  4657. uint32_t caps = obs_get_source_output_flags(type);
  4658. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4659. continue;
  4660. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4661. addSource(popup, unversioned_type, name);
  4662. } else {
  4663. addSource(deprecated, unversioned_type, name);
  4664. foundDeprecated = true;
  4665. }
  4666. foundValues = true;
  4667. }
  4668. addSource(popup, "scene", Str("Basic.Scene"));
  4669. popup->addSeparator();
  4670. QAction *addGroup = new QAction(QTStr("Group"), this);
  4671. addGroup->setData(QT_UTF8("group"));
  4672. addGroup->setIcon(GetGroupIcon());
  4673. connect(addGroup, SIGNAL(triggered(bool)), this,
  4674. SLOT(AddSourceFromAction()));
  4675. popup->addAction(addGroup);
  4676. if (!foundDeprecated) {
  4677. delete deprecated;
  4678. deprecated = nullptr;
  4679. }
  4680. if (!foundValues) {
  4681. delete popup;
  4682. popup = nullptr;
  4683. } else if (foundDeprecated) {
  4684. popup->addSeparator();
  4685. popup->addMenu(deprecated);
  4686. }
  4687. return popup;
  4688. }
  4689. void OBSBasic::AddSourceFromAction()
  4690. {
  4691. QAction *action = qobject_cast<QAction *>(sender());
  4692. if (!action)
  4693. return;
  4694. AddSource(QT_TO_UTF8(action->data().toString()));
  4695. }
  4696. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4697. {
  4698. if (!GetCurrentScene()) {
  4699. // Tell the user he needs a scene first (help beginners).
  4700. OBSMessageBox::information(
  4701. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4702. QTStr("Basic.Main.AddSourceHelp.Text"));
  4703. return;
  4704. }
  4705. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4706. if (popup)
  4707. popup->exec(pos);
  4708. }
  4709. void OBSBasic::on_actionAddSource_triggered()
  4710. {
  4711. AddSourcePopupMenu(QCursor::pos());
  4712. }
  4713. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4714. {
  4715. vector<OBSSceneItem> &items =
  4716. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4717. if (obs_sceneitem_selected(item)) {
  4718. items.emplace_back(item);
  4719. } else if (obs_sceneitem_is_group(item)) {
  4720. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4721. }
  4722. return true;
  4723. };
  4724. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  4725. std::vector<obs_source_t *> *sources)
  4726. {
  4727. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  4728. if (!sources) {
  4729. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  4730. } else {
  4731. for (obs_source_t *source : *sources) {
  4732. obs_data_t *source_data = obs_save_source(source);
  4733. obs_data_array_push_back(undo_array, source_data);
  4734. obs_data_release(source_data);
  4735. }
  4736. }
  4737. OBSDataAutoRelease scene_data =
  4738. obs_save_source(obs_scene_get_source(scene));
  4739. obs_data_array_push_back(undo_array, scene_data);
  4740. OBSDataAutoRelease data = obs_data_create();
  4741. obs_data_set_array(data, "array", undo_array);
  4742. obs_data_get_json(data);
  4743. return data.Get();
  4744. }
  4745. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  4746. {
  4747. auto sources = static_cast<std::vector<OBSSource> *>(p);
  4748. sources->push_back(obs_sceneitem_get_source(item));
  4749. return true;
  4750. }
  4751. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  4752. OBSData undo_data, OBSData redo_data)
  4753. {
  4754. auto undo_redo = [this](const std::string &json) {
  4755. OBSDataAutoRelease base =
  4756. obs_data_create_from_json(json.c_str());
  4757. OBSDataArrayAutoRelease array =
  4758. obs_data_get_array(base, "array");
  4759. std::vector<OBSSource> sources;
  4760. std::vector<OBSSource> old_sources;
  4761. /* create missing sources */
  4762. const size_t count = obs_data_array_count(array);
  4763. sources.reserve(count);
  4764. for (size_t i = 0; i < count; i++) {
  4765. OBSDataAutoRelease data = obs_data_array_item(array, i);
  4766. const char *name = obs_data_get_string(data, "name");
  4767. OBSSourceAutoRelease source =
  4768. obs_get_source_by_name(name);
  4769. if (!source)
  4770. source = obs_load_source(data);
  4771. sources.push_back(source.Get());
  4772. /* update scene/group settings to restore their
  4773. * contents to their saved settings */
  4774. obs_scene_t *scene =
  4775. obs_group_or_scene_from_source(source);
  4776. if (scene) {
  4777. obs_scene_enum_items(scene, add_source_enum,
  4778. &old_sources);
  4779. OBSDataAutoRelease scene_settings =
  4780. obs_data_get_obj(data, "settings");
  4781. obs_source_update(source, scene_settings);
  4782. }
  4783. }
  4784. /* actually load sources now */
  4785. for (obs_source_t *source : sources)
  4786. obs_source_load2(source);
  4787. ui->sources->RefreshItems();
  4788. };
  4789. const char *undo_json = obs_data_get_last_json(undo_data);
  4790. const char *redo_json = obs_data_get_last_json(redo_data);
  4791. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  4792. redo_json);
  4793. }
  4794. void OBSBasic::on_actionRemoveSource_triggered()
  4795. {
  4796. vector<OBSSceneItem> items;
  4797. OBSScene scene = GetCurrentScene();
  4798. obs_source_t *scene_source = obs_scene_get_source(scene);
  4799. obs_scene_enum_items(scene, remove_items, &items);
  4800. if (!items.size())
  4801. return;
  4802. /* ------------------------------------- */
  4803. /* confirm action with user */
  4804. bool confirmed = false;
  4805. if (items.size() > 1) {
  4806. QString text = QTStr("ConfirmRemove.TextMultiple")
  4807. .arg(QString::number(items.size()));
  4808. QMessageBox remove_items(this);
  4809. remove_items.setText(text);
  4810. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4811. QMessageBox::YesRole);
  4812. remove_items.setDefaultButton(Yes);
  4813. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4814. remove_items.setIcon(QMessageBox::Question);
  4815. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4816. remove_items.exec();
  4817. confirmed = Yes == remove_items.clickedButton();
  4818. } else {
  4819. OBSSceneItem &item = items[0];
  4820. obs_source_t *source = obs_sceneitem_get_source(item);
  4821. if (source && QueryRemoveSource(source))
  4822. confirmed = true;
  4823. }
  4824. if (!confirmed)
  4825. return;
  4826. /* ----------------------------------------------- */
  4827. /* save undo data */
  4828. OBSData undo_data = BackupScene(scene_source);
  4829. /* ----------------------------------------------- */
  4830. /* remove items */
  4831. for (auto &item : items)
  4832. obs_sceneitem_remove(item);
  4833. /* ----------------------------------------------- */
  4834. /* save redo data */
  4835. OBSData redo_data = BackupScene(scene_source);
  4836. /* ----------------------------------------------- */
  4837. /* add undo/redo action */
  4838. QString action_name;
  4839. if (items.size() > 1) {
  4840. action_name = QTStr("Undo.Sources.Multi")
  4841. .arg(QString::number(items.size()));
  4842. } else {
  4843. QString str = QTStr("Undo.Delete");
  4844. action_name = str.arg(obs_source_get_name(
  4845. obs_sceneitem_get_source(items[0])));
  4846. }
  4847. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  4848. }
  4849. void OBSBasic::on_actionInteract_triggered()
  4850. {
  4851. OBSSceneItem item = GetCurrentSceneItem();
  4852. OBSSource source = obs_sceneitem_get_source(item);
  4853. if (source)
  4854. CreateInteractionWindow(source);
  4855. }
  4856. void OBSBasic::on_actionSourceProperties_triggered()
  4857. {
  4858. OBSSceneItem item = GetCurrentSceneItem();
  4859. OBSSource source = obs_sceneitem_get_source(item);
  4860. if (source)
  4861. CreatePropertiesWindow(source);
  4862. }
  4863. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  4864. const QString &action_name)
  4865. {
  4866. OBSSceneItem item = GetCurrentSceneItem();
  4867. obs_source_t *source = obs_sceneitem_get_source(item);
  4868. if (!source)
  4869. return;
  4870. OBSScene scene = GetCurrentScene();
  4871. std::vector<obs_source_t *> sources;
  4872. if (scene != obs_sceneitem_get_scene(item))
  4873. sources.push_back(
  4874. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  4875. OBSData undo_data = BackupScene(scene, &sources);
  4876. obs_sceneitem_set_order(item, movement);
  4877. const char *source_name = obs_source_get_name(source);
  4878. const char *scene_name =
  4879. obs_source_get_name(obs_scene_get_source(scene));
  4880. OBSData redo_data = BackupScene(scene, &sources);
  4881. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  4882. undo_data, redo_data);
  4883. }
  4884. void OBSBasic::on_actionSourceUp_triggered()
  4885. {
  4886. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4887. }
  4888. void OBSBasic::on_actionSourceDown_triggered()
  4889. {
  4890. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4891. }
  4892. void OBSBasic::on_actionMoveUp_triggered()
  4893. {
  4894. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4895. }
  4896. void OBSBasic::on_actionMoveDown_triggered()
  4897. {
  4898. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4899. }
  4900. void OBSBasic::on_actionMoveToTop_triggered()
  4901. {
  4902. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  4903. }
  4904. void OBSBasic::on_actionMoveToBottom_triggered()
  4905. {
  4906. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  4907. }
  4908. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4909. {
  4910. char logDir[512];
  4911. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4912. return nullptr;
  4913. string path = logDir;
  4914. path += "/";
  4915. path += log;
  4916. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4917. if (!file)
  4918. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4919. return file;
  4920. }
  4921. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4922. {
  4923. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4924. if (!fileString)
  4925. return;
  4926. if (!*fileString)
  4927. return;
  4928. ui->menuLogFiles->setEnabled(false);
  4929. #if defined(_WIN32)
  4930. ui->menuCrashLogs->setEnabled(false);
  4931. #endif
  4932. stringstream ss;
  4933. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4934. << CurrentDateTimeString() << "\n\n"
  4935. << fileString;
  4936. if (logUploadThread) {
  4937. logUploadThread->wait();
  4938. }
  4939. RemoteTextThread *thread =
  4940. new RemoteTextThread("https://obsproject.com/logs/upload",
  4941. "text/plain", ss.str().c_str());
  4942. logUploadThread.reset(thread);
  4943. if (crash) {
  4944. connect(thread, &RemoteTextThread::Result, this,
  4945. &OBSBasic::crashUploadFinished);
  4946. } else {
  4947. connect(thread, &RemoteTextThread::Result, this,
  4948. &OBSBasic::logUploadFinished);
  4949. }
  4950. logUploadThread->start();
  4951. }
  4952. void OBSBasic::on_actionShowLogs_triggered()
  4953. {
  4954. char logDir[512];
  4955. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4956. return;
  4957. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4958. QDesktopServices::openUrl(url);
  4959. }
  4960. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4961. {
  4962. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  4963. }
  4964. void OBSBasic::on_actionUploadLastLog_triggered()
  4965. {
  4966. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  4967. }
  4968. void OBSBasic::on_actionViewCurrentLog_triggered()
  4969. {
  4970. if (!logView)
  4971. logView = new OBSLogViewer();
  4972. logView->show();
  4973. logView->setWindowState(
  4974. (logView->windowState() & ~Qt::WindowMinimized) |
  4975. Qt::WindowActive);
  4976. logView->activateWindow();
  4977. logView->raise();
  4978. }
  4979. void OBSBasic::on_actionShowCrashLogs_triggered()
  4980. {
  4981. char logDir[512];
  4982. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4983. return;
  4984. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4985. QDesktopServices::openUrl(url);
  4986. }
  4987. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4988. {
  4989. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  4990. }
  4991. void OBSBasic::on_actionCheckForUpdates_triggered()
  4992. {
  4993. CheckForUpdates(true);
  4994. }
  4995. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4996. {
  4997. ui->menuLogFiles->setEnabled(true);
  4998. #if defined(_WIN32)
  4999. ui->menuCrashLogs->setEnabled(true);
  5000. #endif
  5001. if (text.isEmpty()) {
  5002. OBSMessageBox::critical(
  5003. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5004. error);
  5005. return;
  5006. }
  5007. openLogDialog(text, false);
  5008. }
  5009. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5010. {
  5011. ui->menuLogFiles->setEnabled(true);
  5012. #if defined(_WIN32)
  5013. ui->menuCrashLogs->setEnabled(true);
  5014. #endif
  5015. if (text.isEmpty()) {
  5016. OBSMessageBox::critical(
  5017. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5018. error);
  5019. return;
  5020. }
  5021. openLogDialog(text, true);
  5022. }
  5023. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5024. {
  5025. OBSDataAutoRelease returnData =
  5026. obs_data_create_from_json(QT_TO_UTF8(text));
  5027. string resURL = obs_data_get_string(returnData, "url");
  5028. QString logURL = resURL.c_str();
  5029. OBSLogReply logDialog(this, logURL, crash);
  5030. logDialog.exec();
  5031. }
  5032. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5033. obs_source_t *source, const string &name)
  5034. {
  5035. const char *prevName = obs_source_get_name(source);
  5036. if (name == prevName)
  5037. return;
  5038. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5039. QListWidgetItem *listItem = listWidget->currentItem();
  5040. if (foundSource || name.empty()) {
  5041. listItem->setText(QT_UTF8(prevName));
  5042. if (foundSource) {
  5043. OBSMessageBox::warning(parent,
  5044. QTStr("NameExists.Title"),
  5045. QTStr("NameExists.Text"));
  5046. } else if (name.empty()) {
  5047. OBSMessageBox::warning(parent,
  5048. QTStr("NoNameEntered.Title"),
  5049. QTStr("NoNameEntered.Text"));
  5050. }
  5051. } else {
  5052. auto undo = [prev = std::string(prevName)](
  5053. const std::string &data) {
  5054. OBSSourceAutoRelease source =
  5055. obs_get_source_by_name(data.c_str());
  5056. obs_source_set_name(source, prev.c_str());
  5057. };
  5058. auto redo = [name](const std::string &data) {
  5059. OBSSourceAutoRelease source =
  5060. obs_get_source_by_name(data.c_str());
  5061. obs_source_set_name(source, name.c_str());
  5062. };
  5063. std::string undo_data(name);
  5064. std::string redo_data(prevName);
  5065. parent->undo_s.add_action(
  5066. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5067. undo_data, redo_data);
  5068. listItem->setText(QT_UTF8(name.c_str()));
  5069. obs_source_set_name(source, name.c_str());
  5070. }
  5071. }
  5072. void OBSBasic::SceneNameEdited(QWidget *editor,
  5073. QAbstractItemDelegate::EndEditHint endHint)
  5074. {
  5075. OBSScene scene = GetCurrentScene();
  5076. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5077. string text = QT_TO_UTF8(edit->text().trimmed());
  5078. if (!scene)
  5079. return;
  5080. obs_source_t *source = obs_scene_get_source(scene);
  5081. RenameListItem(this, ui->scenes, source, text);
  5082. ui->scenesDock->addAction(renameScene);
  5083. if (api)
  5084. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5085. UNUSED_PARAMETER(endHint);
  5086. }
  5087. void OBSBasic::OpenFilters(OBSSource source)
  5088. {
  5089. if (source == nullptr) {
  5090. OBSSceneItem item = GetCurrentSceneItem();
  5091. source = obs_sceneitem_get_source(item);
  5092. }
  5093. CreateFiltersWindow(source);
  5094. }
  5095. void OBSBasic::OpenProperties(OBSSource source)
  5096. {
  5097. if (source == nullptr) {
  5098. OBSSceneItem item = GetCurrentSceneItem();
  5099. source = obs_sceneitem_get_source(item);
  5100. }
  5101. CreatePropertiesWindow(source);
  5102. }
  5103. void OBSBasic::OpenInteraction(OBSSource source)
  5104. {
  5105. if (source == nullptr) {
  5106. OBSSceneItem item = GetCurrentSceneItem();
  5107. source = obs_sceneitem_get_source(item);
  5108. }
  5109. CreateInteractionWindow(source);
  5110. }
  5111. void OBSBasic::OpenSceneFilters()
  5112. {
  5113. OBSScene scene = GetCurrentScene();
  5114. OBSSource source = obs_scene_get_source(scene);
  5115. CreateFiltersWindow(source);
  5116. }
  5117. #define RECORDING_START \
  5118. "==== Recording Start ==============================================="
  5119. #define RECORDING_STOP \
  5120. "==== Recording Stop ================================================"
  5121. #define REPLAY_BUFFER_START \
  5122. "==== Replay Buffer Start ==========================================="
  5123. #define REPLAY_BUFFER_STOP \
  5124. "==== Replay Buffer Stop ============================================"
  5125. #define STREAMING_START \
  5126. "==== Streaming Start ==============================================="
  5127. #define STREAMING_STOP \
  5128. "==== Streaming Stop ================================================"
  5129. #define VIRTUAL_CAM_START \
  5130. "==== Virtual Camera Start =========================================="
  5131. #define VIRTUAL_CAM_STOP \
  5132. "==== Virtual Camera Stop ==========================================="
  5133. void OBSBasic::DisplayStreamStartError()
  5134. {
  5135. QString message = !outputHandler->lastError.empty()
  5136. ? QTStr(outputHandler->lastError.c_str())
  5137. : QTStr("Output.StartFailedGeneric");
  5138. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5139. ui->streamButton->setEnabled(true);
  5140. ui->streamButton->setChecked(false);
  5141. if (sysTrayStream) {
  5142. sysTrayStream->setText(ui->streamButton->text());
  5143. sysTrayStream->setEnabled(true);
  5144. }
  5145. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5146. }
  5147. #if YOUTUBE_ENABLED
  5148. void OBSBasic::YouTubeActionDialogOk(const QString &id, const QString &key,
  5149. bool autostart, bool autostop,
  5150. bool start_now)
  5151. {
  5152. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5153. obs_service_t *service_obj = GetService();
  5154. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5155. const std::string a_key = QT_TO_UTF8(key);
  5156. obs_data_set_string(settings, "key", a_key.c_str());
  5157. const std::string an_id = QT_TO_UTF8(id);
  5158. obs_data_set_string(settings, "stream_id", an_id.c_str());
  5159. obs_service_update(service_obj, settings);
  5160. autoStartBroadcast = autostart;
  5161. autoStopBroadcast = autostop;
  5162. broadcastReady = true;
  5163. if (start_now)
  5164. QMetaObject::invokeMethod(this, "StartStreaming");
  5165. }
  5166. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5167. {
  5168. YoutubeApiWrappers *apiYouTube(
  5169. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5170. if (!apiYouTube) {
  5171. /* technically we should never get here -Jim */
  5172. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5173. Qt::QueuedConnection);
  5174. youtubeStreamCheckThread->deleteLater();
  5175. blog(LOG_ERROR, "==========================================");
  5176. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5177. blog(LOG_ERROR, "==========================================");
  5178. return;
  5179. }
  5180. int timeout = 0;
  5181. json11::Json json;
  5182. QString id = key.c_str();
  5183. while (StreamingActive()) {
  5184. if (timeout == 14) {
  5185. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5186. Qt::QueuedConnection);
  5187. break;
  5188. }
  5189. if (!apiYouTube->FindStream(id, json)) {
  5190. QMetaObject::invokeMethod(this,
  5191. "DisplayStreamStartError",
  5192. Qt::QueuedConnection);
  5193. QMetaObject::invokeMethod(this, "StopStreaming",
  5194. Qt::QueuedConnection);
  5195. break;
  5196. }
  5197. auto item = json["items"][0];
  5198. auto status = item["status"]["streamStatus"].string_value();
  5199. if (status == "active") {
  5200. QMetaObject::invokeMethod(ui->broadcastButton,
  5201. "setEnabled",
  5202. Q_ARG(bool, true));
  5203. break;
  5204. } else {
  5205. QThread::sleep(1);
  5206. timeout++;
  5207. }
  5208. }
  5209. youtubeStreamCheckThread->deleteLater();
  5210. }
  5211. void OBSBasic::ShowYouTubeAutoStartWarning()
  5212. {
  5213. auto msgBox = []() {
  5214. QMessageBox msgbox(App()->GetMainWindow());
  5215. msgbox.setWindowTitle(QTStr(
  5216. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5217. msgbox.setText(
  5218. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5219. msgbox.setIcon(QMessageBox::Icon::Information);
  5220. msgbox.addButton(QMessageBox::Ok);
  5221. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5222. msgbox.setCheckBox(cb);
  5223. msgbox.exec();
  5224. if (cb->isChecked()) {
  5225. config_set_bool(App()->GlobalConfig(), "General",
  5226. "WarnedAboutYouTubeAutoStart", true);
  5227. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5228. }
  5229. };
  5230. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5231. "WarnedAboutYouTubeAutoStart");
  5232. if (!warned) {
  5233. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5234. Q_ARG(VoidFunc, msgBox));
  5235. }
  5236. }
  5237. #endif
  5238. void OBSBasic::StartStreaming()
  5239. {
  5240. if (outputHandler->StreamingActive())
  5241. return;
  5242. if (disableOutputsRef)
  5243. return;
  5244. if (auth && auth->broadcastFlow()) {
  5245. if (!broadcastActive && !broadcastReady) {
  5246. ui->streamButton->setChecked(false);
  5247. QMessageBox no_broadcast(this);
  5248. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5249. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5250. QTStr("Basic.Main.SetupBroadcast"),
  5251. QMessageBox::YesRole);
  5252. no_broadcast.setDefaultButton(SetupBroadcast);
  5253. no_broadcast.addButton(QTStr("Close"),
  5254. QMessageBox::NoRole);
  5255. no_broadcast.setIcon(QMessageBox::Information);
  5256. no_broadcast.setWindowTitle(
  5257. QTStr("Output.NoBroadcast.Title"));
  5258. no_broadcast.exec();
  5259. if (no_broadcast.clickedButton() == SetupBroadcast)
  5260. QMetaObject::invokeMethod(this,
  5261. "SetupBroadcast");
  5262. return;
  5263. }
  5264. }
  5265. if (!outputHandler->SetupStreaming(service)) {
  5266. DisplayStreamStartError();
  5267. return;
  5268. }
  5269. if (api)
  5270. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5271. SaveProject();
  5272. ui->streamButton->setEnabled(false);
  5273. ui->streamButton->setChecked(false);
  5274. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5275. ui->broadcastButton->setChecked(false);
  5276. if (sysTrayStream) {
  5277. sysTrayStream->setEnabled(false);
  5278. sysTrayStream->setText(ui->streamButton->text());
  5279. }
  5280. if (!outputHandler->StartStreaming(service)) {
  5281. DisplayStreamStartError();
  5282. return;
  5283. }
  5284. if (!autoStartBroadcast) {
  5285. ui->broadcastButton->setText(
  5286. QTStr("Basic.Main.StartBroadcast"));
  5287. ui->broadcastButton->setProperty("broadcastState", "ready");
  5288. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5289. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5290. // well, we need to disable button while stream is not active
  5291. ui->broadcastButton->setEnabled(false);
  5292. } else {
  5293. if (!autoStopBroadcast) {
  5294. ui->broadcastButton->setText(
  5295. QTStr("Basic.Main.StopBroadcast"));
  5296. } else {
  5297. ui->broadcastButton->setText(
  5298. QTStr("Basic.Main.AutoStopEnabled"));
  5299. ui->broadcastButton->setEnabled(false);
  5300. }
  5301. ui->broadcastButton->setProperty("broadcastState", "active");
  5302. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5303. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5304. broadcastActive = true;
  5305. }
  5306. bool recordWhenStreaming = config_get_bool(
  5307. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5308. if (recordWhenStreaming)
  5309. StartRecording();
  5310. bool replayBufferWhileStreaming = config_get_bool(
  5311. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5312. if (replayBufferWhileStreaming)
  5313. StartReplayBuffer();
  5314. #if YOUTUBE_ENABLED
  5315. if (!autoStartBroadcast)
  5316. OBSBasic::ShowYouTubeAutoStartWarning();
  5317. #endif
  5318. }
  5319. void OBSBasic::BroadcastButtonClicked()
  5320. {
  5321. if (!broadcastReady ||
  5322. (!broadcastActive && !outputHandler->StreamingActive())) {
  5323. SetupBroadcast();
  5324. if (broadcastReady)
  5325. ui->broadcastButton->setChecked(true);
  5326. return;
  5327. }
  5328. if (!autoStartBroadcast) {
  5329. #if YOUTUBE_ENABLED
  5330. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5331. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5332. if (ytAuth.get()) {
  5333. if (!ytAuth->StartLatestBroadcast()) {
  5334. auto last_error = ytAuth->GetLastError();
  5335. if (last_error.isEmpty())
  5336. last_error = QTStr(
  5337. "YouTube.Actions.Error.YouTubeApi");
  5338. if (!ytAuth->GetTranslatedError(last_error))
  5339. last_error =
  5340. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5341. .arg(last_error,
  5342. ytAuth->GetBroadcastId());
  5343. OBSMessageBox::warning(
  5344. this,
  5345. QTStr("Output.BroadcastStartFailed"),
  5346. last_error, true);
  5347. ui->broadcastButton->setChecked(false);
  5348. return;
  5349. }
  5350. }
  5351. #endif
  5352. broadcastActive = true;
  5353. autoStartBroadcast = true; // and clear the flag
  5354. if (!autoStopBroadcast) {
  5355. ui->broadcastButton->setText(
  5356. QTStr("Basic.Main.StopBroadcast"));
  5357. } else {
  5358. ui->broadcastButton->setText(
  5359. QTStr("Basic.Main.AutoStopEnabled"));
  5360. ui->broadcastButton->setEnabled(false);
  5361. }
  5362. ui->broadcastButton->setProperty("broadcastState", "active");
  5363. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5364. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5365. } else if (!autoStopBroadcast) {
  5366. #if YOUTUBE_ENABLED
  5367. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5368. "WarnBeforeStoppingStream");
  5369. if (confirm && isVisible()) {
  5370. QMessageBox::StandardButton button = OBSMessageBox::question(
  5371. this, QTStr("ConfirmStop.Title"),
  5372. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5373. QMessageBox::Yes | QMessageBox::No,
  5374. QMessageBox::No);
  5375. if (button == QMessageBox::No) {
  5376. ui->broadcastButton->setChecked(true);
  5377. return;
  5378. }
  5379. }
  5380. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5381. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5382. if (ytAuth.get()) {
  5383. if (!ytAuth->StopLatestBroadcast()) {
  5384. auto last_error = ytAuth->GetLastError();
  5385. if (last_error.isEmpty())
  5386. last_error = QTStr(
  5387. "YouTube.Actions.Error.YouTubeApi");
  5388. if (!ytAuth->GetTranslatedError(last_error))
  5389. last_error =
  5390. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5391. .arg(last_error,
  5392. ytAuth->GetBroadcastId());
  5393. OBSMessageBox::warning(
  5394. this,
  5395. QTStr("Output.BroadcastStopFailed"),
  5396. last_error, true);
  5397. }
  5398. }
  5399. #endif
  5400. broadcastActive = false;
  5401. broadcastReady = false;
  5402. autoStopBroadcast = true;
  5403. QMetaObject::invokeMethod(this, "StopStreaming");
  5404. SetBroadcastFlowEnabled(true);
  5405. }
  5406. }
  5407. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5408. {
  5409. ui->broadcastButton->setEnabled(enabled);
  5410. ui->broadcastButton->setVisible(enabled);
  5411. ui->broadcastButton->setChecked(broadcastReady);
  5412. ui->broadcastButton->setProperty("broadcastState", "idle");
  5413. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5414. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5415. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5416. }
  5417. void OBSBasic::SetupBroadcast()
  5418. {
  5419. #if YOUTUBE_ENABLED
  5420. Auth *const auth = GetAuth();
  5421. if (IsYouTubeService(auth->service())) {
  5422. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5423. connect(&dialog, &OBSYoutubeActions::ok, this,
  5424. &OBSBasic::YouTubeActionDialogOk);
  5425. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5426. if (result != QDialog::Accepted) {
  5427. if (!broadcastReady)
  5428. ui->broadcastButton->setChecked(false);
  5429. }
  5430. }
  5431. #endif
  5432. }
  5433. #ifdef _WIN32
  5434. static inline void UpdateProcessPriority()
  5435. {
  5436. const char *priority = config_get_string(App()->GlobalConfig(),
  5437. "General", "ProcessPriority");
  5438. if (priority && strcmp(priority, "Normal") != 0)
  5439. SetProcessPriority(priority);
  5440. }
  5441. static inline void ClearProcessPriority()
  5442. {
  5443. const char *priority = config_get_string(App()->GlobalConfig(),
  5444. "General", "ProcessPriority");
  5445. if (priority && strcmp(priority, "Normal") != 0)
  5446. SetProcessPriority("Normal");
  5447. }
  5448. #else
  5449. #define UpdateProcessPriority() \
  5450. do { \
  5451. } while (false)
  5452. #define ClearProcessPriority() \
  5453. do { \
  5454. } while (false)
  5455. #endif
  5456. inline void OBSBasic::OnActivate(bool force)
  5457. {
  5458. if (ui->profileMenu->isEnabled() || force) {
  5459. ui->profileMenu->setEnabled(false);
  5460. ui->autoConfigure->setEnabled(false);
  5461. App()->IncrementSleepInhibition();
  5462. UpdateProcessPriority();
  5463. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5464. if (trayIcon && trayIcon->isVisible()) {
  5465. #ifdef __APPLE__
  5466. QIcon trayMask =
  5467. QIcon(":/res/images/tray_active_macos.svg");
  5468. trayMask.setIsMask(true);
  5469. trayIcon->setIcon(
  5470. QIcon::fromTheme("obs-tray", trayMask));
  5471. #else
  5472. trayIcon->setIcon(QIcon::fromTheme(
  5473. "obs-tray-active",
  5474. QIcon(":/res/images/tray_active.png")));
  5475. #endif
  5476. }
  5477. }
  5478. }
  5479. extern volatile bool recording_paused;
  5480. extern volatile bool replaybuf_active;
  5481. inline void OBSBasic::OnDeactivate()
  5482. {
  5483. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5484. ui->profileMenu->setEnabled(true);
  5485. ui->autoConfigure->setEnabled(true);
  5486. App()->DecrementSleepInhibition();
  5487. ClearProcessPriority();
  5488. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5489. if (trayIcon && trayIcon->isVisible()) {
  5490. #ifdef __APPLE__
  5491. QIcon trayIconFile =
  5492. QIcon(":/res/images/obs_macos.svg");
  5493. trayIconFile.setIsMask(true);
  5494. #else
  5495. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5496. #endif
  5497. trayIcon->setIcon(
  5498. QIcon::fromTheme("obs-tray", trayIconFile));
  5499. }
  5500. } else if (outputHandler->Active() && trayIcon &&
  5501. trayIcon->isVisible()) {
  5502. if (os_atomic_load_bool(&recording_paused)) {
  5503. #ifdef __APPLE__
  5504. QIcon trayIconFile =
  5505. QIcon(":/res/images/obs_paused_macos.svg");
  5506. trayIconFile.setIsMask(true);
  5507. #else
  5508. QIcon trayIconFile =
  5509. QIcon(":/res/images/obs_paused.png");
  5510. #endif
  5511. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5512. trayIconFile));
  5513. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5514. } else {
  5515. #ifdef __APPLE__
  5516. QIcon trayIconFile =
  5517. QIcon(":/res/images/tray_active_macos.svg");
  5518. trayIconFile.setIsMask(true);
  5519. #else
  5520. QIcon trayIconFile =
  5521. QIcon(":/res/images/tray_active.png");
  5522. #endif
  5523. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5524. trayIconFile));
  5525. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5526. }
  5527. }
  5528. }
  5529. void OBSBasic::StopStreaming()
  5530. {
  5531. SaveProject();
  5532. if (outputHandler->StreamingActive())
  5533. outputHandler->StopStreaming(streamingStopping);
  5534. // special case: force reset broadcast state if
  5535. // no autostart and no autostop selected
  5536. if (!autoStartBroadcast && !broadcastActive) {
  5537. broadcastActive = false;
  5538. autoStartBroadcast = true;
  5539. autoStopBroadcast = true;
  5540. broadcastReady = false;
  5541. }
  5542. if (autoStopBroadcast) {
  5543. broadcastActive = false;
  5544. broadcastReady = false;
  5545. }
  5546. OnDeactivate();
  5547. bool recordWhenStreaming = config_get_bool(
  5548. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5549. bool keepRecordingWhenStreamStops =
  5550. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5551. "KeepRecordingWhenStreamStops");
  5552. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5553. StopRecording();
  5554. bool replayBufferWhileStreaming = config_get_bool(
  5555. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5556. bool keepReplayBufferStreamStops =
  5557. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5558. "KeepReplayBufferStreamStops");
  5559. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5560. StopReplayBuffer();
  5561. }
  5562. void OBSBasic::ForceStopStreaming()
  5563. {
  5564. SaveProject();
  5565. if (outputHandler->StreamingActive())
  5566. outputHandler->StopStreaming(true);
  5567. // special case: force reset broadcast state if
  5568. // no autostart and no autostop selected
  5569. if (!autoStartBroadcast && !broadcastActive) {
  5570. broadcastActive = false;
  5571. autoStartBroadcast = true;
  5572. autoStopBroadcast = true;
  5573. broadcastReady = false;
  5574. }
  5575. if (autoStopBroadcast) {
  5576. broadcastActive = false;
  5577. broadcastReady = false;
  5578. }
  5579. OnDeactivate();
  5580. bool recordWhenStreaming = config_get_bool(
  5581. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5582. bool keepRecordingWhenStreamStops =
  5583. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5584. "KeepRecordingWhenStreamStops");
  5585. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5586. StopRecording();
  5587. bool replayBufferWhileStreaming = config_get_bool(
  5588. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5589. bool keepReplayBufferStreamStops =
  5590. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5591. "KeepReplayBufferStreamStops");
  5592. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5593. StopReplayBuffer();
  5594. }
  5595. void OBSBasic::StreamDelayStarting(int sec)
  5596. {
  5597. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5598. ui->streamButton->setEnabled(true);
  5599. ui->streamButton->setChecked(true);
  5600. if (sysTrayStream) {
  5601. sysTrayStream->setText(ui->streamButton->text());
  5602. sysTrayStream->setEnabled(true);
  5603. }
  5604. if (!startStreamMenu.isNull())
  5605. startStreamMenu->deleteLater();
  5606. startStreamMenu = new QMenu();
  5607. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  5608. SLOT(StopStreaming()));
  5609. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5610. SLOT(ForceStopStreaming()));
  5611. ui->streamButton->setMenu(startStreamMenu);
  5612. ui->statusbar->StreamDelayStarting(sec);
  5613. OnActivate();
  5614. }
  5615. void OBSBasic::StreamDelayStopping(int sec)
  5616. {
  5617. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5618. ui->streamButton->setEnabled(true);
  5619. ui->streamButton->setChecked(false);
  5620. if (sysTrayStream) {
  5621. sysTrayStream->setText(ui->streamButton->text());
  5622. sysTrayStream->setEnabled(true);
  5623. }
  5624. if (!startStreamMenu.isNull())
  5625. startStreamMenu->deleteLater();
  5626. startStreamMenu = new QMenu();
  5627. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  5628. SLOT(StartStreaming()));
  5629. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5630. SLOT(ForceStopStreaming()));
  5631. ui->streamButton->setMenu(startStreamMenu);
  5632. ui->statusbar->StreamDelayStopping(sec);
  5633. if (api)
  5634. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5635. }
  5636. void OBSBasic::StreamingStart()
  5637. {
  5638. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5639. ui->streamButton->setEnabled(true);
  5640. ui->streamButton->setChecked(true);
  5641. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  5642. if (sysTrayStream) {
  5643. sysTrayStream->setText(ui->streamButton->text());
  5644. sysTrayStream->setEnabled(true);
  5645. }
  5646. #if YOUTUBE_ENABLED
  5647. if (!autoStartBroadcast) {
  5648. // get a current stream key
  5649. obs_service_t *service_obj = GetService();
  5650. OBSDataAutoRelease settings =
  5651. obs_service_get_settings(service_obj);
  5652. std::string key = obs_data_get_string(settings, "stream_id");
  5653. if (!key.empty() && !youtubeStreamCheckThread) {
  5654. youtubeStreamCheckThread = CreateQThread(
  5655. [this, key] { YoutubeStreamCheck(key); });
  5656. youtubeStreamCheckThread->setObjectName(
  5657. "YouTubeStreamCheckThread");
  5658. youtubeStreamCheckThread->start();
  5659. }
  5660. }
  5661. #endif
  5662. if (api)
  5663. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  5664. OnActivate();
  5665. blog(LOG_INFO, STREAMING_START);
  5666. }
  5667. void OBSBasic::StreamStopping()
  5668. {
  5669. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  5670. if (sysTrayStream)
  5671. sysTrayStream->setText(ui->streamButton->text());
  5672. streamingStopping = true;
  5673. if (api)
  5674. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5675. }
  5676. void OBSBasic::StreamingStop(int code, QString last_error)
  5677. {
  5678. const char *errorDescription = "";
  5679. DStr errorMessage;
  5680. bool use_last_error = false;
  5681. bool encode_error = false;
  5682. switch (code) {
  5683. case OBS_OUTPUT_BAD_PATH:
  5684. errorDescription = Str("Output.ConnectFail.BadPath");
  5685. break;
  5686. case OBS_OUTPUT_CONNECT_FAILED:
  5687. use_last_error = true;
  5688. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  5689. break;
  5690. case OBS_OUTPUT_INVALID_STREAM:
  5691. errorDescription = Str("Output.ConnectFail.InvalidStream");
  5692. break;
  5693. case OBS_OUTPUT_ENCODE_ERROR:
  5694. encode_error = true;
  5695. break;
  5696. default:
  5697. case OBS_OUTPUT_ERROR:
  5698. use_last_error = true;
  5699. errorDescription = Str("Output.ConnectFail.Error");
  5700. break;
  5701. case OBS_OUTPUT_DISCONNECTED:
  5702. /* doesn't happen if output is set to reconnect. note that
  5703. * reconnects are handled in the output, not in the UI */
  5704. use_last_error = true;
  5705. errorDescription = Str("Output.ConnectFail.Disconnected");
  5706. }
  5707. if (use_last_error && !last_error.isEmpty())
  5708. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5709. QT_TO_UTF8(last_error));
  5710. else
  5711. dstr_copy(errorMessage, errorDescription);
  5712. ui->statusbar->StreamStopped();
  5713. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5714. ui->streamButton->setEnabled(true);
  5715. ui->streamButton->setChecked(false);
  5716. if (sysTrayStream) {
  5717. sysTrayStream->setText(ui->streamButton->text());
  5718. sysTrayStream->setEnabled(true);
  5719. }
  5720. streamingStopping = false;
  5721. if (api)
  5722. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  5723. OnDeactivate();
  5724. blog(LOG_INFO, STREAMING_STOP);
  5725. if (encode_error) {
  5726. QString msg =
  5727. last_error.isEmpty()
  5728. ? QTStr("Output.StreamEncodeError.Msg")
  5729. : QTStr("Output.StreamEncodeError.Msg.LastError")
  5730. .arg(last_error);
  5731. OBSMessageBox::information(
  5732. this, QTStr("Output.StreamEncodeError.Title"), msg);
  5733. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5734. OBSMessageBox::information(this,
  5735. QTStr("Output.ConnectFail.Title"),
  5736. QT_UTF8(errorMessage));
  5737. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5738. SysTrayNotify(QT_UTF8(errorDescription),
  5739. QSystemTrayIcon::Warning);
  5740. }
  5741. if (!startStreamMenu.isNull()) {
  5742. ui->streamButton->setMenu(nullptr);
  5743. startStreamMenu->deleteLater();
  5744. startStreamMenu = nullptr;
  5745. }
  5746. // Reset broadcast button state/text
  5747. if (!broadcastActive)
  5748. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  5749. }
  5750. void OBSBasic::AutoRemux(QString input, bool no_show)
  5751. {
  5752. bool autoRemux = config_get_bool(Config(), "Video", "AutoRemux");
  5753. if (!autoRemux)
  5754. return;
  5755. const char *recType = config_get_string(Config(), "AdvOut", "RecType");
  5756. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  5757. if (ffmpegOutput)
  5758. return;
  5759. if (input.isEmpty())
  5760. return;
  5761. QFileInfo fi(input);
  5762. QString suffix = fi.suffix();
  5763. /* do not remux if lossless */
  5764. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  5765. return;
  5766. }
  5767. QString path = fi.path();
  5768. QString output = input;
  5769. output.resize(output.size() - suffix.size());
  5770. output += "mp4";
  5771. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  5772. if (!no_show)
  5773. remux->show();
  5774. remux->AutoRemux(input, output);
  5775. }
  5776. void OBSBasic::StartRecording()
  5777. {
  5778. if (outputHandler->RecordingActive())
  5779. return;
  5780. if (disableOutputsRef)
  5781. return;
  5782. if (!OutputPathValid()) {
  5783. OutputPathInvalidMessage();
  5784. ui->recordButton->setChecked(false);
  5785. return;
  5786. }
  5787. if (LowDiskSpace()) {
  5788. DiskSpaceMessage();
  5789. ui->recordButton->setChecked(false);
  5790. return;
  5791. }
  5792. if (api)
  5793. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  5794. SaveProject();
  5795. if (!outputHandler->StartRecording())
  5796. ui->recordButton->setChecked(false);
  5797. }
  5798. void OBSBasic::RecordStopping()
  5799. {
  5800. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  5801. if (sysTrayRecord)
  5802. sysTrayRecord->setText(ui->recordButton->text());
  5803. recordingStopping = true;
  5804. if (api)
  5805. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  5806. }
  5807. void OBSBasic::StopRecording()
  5808. {
  5809. SaveProject();
  5810. if (outputHandler->RecordingActive())
  5811. outputHandler->StopRecording(recordingStopping);
  5812. OnDeactivate();
  5813. }
  5814. void OBSBasic::RecordingStart()
  5815. {
  5816. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  5817. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  5818. ui->recordButton->setChecked(true);
  5819. if (sysTrayRecord)
  5820. sysTrayRecord->setText(ui->recordButton->text());
  5821. recordingStopping = false;
  5822. if (api)
  5823. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  5824. if (!diskFullTimer->isActive())
  5825. diskFullTimer->start(1000);
  5826. OnActivate();
  5827. UpdatePause();
  5828. blog(LOG_INFO, RECORDING_START);
  5829. }
  5830. void OBSBasic::RecordingStop(int code, QString last_error)
  5831. {
  5832. ui->statusbar->RecordingStopped();
  5833. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  5834. ui->recordButton->setChecked(false);
  5835. if (sysTrayRecord)
  5836. sysTrayRecord->setText(ui->recordButton->text());
  5837. blog(LOG_INFO, RECORDING_STOP);
  5838. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5839. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5840. QTStr("Output.RecordFail.Unsupported"));
  5841. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  5842. QString msg =
  5843. last_error.isEmpty()
  5844. ? QTStr("Output.RecordError.EncodeErrorMsg")
  5845. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  5846. .arg(last_error);
  5847. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  5848. msg);
  5849. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5850. OBSMessageBox::warning(this,
  5851. QTStr("Output.RecordNoSpace.Title"),
  5852. QTStr("Output.RecordNoSpace.Msg"));
  5853. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5854. const char *errorDescription;
  5855. DStr errorMessage;
  5856. bool use_last_error = true;
  5857. errorDescription = Str("Output.RecordError.Msg");
  5858. if (use_last_error && !last_error.isEmpty())
  5859. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5860. QT_TO_UTF8(last_error));
  5861. else
  5862. dstr_copy(errorMessage, errorDescription);
  5863. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5864. QT_UTF8(errorMessage));
  5865. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5866. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5867. QSystemTrayIcon::Warning);
  5868. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5869. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5870. QSystemTrayIcon::Warning);
  5871. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5872. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5873. QSystemTrayIcon::Warning);
  5874. } else if (code == OBS_OUTPUT_SUCCESS) {
  5875. if (outputHandler) {
  5876. std::string path = outputHandler->lastRecordingPath;
  5877. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5878. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  5879. }
  5880. }
  5881. if (api)
  5882. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  5883. if (diskFullTimer->isActive())
  5884. diskFullTimer->stop();
  5885. AutoRemux(outputHandler->lastRecordingPath.c_str());
  5886. OnDeactivate();
  5887. UpdatePause(false);
  5888. }
  5889. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  5890. {
  5891. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5892. ShowStatusBarMessage(str.arg(lastRecordingPath));
  5893. AutoRemux(lastRecordingPath, true);
  5894. }
  5895. void OBSBasic::ShowReplayBufferPauseWarning()
  5896. {
  5897. auto msgBox = []() {
  5898. QMessageBox msgbox(App()->GetMainWindow());
  5899. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  5900. "PauseWarning.Title"));
  5901. msgbox.setText(QTStr("Output.ReplayBuffer."
  5902. "PauseWarning.Text"));
  5903. msgbox.setIcon(QMessageBox::Icon::Information);
  5904. msgbox.addButton(QMessageBox::Ok);
  5905. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5906. msgbox.setCheckBox(cb);
  5907. msgbox.exec();
  5908. if (cb->isChecked()) {
  5909. config_set_bool(App()->GlobalConfig(), "General",
  5910. "WarnedAboutReplayBufferPausing", true);
  5911. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5912. }
  5913. };
  5914. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5915. "WarnedAboutReplayBufferPausing");
  5916. if (!warned) {
  5917. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5918. Q_ARG(VoidFunc, msgBox));
  5919. }
  5920. }
  5921. void OBSBasic::StartReplayBuffer()
  5922. {
  5923. if (!outputHandler || !outputHandler->replayBuffer)
  5924. return;
  5925. if (outputHandler->ReplayBufferActive())
  5926. return;
  5927. if (disableOutputsRef)
  5928. return;
  5929. if (!UIValidation::NoSourcesConfirmation(this)) {
  5930. replayBufferButton->setChecked(false);
  5931. return;
  5932. }
  5933. if (!OutputPathValid()) {
  5934. OutputPathInvalidMessage();
  5935. replayBufferButton->setChecked(false);
  5936. return;
  5937. }
  5938. if (LowDiskSpace()) {
  5939. DiskSpaceMessage();
  5940. replayBufferButton->setChecked(false);
  5941. return;
  5942. }
  5943. if (api)
  5944. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  5945. SaveProject();
  5946. if (!outputHandler->StartReplayBuffer()) {
  5947. replayBufferButton->setChecked(false);
  5948. } else if (os_atomic_load_bool(&recording_paused)) {
  5949. ShowReplayBufferPauseWarning();
  5950. }
  5951. }
  5952. void OBSBasic::ReplayBufferStopping()
  5953. {
  5954. if (!outputHandler || !outputHandler->replayBuffer)
  5955. return;
  5956. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  5957. if (sysTrayReplayBuffer)
  5958. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5959. replayBufferStopping = true;
  5960. if (api)
  5961. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  5962. }
  5963. void OBSBasic::StopReplayBuffer()
  5964. {
  5965. if (!outputHandler || !outputHandler->replayBuffer)
  5966. return;
  5967. SaveProject();
  5968. if (outputHandler->ReplayBufferActive())
  5969. outputHandler->StopReplayBuffer(replayBufferStopping);
  5970. OnDeactivate();
  5971. }
  5972. void OBSBasic::ReplayBufferStart()
  5973. {
  5974. if (!outputHandler || !outputHandler->replayBuffer)
  5975. return;
  5976. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  5977. replayBufferButton->setChecked(true);
  5978. if (sysTrayReplayBuffer)
  5979. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5980. replayBufferStopping = false;
  5981. if (api)
  5982. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  5983. OnActivate();
  5984. UpdateReplayBuffer();
  5985. blog(LOG_INFO, REPLAY_BUFFER_START);
  5986. }
  5987. void OBSBasic::ReplayBufferSave()
  5988. {
  5989. if (!outputHandler || !outputHandler->replayBuffer)
  5990. return;
  5991. if (!outputHandler->ReplayBufferActive())
  5992. return;
  5993. calldata_t cd = {0};
  5994. proc_handler_t *ph =
  5995. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5996. proc_handler_call(ph, "save", &cd);
  5997. calldata_free(&cd);
  5998. }
  5999. void OBSBasic::ReplayBufferSaved()
  6000. {
  6001. if (!outputHandler || !outputHandler->replayBuffer)
  6002. return;
  6003. if (!outputHandler->ReplayBufferActive())
  6004. return;
  6005. calldata_t cd = {0};
  6006. proc_handler_t *ph =
  6007. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6008. proc_handler_call(ph, "get_last_replay", &cd);
  6009. QString path = QT_UTF8(calldata_string(&cd, "path"));
  6010. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(path);
  6011. ShowStatusBarMessage(msg);
  6012. calldata_free(&cd);
  6013. if (api)
  6014. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6015. AutoRemux(path);
  6016. }
  6017. void OBSBasic::ReplayBufferStop(int code)
  6018. {
  6019. if (!outputHandler || !outputHandler->replayBuffer)
  6020. return;
  6021. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  6022. replayBufferButton->setChecked(false);
  6023. if (sysTrayReplayBuffer)
  6024. sysTrayReplayBuffer->setText(replayBufferButton->text());
  6025. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6026. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6027. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6028. QTStr("Output.RecordFail.Unsupported"));
  6029. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6030. OBSMessageBox::warning(this,
  6031. QTStr("Output.RecordNoSpace.Title"),
  6032. QTStr("Output.RecordNoSpace.Msg"));
  6033. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6034. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6035. QTStr("Output.RecordError.Msg"));
  6036. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6037. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6038. QSystemTrayIcon::Warning);
  6039. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6040. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6041. QSystemTrayIcon::Warning);
  6042. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6043. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6044. QSystemTrayIcon::Warning);
  6045. }
  6046. if (api)
  6047. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6048. OnDeactivate();
  6049. UpdateReplayBuffer(false);
  6050. }
  6051. void OBSBasic::StartVirtualCam()
  6052. {
  6053. if (!outputHandler || !outputHandler->virtualCam)
  6054. return;
  6055. if (outputHandler->VirtualCamActive())
  6056. return;
  6057. if (disableOutputsRef)
  6058. return;
  6059. SaveProject();
  6060. if (!outputHandler->StartVirtualCam()) {
  6061. vcamButton->setChecked(false);
  6062. }
  6063. }
  6064. void OBSBasic::StopVirtualCam()
  6065. {
  6066. if (!outputHandler || !outputHandler->virtualCam)
  6067. return;
  6068. SaveProject();
  6069. if (outputHandler->VirtualCamActive())
  6070. outputHandler->StopVirtualCam();
  6071. OnDeactivate();
  6072. }
  6073. void OBSBasic::OnVirtualCamStart()
  6074. {
  6075. if (!outputHandler || !outputHandler->virtualCam)
  6076. return;
  6077. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  6078. if (sysTrayVirtualCam)
  6079. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6080. vcamButton->setChecked(true);
  6081. if (api)
  6082. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6083. OnActivate();
  6084. blog(LOG_INFO, VIRTUAL_CAM_START);
  6085. }
  6086. void OBSBasic::OnVirtualCamStop(int)
  6087. {
  6088. if (!outputHandler || !outputHandler->virtualCam)
  6089. return;
  6090. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  6091. if (sysTrayVirtualCam)
  6092. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6093. vcamButton->setChecked(false);
  6094. if (api)
  6095. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6096. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6097. OnDeactivate();
  6098. }
  6099. void OBSBasic::on_streamButton_clicked()
  6100. {
  6101. if (outputHandler->StreamingActive()) {
  6102. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6103. "WarnBeforeStoppingStream");
  6104. #if YOUTUBE_ENABLED
  6105. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6106. autoStopBroadcast) {
  6107. QMessageBox::StandardButton button = OBSMessageBox::question(
  6108. this, QTStr("ConfirmStop.Title"),
  6109. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6110. QMessageBox::Yes | QMessageBox::No,
  6111. QMessageBox::No);
  6112. if (button == QMessageBox::No) {
  6113. ui->streamButton->setChecked(true);
  6114. return;
  6115. }
  6116. confirm = false;
  6117. }
  6118. #endif
  6119. if (confirm && isVisible()) {
  6120. QMessageBox::StandardButton button =
  6121. OBSMessageBox::question(
  6122. this, QTStr("ConfirmStop.Title"),
  6123. QTStr("ConfirmStop.Text"),
  6124. QMessageBox::Yes | QMessageBox::No,
  6125. QMessageBox::No);
  6126. if (button == QMessageBox::No) {
  6127. ui->streamButton->setChecked(true);
  6128. return;
  6129. }
  6130. }
  6131. StopStreaming();
  6132. } else {
  6133. if (!UIValidation::NoSourcesConfirmation(this)) {
  6134. ui->streamButton->setChecked(false);
  6135. return;
  6136. }
  6137. Auth *auth = GetAuth();
  6138. auto action =
  6139. (auth && auth->external())
  6140. ? StreamSettingsAction::ContinueStream
  6141. : UIValidation::StreamSettingsConfirmation(
  6142. this, service);
  6143. switch (action) {
  6144. case StreamSettingsAction::ContinueStream:
  6145. break;
  6146. case StreamSettingsAction::OpenSettings:
  6147. on_action_Settings_triggered();
  6148. ui->streamButton->setChecked(false);
  6149. return;
  6150. case StreamSettingsAction::Cancel:
  6151. ui->streamButton->setChecked(false);
  6152. return;
  6153. }
  6154. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6155. "WarnBeforeStartingStream");
  6156. bool bwtest = false;
  6157. if (this->auth) {
  6158. OBSDataAutoRelease settings =
  6159. obs_service_get_settings(service);
  6160. bwtest = obs_data_get_bool(settings, "bwtest");
  6161. // Disable confirmation if this is going to open broadcast setup
  6162. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6163. !broadcastActive)
  6164. confirm = false;
  6165. }
  6166. if (bwtest && isVisible()) {
  6167. QMessageBox::StandardButton button =
  6168. OBSMessageBox::question(
  6169. this, QTStr("ConfirmBWTest.Title"),
  6170. QTStr("ConfirmBWTest.Text"));
  6171. if (button == QMessageBox::No) {
  6172. ui->streamButton->setChecked(false);
  6173. return;
  6174. }
  6175. } else if (confirm && isVisible()) {
  6176. QMessageBox::StandardButton button =
  6177. OBSMessageBox::question(
  6178. this, QTStr("ConfirmStart.Title"),
  6179. QTStr("ConfirmStart.Text"),
  6180. QMessageBox::Yes | QMessageBox::No,
  6181. QMessageBox::No);
  6182. if (button == QMessageBox::No) {
  6183. ui->streamButton->setChecked(false);
  6184. return;
  6185. }
  6186. }
  6187. StartStreaming();
  6188. }
  6189. }
  6190. void OBSBasic::on_recordButton_clicked()
  6191. {
  6192. if (outputHandler->RecordingActive()) {
  6193. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6194. "WarnBeforeStoppingRecord");
  6195. if (confirm && isVisible()) {
  6196. QMessageBox::StandardButton button =
  6197. OBSMessageBox::question(
  6198. this, QTStr("ConfirmStopRecord.Title"),
  6199. QTStr("ConfirmStopRecord.Text"),
  6200. QMessageBox::Yes | QMessageBox::No,
  6201. QMessageBox::No);
  6202. if (button == QMessageBox::No) {
  6203. ui->recordButton->setChecked(true);
  6204. return;
  6205. }
  6206. }
  6207. StopRecording();
  6208. } else {
  6209. if (!UIValidation::NoSourcesConfirmation(this)) {
  6210. ui->recordButton->setChecked(false);
  6211. return;
  6212. }
  6213. StartRecording();
  6214. }
  6215. }
  6216. void OBSBasic::VCamButtonClicked()
  6217. {
  6218. if (outputHandler->VirtualCamActive()) {
  6219. StopVirtualCam();
  6220. } else {
  6221. if (!UIValidation::NoSourcesConfirmation(this)) {
  6222. vcamButton->setChecked(false);
  6223. return;
  6224. }
  6225. StartVirtualCam();
  6226. }
  6227. }
  6228. void OBSBasic::on_settingsButton_clicked()
  6229. {
  6230. on_action_Settings_triggered();
  6231. }
  6232. void OBSBasic::on_actionHelpPortal_triggered()
  6233. {
  6234. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6235. QDesktopServices::openUrl(url);
  6236. }
  6237. void OBSBasic::on_actionWebsite_triggered()
  6238. {
  6239. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6240. QDesktopServices::openUrl(url);
  6241. }
  6242. void OBSBasic::on_actionDiscord_triggered()
  6243. {
  6244. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6245. QDesktopServices::openUrl(url);
  6246. }
  6247. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6248. {
  6249. char path[512];
  6250. int ret = GetConfigPath(path, 512, "obs-studio");
  6251. if (ret <= 0)
  6252. return;
  6253. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6254. }
  6255. void OBSBasic::on_actionShowProfileFolder_triggered()
  6256. {
  6257. char path[512];
  6258. int ret = GetProfilePath(path, 512, "");
  6259. if (ret <= 0)
  6260. return;
  6261. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6262. }
  6263. int OBSBasic::GetTopSelectedSourceItem()
  6264. {
  6265. QModelIndexList selectedItems =
  6266. ui->sources->selectionModel()->selectedIndexes();
  6267. return selectedItems.count() ? selectedItems[0].row() : -1;
  6268. }
  6269. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6270. {
  6271. return ui->sources->selectionModel()->selectedIndexes();
  6272. }
  6273. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  6274. {
  6275. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6276. UNUSED_PARAMETER(pos);
  6277. }
  6278. void OBSBasic::ProgramViewContextMenuRequested(const QPoint &)
  6279. {
  6280. QMenu popup(this);
  6281. QPointer<QMenu> studioProgramProjector;
  6282. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6283. AddProjectorMenuMonitors(studioProgramProjector, this,
  6284. SLOT(OpenStudioProgramProjector()));
  6285. popup.addMenu(studioProgramProjector);
  6286. QAction *studioProgramWindow =
  6287. popup.addAction(QTStr("StudioProgramWindow"), this,
  6288. SLOT(OpenStudioProgramWindow()));
  6289. popup.addAction(studioProgramWindow);
  6290. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6291. SLOT(ScreenshotProgram()));
  6292. popup.exec(QCursor::pos());
  6293. }
  6294. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  6295. {
  6296. QMenu popup(this);
  6297. delete previewProjectorMain;
  6298. QAction *action =
  6299. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6300. this, SLOT(TogglePreview()));
  6301. action->setCheckable(true);
  6302. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6303. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6304. AddProjectorMenuMonitors(previewProjectorMain, this,
  6305. SLOT(OpenPreviewProjector()));
  6306. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6307. SLOT(OpenPreviewWindow()));
  6308. popup.addMenu(previewProjectorMain);
  6309. popup.addAction(previewWindow);
  6310. popup.exec(QCursor::pos());
  6311. UNUSED_PARAMETER(pos);
  6312. }
  6313. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6314. {
  6315. #ifndef _WIN32
  6316. /* Make sure all dialogs are safely and successfully closed before
  6317. * switching the always on top mode due to the fact that windows all
  6318. * have to be recreated, so queue the actual toggle to happen after
  6319. * all events related to closing the dialogs have finished */
  6320. CloseDialogs();
  6321. #endif
  6322. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6323. Qt::QueuedConnection);
  6324. }
  6325. void OBSBasic::ToggleAlwaysOnTop()
  6326. {
  6327. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6328. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6329. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6330. show();
  6331. }
  6332. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6333. {
  6334. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6335. if (strcmp(val, "10") == 0) {
  6336. num = 10;
  6337. den = 1;
  6338. } else if (strcmp(val, "20") == 0) {
  6339. num = 20;
  6340. den = 1;
  6341. } else if (strcmp(val, "24 NTSC") == 0) {
  6342. num = 24000;
  6343. den = 1001;
  6344. } else if (strcmp(val, "25 PAL") == 0) {
  6345. num = 25;
  6346. den = 1;
  6347. } else if (strcmp(val, "29.97") == 0) {
  6348. num = 30000;
  6349. den = 1001;
  6350. } else if (strcmp(val, "48") == 0) {
  6351. num = 48;
  6352. den = 1;
  6353. } else if (strcmp(val, "50 PAL") == 0) {
  6354. num = 50;
  6355. den = 1;
  6356. } else if (strcmp(val, "59.94") == 0) {
  6357. num = 60000;
  6358. den = 1001;
  6359. } else if (strcmp(val, "60") == 0) {
  6360. num = 60;
  6361. den = 1;
  6362. } else {
  6363. num = 30;
  6364. den = 1;
  6365. }
  6366. }
  6367. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6368. {
  6369. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6370. den = 1;
  6371. }
  6372. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6373. {
  6374. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6375. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6376. }
  6377. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6378. {
  6379. num = 1000000000;
  6380. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6381. }
  6382. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6383. {
  6384. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6385. if (type == 1) //"Integer"
  6386. GetFPSInteger(num, den);
  6387. else if (type == 2) //"Fraction"
  6388. GetFPSFraction(num, den);
  6389. else if (false) //"Nanoseconds", currently not implemented
  6390. GetFPSNanoseconds(num, den);
  6391. else
  6392. GetFPSCommon(num, den);
  6393. }
  6394. config_t *OBSBasic::Config() const
  6395. {
  6396. return basicConfig;
  6397. }
  6398. void OBSBasic::UpdateEditMenu()
  6399. {
  6400. QModelIndexList items = GetAllSelectedSourceItems();
  6401. int count = items.count();
  6402. size_t filter_count = 0;
  6403. if (count == 1) {
  6404. OBSSceneItem sceneItem =
  6405. ui->sources->Get(GetTopSelectedSourceItem());
  6406. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6407. filter_count = obs_source_filter_count(source);
  6408. }
  6409. bool allowPastingDuplicate = !!clipboard.size();
  6410. for (size_t i = clipboard.size(); i > 0; i--) {
  6411. const size_t idx = i - 1;
  6412. OBSWeakSource &weak = clipboard[idx].weak_source;
  6413. if (obs_weak_source_expired(weak)) {
  6414. clipboard.erase(clipboard.begin() + idx);
  6415. continue;
  6416. }
  6417. OBSSourceAutoRelease strong =
  6418. obs_weak_source_get_source(weak.Get());
  6419. if (allowPastingDuplicate &&
  6420. obs_source_get_output_flags(strong) &
  6421. OBS_SOURCE_DO_NOT_DUPLICATE)
  6422. allowPastingDuplicate = false;
  6423. }
  6424. ui->actionCopySource->setEnabled(count > 0);
  6425. ui->actionEditTransform->setEnabled(count == 1);
  6426. ui->actionCopyTransform->setEnabled(count == 1);
  6427. ui->actionPasteTransform->setEnabled(hasCopiedTransform && count > 0);
  6428. ui->actionCopyFilters->setEnabled(filter_count > 0);
  6429. ui->actionPasteFilters->setEnabled(
  6430. !obs_weak_source_expired(copyFiltersSource) && count > 0);
  6431. ui->actionPasteRef->setEnabled(!!clipboard.size());
  6432. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6433. ui->actionMoveUp->setEnabled(count > 0);
  6434. ui->actionMoveDown->setEnabled(count > 0);
  6435. ui->actionMoveToTop->setEnabled(count > 0);
  6436. ui->actionMoveToBottom->setEnabled(count > 0);
  6437. bool canTransform = false;
  6438. for (int i = 0; i < count; i++) {
  6439. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  6440. if (!obs_sceneitem_locked(item))
  6441. canTransform = true;
  6442. }
  6443. ui->actionResetTransform->setEnabled(canTransform);
  6444. ui->actionRotate90CW->setEnabled(canTransform);
  6445. ui->actionRotate90CCW->setEnabled(canTransform);
  6446. ui->actionRotate180->setEnabled(canTransform);
  6447. ui->actionFlipHorizontal->setEnabled(canTransform);
  6448. ui->actionFlipVertical->setEnabled(canTransform);
  6449. ui->actionFitToScreen->setEnabled(canTransform);
  6450. ui->actionStretchToScreen->setEnabled(canTransform);
  6451. ui->actionCenterToScreen->setEnabled(canTransform);
  6452. ui->actionVerticalCenter->setEnabled(canTransform);
  6453. ui->actionHorizontalCenter->setEnabled(canTransform);
  6454. }
  6455. void OBSBasic::on_actionEditTransform_triggered()
  6456. {
  6457. if (transformWindow)
  6458. transformWindow->close();
  6459. if (!GetCurrentSceneItem())
  6460. return;
  6461. transformWindow = new OBSBasicTransform(this);
  6462. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  6463. &OBSBasicTransform::OnSceneChanged);
  6464. transformWindow->show();
  6465. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  6466. }
  6467. void OBSBasic::on_actionCopyTransform_triggered()
  6468. {
  6469. OBSSceneItem item = GetCurrentSceneItem();
  6470. obs_sceneitem_get_info(item, &copiedTransformInfo);
  6471. obs_sceneitem_get_crop(item, &copiedCropInfo);
  6472. ui->actionPasteTransform->setEnabled(true);
  6473. hasCopiedTransform = true;
  6474. }
  6475. void undo_redo(const std::string &data)
  6476. {
  6477. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  6478. OBSSourceAutoRelease source =
  6479. obs_get_source_by_name(obs_data_get_string(dat, "scene_name"));
  6480. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  6481. ->SetCurrentScene(source.Get(), true);
  6482. obs_scene_load_transform_states(data.c_str());
  6483. }
  6484. void OBSBasic::on_actionPasteTransform_triggered()
  6485. {
  6486. OBSDataAutoRelease wrapper =
  6487. obs_scene_save_transform_states(GetCurrentScene(), false);
  6488. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  6489. if (!obs_sceneitem_selected(item))
  6490. return true;
  6491. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  6492. obs_sceneitem_defer_update_begin(item);
  6493. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  6494. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  6495. obs_sceneitem_defer_update_end(item);
  6496. return true;
  6497. };
  6498. obs_scene_enum_items(GetCurrentScene(), func, this);
  6499. OBSDataAutoRelease rwrapper =
  6500. obs_scene_save_transform_states(GetCurrentScene(), false);
  6501. std::string undo_data(obs_data_get_json(wrapper));
  6502. std::string redo_data(obs_data_get_json(rwrapper));
  6503. undo_s.add_action(
  6504. QTStr("Undo.Transform.Paste")
  6505. .arg(obs_source_get_name(GetCurrentSceneSource())),
  6506. undo_redo, undo_redo, undo_data, redo_data);
  6507. }
  6508. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  6509. {
  6510. if (obs_sceneitem_is_group(item))
  6511. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  6512. if (!obs_sceneitem_selected(item))
  6513. return true;
  6514. if (obs_sceneitem_locked(item))
  6515. return true;
  6516. obs_sceneitem_defer_update_begin(item);
  6517. obs_transform_info info;
  6518. vec2_set(&info.pos, 0.0f, 0.0f);
  6519. vec2_set(&info.scale, 1.0f, 1.0f);
  6520. info.rot = 0.0f;
  6521. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  6522. info.bounds_type = OBS_BOUNDS_NONE;
  6523. info.bounds_alignment = OBS_ALIGN_CENTER;
  6524. vec2_set(&info.bounds, 0.0f, 0.0f);
  6525. obs_sceneitem_set_info(item, &info);
  6526. obs_sceneitem_crop crop = {};
  6527. obs_sceneitem_set_crop(item, &crop);
  6528. obs_sceneitem_defer_update_end(item);
  6529. UNUSED_PARAMETER(scene);
  6530. UNUSED_PARAMETER(param);
  6531. return true;
  6532. }
  6533. void OBSBasic::on_actionResetTransform_triggered()
  6534. {
  6535. obs_scene_t *scene = GetCurrentScene();
  6536. OBSDataAutoRelease wrapper =
  6537. obs_scene_save_transform_states(scene, false);
  6538. obs_scene_enum_items(scene, reset_tr, nullptr);
  6539. OBSDataAutoRelease rwrapper =
  6540. obs_scene_save_transform_states(scene, false);
  6541. std::string undo_data(obs_data_get_json(wrapper));
  6542. std::string redo_data(obs_data_get_json(rwrapper));
  6543. undo_s.add_action(
  6544. QTStr("Undo.Transform.Reset")
  6545. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  6546. undo_redo, undo_redo, undo_data, redo_data);
  6547. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  6548. }
  6549. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  6550. {
  6551. matrix4 boxTransform;
  6552. obs_sceneitem_get_box_transform(item, &boxTransform);
  6553. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  6554. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  6555. auto GetMinPos = [&](float x, float y) {
  6556. vec3 pos;
  6557. vec3_set(&pos, x, y, 0.0f);
  6558. vec3_transform(&pos, &pos, &boxTransform);
  6559. vec3_min(&tl, &tl, &pos);
  6560. vec3_max(&br, &br, &pos);
  6561. };
  6562. GetMinPos(0.0f, 0.0f);
  6563. GetMinPos(1.0f, 0.0f);
  6564. GetMinPos(0.0f, 1.0f);
  6565. GetMinPos(1.0f, 1.0f);
  6566. }
  6567. static vec3 GetItemTL(obs_sceneitem_t *item)
  6568. {
  6569. vec3 tl, br;
  6570. GetItemBox(item, tl, br);
  6571. return tl;
  6572. }
  6573. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  6574. {
  6575. vec3 newTL;
  6576. vec2 pos;
  6577. obs_sceneitem_get_pos(item, &pos);
  6578. newTL = GetItemTL(item);
  6579. pos.x += tl.x - newTL.x;
  6580. pos.y += tl.y - newTL.y;
  6581. obs_sceneitem_set_pos(item, &pos);
  6582. }
  6583. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  6584. void *param)
  6585. {
  6586. if (obs_sceneitem_is_group(item))
  6587. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  6588. param);
  6589. if (!obs_sceneitem_selected(item))
  6590. return true;
  6591. if (obs_sceneitem_locked(item))
  6592. return true;
  6593. float rot = *reinterpret_cast<float *>(param);
  6594. vec3 tl = GetItemTL(item);
  6595. rot += obs_sceneitem_get_rot(item);
  6596. if (rot >= 360.0f)
  6597. rot -= 360.0f;
  6598. else if (rot <= -360.0f)
  6599. rot += 360.0f;
  6600. obs_sceneitem_set_rot(item, rot);
  6601. obs_sceneitem_force_update_transform(item);
  6602. SetItemTL(item, tl);
  6603. UNUSED_PARAMETER(scene);
  6604. return true;
  6605. };
  6606. void OBSBasic::on_actionRotate90CW_triggered()
  6607. {
  6608. float f90CW = 90.0f;
  6609. OBSDataAutoRelease wrapper =
  6610. obs_scene_save_transform_states(GetCurrentScene(), false);
  6611. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  6612. OBSDataAutoRelease rwrapper =
  6613. obs_scene_save_transform_states(GetCurrentScene(), false);
  6614. std::string undo_data(obs_data_get_json(wrapper));
  6615. std::string redo_data(obs_data_get_json(rwrapper));
  6616. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6617. .arg(obs_source_get_name(obs_scene_get_source(
  6618. GetCurrentScene()))),
  6619. undo_redo, undo_redo, undo_data, redo_data);
  6620. }
  6621. void OBSBasic::on_actionRotate90CCW_triggered()
  6622. {
  6623. float f90CCW = -90.0f;
  6624. OBSDataAutoRelease wrapper =
  6625. obs_scene_save_transform_states(GetCurrentScene(), false);
  6626. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  6627. OBSDataAutoRelease rwrapper =
  6628. obs_scene_save_transform_states(GetCurrentScene(), false);
  6629. std::string undo_data(obs_data_get_json(wrapper));
  6630. std::string redo_data(obs_data_get_json(rwrapper));
  6631. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6632. .arg(obs_source_get_name(obs_scene_get_source(
  6633. GetCurrentScene()))),
  6634. undo_redo, undo_redo, undo_data, redo_data);
  6635. }
  6636. void OBSBasic::on_actionRotate180_triggered()
  6637. {
  6638. float f180 = 180.0f;
  6639. OBSDataAutoRelease wrapper =
  6640. obs_scene_save_transform_states(GetCurrentScene(), false);
  6641. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  6642. OBSDataAutoRelease rwrapper =
  6643. obs_scene_save_transform_states(GetCurrentScene(), false);
  6644. std::string undo_data(obs_data_get_json(wrapper));
  6645. std::string redo_data(obs_data_get_json(rwrapper));
  6646. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6647. .arg(obs_source_get_name(obs_scene_get_source(
  6648. GetCurrentScene()))),
  6649. undo_redo, undo_redo, undo_data, redo_data);
  6650. }
  6651. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  6652. void *param)
  6653. {
  6654. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  6655. if (obs_sceneitem_is_group(item))
  6656. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  6657. param);
  6658. if (!obs_sceneitem_selected(item))
  6659. return true;
  6660. if (obs_sceneitem_locked(item))
  6661. return true;
  6662. vec3 tl = GetItemTL(item);
  6663. vec2 scale;
  6664. obs_sceneitem_get_scale(item, &scale);
  6665. vec2_mul(&scale, &scale, &mul);
  6666. obs_sceneitem_set_scale(item, &scale);
  6667. obs_sceneitem_force_update_transform(item);
  6668. SetItemTL(item, tl);
  6669. UNUSED_PARAMETER(scene);
  6670. return true;
  6671. }
  6672. void OBSBasic::on_actionFlipHorizontal_triggered()
  6673. {
  6674. vec2 scale;
  6675. vec2_set(&scale, -1.0f, 1.0f);
  6676. OBSDataAutoRelease wrapper =
  6677. obs_scene_save_transform_states(GetCurrentScene(), false);
  6678. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6679. &scale);
  6680. OBSDataAutoRelease rwrapper =
  6681. obs_scene_save_transform_states(GetCurrentScene(), false);
  6682. std::string undo_data(obs_data_get_json(wrapper));
  6683. std::string redo_data(obs_data_get_json(rwrapper));
  6684. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  6685. .arg(obs_source_get_name(obs_scene_get_source(
  6686. GetCurrentScene()))),
  6687. undo_redo, undo_redo, undo_data, redo_data);
  6688. }
  6689. void OBSBasic::on_actionFlipVertical_triggered()
  6690. {
  6691. vec2 scale;
  6692. vec2_set(&scale, 1.0f, -1.0f);
  6693. OBSDataAutoRelease wrapper =
  6694. obs_scene_save_transform_states(GetCurrentScene(), false);
  6695. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6696. &scale);
  6697. OBSDataAutoRelease rwrapper =
  6698. obs_scene_save_transform_states(GetCurrentScene(), false);
  6699. std::string undo_data(obs_data_get_json(wrapper));
  6700. std::string redo_data(obs_data_get_json(rwrapper));
  6701. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  6702. .arg(obs_source_get_name(obs_scene_get_source(
  6703. GetCurrentScene()))),
  6704. undo_redo, undo_redo, undo_data, redo_data);
  6705. }
  6706. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  6707. void *param)
  6708. {
  6709. obs_bounds_type boundsType =
  6710. *reinterpret_cast<obs_bounds_type *>(param);
  6711. if (obs_sceneitem_is_group(item))
  6712. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  6713. param);
  6714. if (!obs_sceneitem_selected(item))
  6715. return true;
  6716. if (obs_sceneitem_locked(item))
  6717. return true;
  6718. obs_video_info ovi;
  6719. obs_get_video_info(&ovi);
  6720. obs_transform_info itemInfo;
  6721. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  6722. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  6723. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  6724. itemInfo.rot = 0.0f;
  6725. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  6726. float(ovi.base_height));
  6727. itemInfo.bounds_type = boundsType;
  6728. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  6729. obs_sceneitem_set_info(item, &itemInfo);
  6730. UNUSED_PARAMETER(scene);
  6731. return true;
  6732. }
  6733. void OBSBasic::on_actionFitToScreen_triggered()
  6734. {
  6735. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  6736. OBSDataAutoRelease wrapper =
  6737. obs_scene_save_transform_states(GetCurrentScene(), false);
  6738. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6739. &boundsType);
  6740. OBSDataAutoRelease rwrapper =
  6741. obs_scene_save_transform_states(GetCurrentScene(), false);
  6742. std::string undo_data(obs_data_get_json(wrapper));
  6743. std::string redo_data(obs_data_get_json(rwrapper));
  6744. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  6745. .arg(obs_source_get_name(obs_scene_get_source(
  6746. GetCurrentScene()))),
  6747. undo_redo, undo_redo, undo_data, redo_data);
  6748. }
  6749. void OBSBasic::on_actionStretchToScreen_triggered()
  6750. {
  6751. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  6752. OBSDataAutoRelease wrapper =
  6753. obs_scene_save_transform_states(GetCurrentScene(), false);
  6754. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6755. &boundsType);
  6756. OBSDataAutoRelease rwrapper =
  6757. obs_scene_save_transform_states(GetCurrentScene(), false);
  6758. std::string undo_data(obs_data_get_json(wrapper));
  6759. std::string redo_data(obs_data_get_json(rwrapper));
  6760. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  6761. .arg(obs_source_get_name(obs_scene_get_source(
  6762. GetCurrentScene()))),
  6763. undo_redo, undo_redo, undo_data, redo_data);
  6764. }
  6765. enum class CenterType {
  6766. Scene,
  6767. Vertical,
  6768. Horizontal,
  6769. };
  6770. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6771. {
  6772. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  6773. vec3 tl, br, itemCenter, screenCenter, offset;
  6774. obs_video_info ovi;
  6775. obs_transform_info oti;
  6776. if (obs_sceneitem_is_group(item))
  6777. obs_sceneitem_group_enum_items(item, center_to_scene,
  6778. &centerType);
  6779. if (!obs_sceneitem_selected(item))
  6780. return true;
  6781. if (obs_sceneitem_locked(item))
  6782. return true;
  6783. obs_get_video_info(&ovi);
  6784. obs_sceneitem_get_info(item, &oti);
  6785. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  6786. 0.0f);
  6787. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  6788. GetItemBox(item, tl, br);
  6789. vec3_sub(&itemCenter, &br, &tl);
  6790. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  6791. vec3_add(&itemCenter, &itemCenter, &tl);
  6792. vec3_sub(&offset, &screenCenter, &itemCenter);
  6793. vec3_add(&tl, &tl, &offset);
  6794. vec3 itemTL = GetItemTL(item);
  6795. if (centerType == CenterType::Vertical)
  6796. tl.x = itemTL.x;
  6797. else if (centerType == CenterType::Horizontal)
  6798. tl.y = itemTL.y;
  6799. SetItemTL(item, tl);
  6800. return true;
  6801. };
  6802. void OBSBasic::on_actionCenterToScreen_triggered()
  6803. {
  6804. CenterType centerType = CenterType::Scene;
  6805. OBSDataAutoRelease wrapper =
  6806. obs_scene_save_transform_states(GetCurrentScene(), false);
  6807. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6808. OBSDataAutoRelease rwrapper =
  6809. obs_scene_save_transform_states(GetCurrentScene(), false);
  6810. std::string undo_data(obs_data_get_json(wrapper));
  6811. std::string redo_data(obs_data_get_json(rwrapper));
  6812. undo_s.add_action(QTStr("Undo.Transform.Center")
  6813. .arg(obs_source_get_name(obs_scene_get_source(
  6814. GetCurrentScene()))),
  6815. undo_redo, undo_redo, undo_data, redo_data);
  6816. }
  6817. void OBSBasic::on_actionVerticalCenter_triggered()
  6818. {
  6819. CenterType centerType = CenterType::Vertical;
  6820. OBSDataAutoRelease wrapper =
  6821. obs_scene_save_transform_states(GetCurrentScene(), false);
  6822. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6823. OBSDataAutoRelease rwrapper =
  6824. obs_scene_save_transform_states(GetCurrentScene(), false);
  6825. std::string undo_data(obs_data_get_json(wrapper));
  6826. std::string redo_data(obs_data_get_json(rwrapper));
  6827. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  6828. .arg(obs_source_get_name(obs_scene_get_source(
  6829. GetCurrentScene()))),
  6830. undo_redo, undo_redo, undo_data, redo_data);
  6831. }
  6832. void OBSBasic::on_actionHorizontalCenter_triggered()
  6833. {
  6834. CenterType centerType = CenterType::Horizontal;
  6835. OBSDataAutoRelease wrapper =
  6836. obs_scene_save_transform_states(GetCurrentScene(), false);
  6837. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6838. OBSDataAutoRelease rwrapper =
  6839. obs_scene_save_transform_states(GetCurrentScene(), false);
  6840. std::string undo_data(obs_data_get_json(wrapper));
  6841. std::string redo_data(obs_data_get_json(rwrapper));
  6842. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  6843. .arg(obs_source_get_name(obs_scene_get_source(
  6844. GetCurrentScene()))),
  6845. undo_redo, undo_redo, undo_data, redo_data);
  6846. }
  6847. void OBSBasic::EnablePreviewDisplay(bool enable)
  6848. {
  6849. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  6850. ui->preview->setVisible(enable);
  6851. ui->previewDisabledWidget->setVisible(!enable);
  6852. }
  6853. void OBSBasic::TogglePreview()
  6854. {
  6855. previewEnabled = !previewEnabled;
  6856. EnablePreviewDisplay(previewEnabled);
  6857. }
  6858. void OBSBasic::EnablePreview()
  6859. {
  6860. if (previewProgramMode)
  6861. return;
  6862. previewEnabled = true;
  6863. EnablePreviewDisplay(true);
  6864. }
  6865. void OBSBasic::DisablePreview()
  6866. {
  6867. if (previewProgramMode)
  6868. return;
  6869. previewEnabled = false;
  6870. EnablePreviewDisplay(false);
  6871. }
  6872. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6873. {
  6874. if (obs_sceneitem_locked(item))
  6875. return true;
  6876. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  6877. struct vec2 pos;
  6878. if (!obs_sceneitem_selected(item)) {
  6879. if (obs_sceneitem_is_group(item)) {
  6880. struct vec3 offset3;
  6881. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  6882. struct matrix4 matrix;
  6883. obs_sceneitem_get_draw_transform(item, &matrix);
  6884. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  6885. matrix4_inv(&matrix, &matrix);
  6886. vec3_transform(&offset3, &offset3, &matrix);
  6887. struct vec2 new_offset;
  6888. vec2_set(&new_offset, offset3.x, offset3.y);
  6889. obs_sceneitem_group_enum_items(item, nudge_callback,
  6890. &new_offset);
  6891. }
  6892. return true;
  6893. }
  6894. obs_sceneitem_get_pos(item, &pos);
  6895. vec2_add(&pos, &pos, &offset);
  6896. obs_sceneitem_set_pos(item, &pos);
  6897. return true;
  6898. }
  6899. void OBSBasic::Nudge(int dist, MoveDir dir)
  6900. {
  6901. if (ui->preview->Locked())
  6902. return;
  6903. struct vec2 offset;
  6904. vec2_set(&offset, 0.0f, 0.0f);
  6905. switch (dir) {
  6906. case MoveDir::Up:
  6907. offset.y = (float)-dist;
  6908. break;
  6909. case MoveDir::Down:
  6910. offset.y = (float)dist;
  6911. break;
  6912. case MoveDir::Left:
  6913. offset.x = (float)-dist;
  6914. break;
  6915. case MoveDir::Right:
  6916. offset.x = (float)dist;
  6917. break;
  6918. }
  6919. if (!recent_nudge) {
  6920. recent_nudge = true;
  6921. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  6922. GetCurrentScene(), true);
  6923. std::string undo_data(obs_data_get_json(wrapper));
  6924. nudge_timer = new QTimer;
  6925. QObject::connect(
  6926. nudge_timer, &QTimer::timeout,
  6927. [this, &recent_nudge = recent_nudge, undo_data]() {
  6928. OBSDataAutoRelease rwrapper =
  6929. obs_scene_save_transform_states(
  6930. GetCurrentScene(), true);
  6931. std::string redo_data(
  6932. obs_data_get_json(rwrapper));
  6933. undo_s.add_action(
  6934. QTStr("Undo.Transform")
  6935. .arg(obs_source_get_name(
  6936. GetCurrentSceneSource())),
  6937. undo_redo, undo_redo, undo_data,
  6938. redo_data);
  6939. recent_nudge = false;
  6940. });
  6941. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  6942. &QTimer::deleteLater);
  6943. nudge_timer->setSingleShot(true);
  6944. }
  6945. if (nudge_timer) {
  6946. nudge_timer->stop();
  6947. nudge_timer->start(1000);
  6948. } else {
  6949. blog(LOG_ERROR, "No nudge timer!");
  6950. }
  6951. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  6952. }
  6953. void OBSBasic::NudgeUp()
  6954. {
  6955. Nudge(1, MoveDir::Up);
  6956. }
  6957. void OBSBasic::NudgeDown()
  6958. {
  6959. Nudge(1, MoveDir::Down);
  6960. }
  6961. void OBSBasic::NudgeLeft()
  6962. {
  6963. Nudge(1, MoveDir::Left);
  6964. }
  6965. void OBSBasic::NudgeRight()
  6966. {
  6967. Nudge(1, MoveDir::Right);
  6968. }
  6969. void OBSBasic::NudgeUpFar()
  6970. {
  6971. Nudge(10, MoveDir::Up);
  6972. }
  6973. void OBSBasic::NudgeDownFar()
  6974. {
  6975. Nudge(10, MoveDir::Down);
  6976. }
  6977. void OBSBasic::NudgeLeftFar()
  6978. {
  6979. Nudge(10, MoveDir::Left);
  6980. }
  6981. void OBSBasic::NudgeRightFar()
  6982. {
  6983. Nudge(10, MoveDir::Right);
  6984. }
  6985. void OBSBasic::DeleteProjector(OBSProjector *projector)
  6986. {
  6987. for (size_t i = 0; i < projectors.size(); i++) {
  6988. if (projectors[i] == projector) {
  6989. projectors[i]->deleteLater();
  6990. projectors.erase(projectors.begin() + i);
  6991. break;
  6992. }
  6993. }
  6994. }
  6995. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  6996. ProjectorType type)
  6997. {
  6998. /* seriously? 10 monitors? */
  6999. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7000. return nullptr;
  7001. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7002. "CloseExistingProjectors");
  7003. if (closeProjectors && monitor > -1) {
  7004. for (size_t i = projectors.size(); i > 0; i--) {
  7005. size_t idx = i - 1;
  7006. if (projectors[idx]->GetMonitor() == monitor)
  7007. DeleteProjector(projectors[idx]);
  7008. }
  7009. }
  7010. OBSProjector *projector =
  7011. new OBSProjector(nullptr, source, monitor, type);
  7012. projectors.emplace_back(projector);
  7013. return projector;
  7014. }
  7015. void OBSBasic::OpenStudioProgramProjector()
  7016. {
  7017. int monitor = sender()->property("monitor").toInt();
  7018. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7019. }
  7020. void OBSBasic::OpenPreviewProjector()
  7021. {
  7022. int monitor = sender()->property("monitor").toInt();
  7023. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7024. }
  7025. void OBSBasic::OpenSourceProjector()
  7026. {
  7027. int monitor = sender()->property("monitor").toInt();
  7028. OBSSceneItem item = GetCurrentSceneItem();
  7029. if (!item)
  7030. return;
  7031. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7032. ProjectorType::Source);
  7033. }
  7034. void OBSBasic::OpenMultiviewProjector()
  7035. {
  7036. int monitor = sender()->property("monitor").toInt();
  7037. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7038. }
  7039. void OBSBasic::OpenSceneProjector()
  7040. {
  7041. int monitor = sender()->property("monitor").toInt();
  7042. OBSScene scene = GetCurrentScene();
  7043. if (!scene)
  7044. return;
  7045. OpenProjector(obs_scene_get_source(scene), monitor,
  7046. ProjectorType::Scene);
  7047. }
  7048. void OBSBasic::OpenStudioProgramWindow()
  7049. {
  7050. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7051. }
  7052. void OBSBasic::OpenPreviewWindow()
  7053. {
  7054. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7055. }
  7056. void OBSBasic::OpenSourceWindow()
  7057. {
  7058. OBSSceneItem item = GetCurrentSceneItem();
  7059. if (!item)
  7060. return;
  7061. OBSSource source = obs_sceneitem_get_source(item);
  7062. OpenProjector(obs_sceneitem_get_source(item), -1,
  7063. ProjectorType::Source);
  7064. }
  7065. void OBSBasic::OpenMultiviewWindow()
  7066. {
  7067. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7068. }
  7069. void OBSBasic::OpenSceneWindow()
  7070. {
  7071. OBSScene scene = GetCurrentScene();
  7072. if (!scene)
  7073. return;
  7074. OBSSource source = obs_scene_get_source(scene);
  7075. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7076. }
  7077. void OBSBasic::OpenSavedProjectors()
  7078. {
  7079. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7080. OpenSavedProjector(info);
  7081. }
  7082. }
  7083. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7084. {
  7085. if (info) {
  7086. OBSProjector *projector = nullptr;
  7087. switch (info->type) {
  7088. case ProjectorType::Source:
  7089. case ProjectorType::Scene: {
  7090. OBSSourceAutoRelease source =
  7091. obs_get_source_by_name(info->name.c_str());
  7092. if (!source)
  7093. return;
  7094. projector = OpenProjector(source, info->monitor,
  7095. info->type);
  7096. break;
  7097. }
  7098. default: {
  7099. projector = OpenProjector(nullptr, info->monitor,
  7100. info->type);
  7101. break;
  7102. }
  7103. }
  7104. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7105. QByteArray byteArray = QByteArray::fromBase64(
  7106. QByteArray(info->geometry.c_str()));
  7107. projector->restoreGeometry(byteArray);
  7108. if (!WindowPositionValid(projector->normalGeometry())) {
  7109. QRect rect = QGuiApplication::primaryScreen()
  7110. ->geometry();
  7111. projector->setGeometry(QStyle::alignedRect(
  7112. Qt::LeftToRight, Qt::AlignCenter,
  7113. size(), rect));
  7114. }
  7115. if (info->alwaysOnTopOverridden)
  7116. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7117. true);
  7118. }
  7119. }
  7120. }
  7121. void OBSBasic::on_actionFullscreenInterface_triggered()
  7122. {
  7123. if (!isFullScreen())
  7124. showFullScreen();
  7125. else
  7126. showNormal();
  7127. }
  7128. void OBSBasic::UpdateTitleBar()
  7129. {
  7130. stringstream name;
  7131. const char *profile =
  7132. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7133. const char *sceneCollection = config_get_string(
  7134. App()->GlobalConfig(), "Basic", "SceneCollection");
  7135. name << "OBS ";
  7136. if (previewProgramMode)
  7137. name << "Studio ";
  7138. name << App()->GetVersionString();
  7139. if (App()->IsPortableMode())
  7140. name << " - Portable Mode";
  7141. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7142. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7143. setWindowTitle(QT_UTF8(name.str().c_str()));
  7144. }
  7145. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7146. {
  7147. char profiles_path[512];
  7148. const char *profile =
  7149. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7150. int ret;
  7151. if (!profile)
  7152. return -1;
  7153. if (!path)
  7154. return -1;
  7155. if (!file)
  7156. file = "";
  7157. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7158. if (ret <= 0)
  7159. return ret;
  7160. if (!*file)
  7161. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7162. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7163. }
  7164. void OBSBasic::on_resetDocks_triggered(bool force)
  7165. {
  7166. /* prune deleted extra docks */
  7167. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7168. if (!extraDocks[i]) {
  7169. extraDocks.removeAt(i);
  7170. }
  7171. }
  7172. if (extraDocks.size() && !force) {
  7173. QMessageBox::StandardButton button = QMessageBox::question(
  7174. this, QTStr("ResetUIWarning.Title"),
  7175. QTStr("ResetUIWarning.Text"));
  7176. if (button == QMessageBox::No)
  7177. return;
  7178. }
  7179. /* undock/hide/center extra docks */
  7180. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7181. if (extraDocks[i]) {
  7182. extraDocks[i]->setVisible(true);
  7183. extraDocks[i]->setFloating(true);
  7184. extraDocks[i]->move(frameGeometry().topLeft() +
  7185. rect().center() -
  7186. extraDocks[i]->rect().center());
  7187. extraDocks[i]->setVisible(false);
  7188. }
  7189. }
  7190. restoreState(startingDockLayout);
  7191. int cx = width();
  7192. int cy = height();
  7193. int cx22_5 = cx * 225 / 1000;
  7194. int cx5 = cx * 5 / 100;
  7195. cy = cy * 225 / 1000;
  7196. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  7197. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7198. ui->mixerDock, ui->transitionsDock,
  7199. ui->controlsDock};
  7200. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  7201. ui->scenesDock->setVisible(true);
  7202. ui->sourcesDock->setVisible(true);
  7203. ui->mixerDock->setVisible(true);
  7204. ui->transitionsDock->setVisible(true);
  7205. ui->controlsDock->setVisible(true);
  7206. statsDock->setVisible(false);
  7207. statsDock->setFloating(true);
  7208. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7209. resizeDocks(docks, sizes, Qt::Horizontal);
  7210. activateWindow();
  7211. }
  7212. void OBSBasic::on_lockDocks_toggled(bool lock)
  7213. {
  7214. QDockWidget::DockWidgetFeatures features =
  7215. lock ? QDockWidget::NoDockWidgetFeatures
  7216. : (QDockWidget::DockWidgetClosable |
  7217. QDockWidget::DockWidgetMovable |
  7218. QDockWidget::DockWidgetFloatable);
  7219. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7220. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7221. ui->scenesDock->setFeatures(mainFeatures);
  7222. ui->sourcesDock->setFeatures(mainFeatures);
  7223. ui->mixerDock->setFeatures(mainFeatures);
  7224. ui->transitionsDock->setFeatures(mainFeatures);
  7225. ui->controlsDock->setFeatures(mainFeatures);
  7226. statsDock->setFeatures(features);
  7227. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7228. if (!extraDocks[i]) {
  7229. extraDocks.removeAt(i);
  7230. } else {
  7231. extraDocks[i]->setFeatures(features);
  7232. }
  7233. }
  7234. }
  7235. void OBSBasic::on_resetUI_triggered()
  7236. {
  7237. on_resetDocks_triggered();
  7238. ui->toggleListboxToolbars->setChecked(true);
  7239. ui->toggleContextBar->setChecked(true);
  7240. ui->toggleSourceIcons->setChecked(true);
  7241. ui->toggleStatusBar->setChecked(true);
  7242. }
  7243. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7244. {
  7245. ui->sourcesToolbar->setVisible(visible);
  7246. ui->scenesToolbar->setVisible(visible);
  7247. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7248. "ShowListboxToolbars", visible);
  7249. }
  7250. void OBSBasic::ShowContextBar()
  7251. {
  7252. on_toggleContextBar_toggled(true);
  7253. }
  7254. void OBSBasic::HideContextBar()
  7255. {
  7256. on_toggleContextBar_toggled(false);
  7257. }
  7258. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7259. {
  7260. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7261. "ShowContextToolbars", visible);
  7262. this->ui->contextContainer->setVisible(visible);
  7263. UpdateContextBar(true);
  7264. }
  7265. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7266. {
  7267. ui->statusbar->setVisible(visible);
  7268. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7269. visible);
  7270. }
  7271. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7272. {
  7273. ui->sources->SetIconsVisible(visible);
  7274. if (advAudioWindow != nullptr)
  7275. advAudioWindow->SetIconsVisible(visible);
  7276. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7277. visible);
  7278. }
  7279. void OBSBasic::on_actionLockPreview_triggered()
  7280. {
  7281. ui->preview->ToggleLocked();
  7282. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7283. }
  7284. void OBSBasic::on_scalingMenu_aboutToShow()
  7285. {
  7286. obs_video_info ovi;
  7287. obs_get_video_info(&ovi);
  7288. QAction *action = ui->actionScaleCanvas;
  7289. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7290. text = text.arg(QString::number(ovi.base_width),
  7291. QString::number(ovi.base_height));
  7292. action->setText(text);
  7293. action = ui->actionScaleOutput;
  7294. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7295. text = text.arg(QString::number(ovi.output_width),
  7296. QString::number(ovi.output_height));
  7297. action->setText(text);
  7298. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7299. ovi.output_height == ovi.base_height));
  7300. UpdatePreviewScalingMenu();
  7301. }
  7302. void OBSBasic::on_actionScaleWindow_triggered()
  7303. {
  7304. ui->preview->SetFixedScaling(false);
  7305. ui->preview->ResetScrollingOffset();
  7306. emit ui->preview->DisplayResized();
  7307. }
  7308. void OBSBasic::on_actionScaleCanvas_triggered()
  7309. {
  7310. ui->preview->SetFixedScaling(true);
  7311. ui->preview->SetScalingLevel(0);
  7312. emit ui->preview->DisplayResized();
  7313. }
  7314. void OBSBasic::on_actionScaleOutput_triggered()
  7315. {
  7316. obs_video_info ovi;
  7317. obs_get_video_info(&ovi);
  7318. ui->preview->SetFixedScaling(true);
  7319. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7320. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7321. int32_t approxScalingLevel =
  7322. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7323. ui->preview->SetScalingLevel(approxScalingLevel);
  7324. ui->preview->SetScalingAmount(scalingAmount);
  7325. emit ui->preview->DisplayResized();
  7326. }
  7327. void OBSBasic::SetShowing(bool showing)
  7328. {
  7329. if (!showing && isVisible()) {
  7330. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7331. "geometry",
  7332. saveGeometry().toBase64().constData());
  7333. /* hide all visible child dialogs */
  7334. visDlgPositions.clear();
  7335. if (!visDialogs.isEmpty()) {
  7336. for (QDialog *dlg : visDialogs) {
  7337. visDlgPositions.append(dlg->pos());
  7338. dlg->hide();
  7339. }
  7340. }
  7341. if (showHide)
  7342. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7343. QTimer::singleShot(0, this, SLOT(hide()));
  7344. if (previewEnabled)
  7345. EnablePreviewDisplay(false);
  7346. #ifdef __APPLE__
  7347. EnableOSXDockIcon(false);
  7348. #endif
  7349. } else if (showing && !isVisible()) {
  7350. if (showHide)
  7351. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7352. QTimer::singleShot(0, this, SLOT(show()));
  7353. if (previewEnabled)
  7354. EnablePreviewDisplay(true);
  7355. #ifdef __APPLE__
  7356. EnableOSXDockIcon(true);
  7357. #endif
  7358. /* raise and activate window to ensure it is on top */
  7359. raise();
  7360. activateWindow();
  7361. /* show all child dialogs that was visible earlier */
  7362. if (!visDialogs.isEmpty()) {
  7363. for (int i = 0; i < visDialogs.size(); ++i) {
  7364. QDialog *dlg = visDialogs[i];
  7365. dlg->move(visDlgPositions[i]);
  7366. dlg->show();
  7367. }
  7368. }
  7369. /* Unminimize window if it was hidden to tray instead of task
  7370. * bar. */
  7371. if (sysTrayMinimizeToTray()) {
  7372. Qt::WindowStates state;
  7373. state = windowState() & ~Qt::WindowMinimized;
  7374. state |= Qt::WindowActive;
  7375. setWindowState(state);
  7376. }
  7377. }
  7378. }
  7379. void OBSBasic::ToggleShowHide()
  7380. {
  7381. bool showing = isVisible();
  7382. if (showing) {
  7383. /* check for modal dialogs */
  7384. EnumDialogs();
  7385. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7386. return;
  7387. }
  7388. SetShowing(!showing);
  7389. }
  7390. void OBSBasic::SystemTrayInit()
  7391. {
  7392. #ifdef __APPLE__
  7393. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  7394. trayIconFile.setIsMask(true);
  7395. #else
  7396. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  7397. #endif
  7398. trayIcon.reset(new QSystemTrayIcon(
  7399. QIcon::fromTheme("obs-tray", trayIconFile), this));
  7400. trayIcon->setToolTip("OBS Studio");
  7401. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  7402. sysTrayStream = new QAction(
  7403. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  7404. : QTStr("Basic.Main.StartStreaming"),
  7405. trayIcon.data());
  7406. sysTrayRecord = new QAction(
  7407. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  7408. : QTStr("Basic.Main.StartRecording"),
  7409. trayIcon.data());
  7410. sysTrayReplayBuffer = new QAction(
  7411. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  7412. : QTStr("Basic.Main.StartReplayBuffer"),
  7413. trayIcon.data());
  7414. sysTrayVirtualCam = new QAction(
  7415. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  7416. : QTStr("Basic.Main.StartVirtualCam"),
  7417. trayIcon.data());
  7418. exit = new QAction(QTStr("Exit"), trayIcon.data());
  7419. trayMenu = new QMenu;
  7420. previewProjector = new QMenu(QTStr("PreviewProjector"));
  7421. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  7422. AddProjectorMenuMonitors(previewProjector, this,
  7423. SLOT(OpenPreviewProjector()));
  7424. AddProjectorMenuMonitors(studioProgramProjector, this,
  7425. SLOT(OpenStudioProgramProjector()));
  7426. trayMenu->addAction(showHide);
  7427. trayMenu->addSeparator();
  7428. trayMenu->addMenu(previewProjector);
  7429. trayMenu->addMenu(studioProgramProjector);
  7430. trayMenu->addSeparator();
  7431. trayMenu->addAction(sysTrayStream);
  7432. trayMenu->addAction(sysTrayRecord);
  7433. trayMenu->addAction(sysTrayReplayBuffer);
  7434. trayMenu->addAction(sysTrayVirtualCam);
  7435. trayMenu->addSeparator();
  7436. trayMenu->addAction(exit);
  7437. trayIcon->setContextMenu(trayMenu);
  7438. trayIcon->show();
  7439. if (outputHandler && !outputHandler->replayBuffer)
  7440. sysTrayReplayBuffer->setEnabled(false);
  7441. sysTrayVirtualCam->setEnabled(vcamEnabled);
  7442. if (Active())
  7443. OnActivate(true);
  7444. connect(trayIcon.data(),
  7445. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  7446. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  7447. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  7448. connect(sysTrayStream, SIGNAL(triggered()), this,
  7449. SLOT(on_streamButton_clicked()));
  7450. connect(sysTrayRecord, SIGNAL(triggered()), this,
  7451. SLOT(on_recordButton_clicked()));
  7452. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  7453. &OBSBasic::ReplayBufferClicked);
  7454. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  7455. &OBSBasic::VCamButtonClicked);
  7456. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  7457. }
  7458. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  7459. {
  7460. // Refresh projector list
  7461. previewProjector->clear();
  7462. studioProgramProjector->clear();
  7463. AddProjectorMenuMonitors(previewProjector, this,
  7464. SLOT(OpenPreviewProjector()));
  7465. AddProjectorMenuMonitors(studioProgramProjector, this,
  7466. SLOT(OpenStudioProgramProjector()));
  7467. #ifdef __APPLE__
  7468. UNUSED_PARAMETER(reason);
  7469. #else
  7470. if (reason == QSystemTrayIcon::Trigger) {
  7471. EnablePreviewDisplay(previewEnabled && !isVisible());
  7472. ToggleShowHide();
  7473. }
  7474. #endif
  7475. }
  7476. void OBSBasic::SysTrayNotify(const QString &text,
  7477. QSystemTrayIcon::MessageIcon n)
  7478. {
  7479. if (trayIcon && trayIcon->isVisible() &&
  7480. QSystemTrayIcon::supportsMessages()) {
  7481. QSystemTrayIcon::MessageIcon icon =
  7482. QSystemTrayIcon::MessageIcon(n);
  7483. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  7484. }
  7485. }
  7486. void OBSBasic::SystemTray(bool firstStarted)
  7487. {
  7488. if (!QSystemTrayIcon::isSystemTrayAvailable())
  7489. return;
  7490. if (!trayIcon && !firstStarted)
  7491. return;
  7492. bool sysTrayWhenStarted = config_get_bool(
  7493. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  7494. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7495. "SysTrayEnabled");
  7496. if (firstStarted)
  7497. SystemTrayInit();
  7498. if (!sysTrayEnabled) {
  7499. trayIcon->hide();
  7500. } else {
  7501. trayIcon->show();
  7502. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  7503. EnablePreviewDisplay(false);
  7504. #ifdef __APPLE__
  7505. EnableOSXDockIcon(false);
  7506. #endif
  7507. opt_minimize_tray = false;
  7508. }
  7509. }
  7510. if (isVisible())
  7511. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7512. else
  7513. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7514. }
  7515. bool OBSBasic::sysTrayMinimizeToTray()
  7516. {
  7517. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  7518. "SysTrayMinimizeToTray");
  7519. }
  7520. void OBSBasic::on_actionMainUndo_triggered()
  7521. {
  7522. undo_s.undo();
  7523. }
  7524. void OBSBasic::on_actionMainRedo_triggered()
  7525. {
  7526. undo_s.redo();
  7527. }
  7528. void OBSBasic::on_actionCopySource_triggered()
  7529. {
  7530. clipboard.clear();
  7531. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  7532. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  7533. if (!item)
  7534. continue;
  7535. OBSSource source = obs_sceneitem_get_source(item);
  7536. SourceCopyInfo copyInfo;
  7537. copyInfo.weak_source = OBSGetWeakRef(source);
  7538. obs_sceneitem_get_info(item, &copyInfo.transform);
  7539. obs_sceneitem_get_crop(item, &copyInfo.crop);
  7540. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  7541. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  7542. copyInfo.visible = obs_sceneitem_visible(item);
  7543. clipboard.push_back(copyInfo);
  7544. }
  7545. UpdateEditMenu();
  7546. }
  7547. void OBSBasic::on_actionPasteRef_triggered()
  7548. {
  7549. OBSSource scene_source = GetCurrentSceneSource();
  7550. OBSData undo_data = BackupScene(scene_source);
  7551. OBSScene scene = GetCurrentScene();
  7552. undo_s.push_disabled();
  7553. for (size_t i = clipboard.size(); i > 0; i--) {
  7554. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7555. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  7556. if (!source)
  7557. continue;
  7558. const char *name = obs_source_get_name(source);
  7559. /* do not allow duplicate refs of the same group in the same
  7560. * scene */
  7561. if (!!obs_scene_get_group(scene, name)) {
  7562. continue;
  7563. }
  7564. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  7565. }
  7566. undo_s.pop_disabled();
  7567. QString action_name = QTStr("Undo.PasteSourceRef");
  7568. const char *scene_name = obs_source_get_name(scene_source);
  7569. OBSData redo_data = BackupScene(scene_source);
  7570. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7571. redo_data);
  7572. }
  7573. void OBSBasic::on_actionPasteDup_triggered()
  7574. {
  7575. OBSSource scene_source = GetCurrentSceneSource();
  7576. OBSData undo_data = BackupScene(scene_source);
  7577. undo_s.push_disabled();
  7578. for (size_t i = clipboard.size(); i > 0; i--) {
  7579. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7580. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  7581. }
  7582. undo_s.pop_disabled();
  7583. QString action_name = QTStr("Undo.PasteSource");
  7584. const char *scene_name = obs_source_get_name(scene_source);
  7585. OBSData redo_data = BackupScene(scene_source);
  7586. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7587. redo_data);
  7588. }
  7589. void OBSBasic::AudioMixerCopyFilters()
  7590. {
  7591. QAction *action = reinterpret_cast<QAction *>(sender());
  7592. VolControl *vol = action->property("volControl").value<VolControl *>();
  7593. obs_source_t *source = vol->GetSource();
  7594. copyFiltersSource = obs_source_get_weak_source(source);
  7595. }
  7596. void OBSBasic::AudioMixerPasteFilters()
  7597. {
  7598. QAction *action = reinterpret_cast<QAction *>(sender());
  7599. VolControl *vol = action->property("volControl").value<VolControl *>();
  7600. obs_source_t *dstSource = vol->GetSource();
  7601. OBSSourceAutoRelease source =
  7602. obs_weak_source_get_source(copyFiltersSource);
  7603. if (source == dstSource)
  7604. return;
  7605. obs_source_copy_filters(dstSource, source);
  7606. }
  7607. void OBSBasic::SceneCopyFilters()
  7608. {
  7609. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  7610. }
  7611. void OBSBasic::ScenePasteFilters()
  7612. {
  7613. OBSSourceAutoRelease source =
  7614. obs_weak_source_get_source(copyFiltersSource);
  7615. OBSSource dstSource = GetCurrentSceneSource();
  7616. if (source == dstSource)
  7617. return;
  7618. obs_source_copy_filters(dstSource, source);
  7619. }
  7620. void OBSBasic::on_actionCopyFilters_triggered()
  7621. {
  7622. OBSSceneItem item = GetCurrentSceneItem();
  7623. if (!item)
  7624. return;
  7625. OBSSource source = obs_sceneitem_get_source(item);
  7626. copyFiltersSource = obs_source_get_weak_source(source);
  7627. ui->actionPasteFilters->setEnabled(true);
  7628. }
  7629. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  7630. obs_source_t *source,
  7631. obs_data_array_t *undo_array,
  7632. obs_data_array_t *redo_array)
  7633. {
  7634. auto undo_redo = [this](const std::string &json) {
  7635. OBSDataAutoRelease data =
  7636. obs_data_create_from_json(json.c_str());
  7637. OBSDataArrayAutoRelease array =
  7638. obs_data_get_array(data, "array");
  7639. const char *name = obs_data_get_string(data, "name");
  7640. OBSSourceAutoRelease source = obs_get_source_by_name(name);
  7641. obs_source_restore_filters(source, array);
  7642. if (filters)
  7643. filters->UpdateSource(source);
  7644. };
  7645. const char *name = obs_source_get_name(source);
  7646. OBSDataAutoRelease undo_data = obs_data_create();
  7647. OBSDataAutoRelease redo_data = obs_data_create();
  7648. obs_data_set_array(undo_data, "array", undo_array);
  7649. obs_data_set_array(redo_data, "array", redo_array);
  7650. obs_data_set_string(undo_data, "name", name);
  7651. obs_data_set_string(redo_data, "name", name);
  7652. undo_s.add_action(text, undo_redo, undo_redo,
  7653. obs_data_get_json(undo_data),
  7654. obs_data_get_json(redo_data));
  7655. }
  7656. void OBSBasic::on_actionPasteFilters_triggered()
  7657. {
  7658. OBSSourceAutoRelease source =
  7659. obs_weak_source_get_source(copyFiltersSource);
  7660. OBSSceneItem sceneItem = GetCurrentSceneItem();
  7661. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  7662. if (source == dstSource)
  7663. return;
  7664. OBSDataArrayAutoRelease undo_array =
  7665. obs_source_backup_filters(dstSource);
  7666. obs_source_copy_filters(dstSource, source);
  7667. OBSDataArrayAutoRelease redo_array =
  7668. obs_source_backup_filters(dstSource);
  7669. const char *srcName = obs_source_get_name(source);
  7670. const char *dstName = obs_source_get_name(dstSource);
  7671. QString text =
  7672. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  7673. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  7674. redo_array);
  7675. }
  7676. static void ConfirmColor(SourceTree *sources, const QColor &color,
  7677. QModelIndexList selectedItems)
  7678. {
  7679. for (int x = 0; x < selectedItems.count(); x++) {
  7680. SourceTreeItem *treeItem =
  7681. sources->GetItemWidget(selectedItems[x].row());
  7682. treeItem->setStyleSheet("background: " +
  7683. color.name(QColor::HexArgb));
  7684. treeItem->style()->unpolish(treeItem);
  7685. treeItem->style()->polish(treeItem);
  7686. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  7687. OBSDataAutoRelease privData =
  7688. obs_sceneitem_get_private_settings(sceneItem);
  7689. obs_data_set_int(privData, "color-preset", 1);
  7690. obs_data_set_string(privData, "color",
  7691. QT_TO_UTF8(color.name(QColor::HexArgb)));
  7692. }
  7693. }
  7694. void OBSBasic::ColorChange()
  7695. {
  7696. QModelIndexList selectedItems =
  7697. ui->sources->selectionModel()->selectedIndexes();
  7698. QAction *action = qobject_cast<QAction *>(sender());
  7699. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  7700. if (selectedItems.count() == 0)
  7701. return;
  7702. if (colorButton) {
  7703. int preset = colorButton->property("bgColor").value<int>();
  7704. for (int x = 0; x < selectedItems.count(); x++) {
  7705. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  7706. selectedItems[x].row());
  7707. treeItem->setStyleSheet("");
  7708. treeItem->setProperty("bgColor", preset);
  7709. treeItem->style()->unpolish(treeItem);
  7710. treeItem->style()->polish(treeItem);
  7711. OBSSceneItem sceneItem =
  7712. ui->sources->Get(selectedItems[x].row());
  7713. OBSDataAutoRelease privData =
  7714. obs_sceneitem_get_private_settings(sceneItem);
  7715. obs_data_set_int(privData, "color-preset", preset + 1);
  7716. obs_data_set_string(privData, "color", "");
  7717. }
  7718. for (int i = 1; i < 9; i++) {
  7719. stringstream button;
  7720. button << "preset" << i;
  7721. QPushButton *cButton =
  7722. colorButton->parentWidget()
  7723. ->findChild<QPushButton *>(
  7724. button.str().c_str());
  7725. cButton->setStyleSheet("border: 1px solid black");
  7726. }
  7727. colorButton->setStyleSheet("border: 2px solid black");
  7728. } else if (action) {
  7729. int preset = action->property("bgColor").value<int>();
  7730. if (preset == 1) {
  7731. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  7732. SourceTreeItem *curTreeItem =
  7733. GetItemWidgetFromSceneItem(curSceneItem);
  7734. OBSDataAutoRelease curPrivData =
  7735. obs_sceneitem_get_private_settings(
  7736. curSceneItem);
  7737. int oldPreset =
  7738. obs_data_get_int(curPrivData, "color-preset");
  7739. const QString oldSheet = curTreeItem->styleSheet();
  7740. auto liveChangeColor = [=](const QColor &color) {
  7741. if (color.isValid()) {
  7742. curTreeItem->setStyleSheet(
  7743. "background: " +
  7744. color.name(QColor::HexArgb));
  7745. }
  7746. };
  7747. auto changedColor = [=](const QColor &color) {
  7748. if (color.isValid()) {
  7749. ConfirmColor(ui->sources, color,
  7750. selectedItems);
  7751. }
  7752. };
  7753. auto rejected = [=]() {
  7754. if (oldPreset == 1) {
  7755. curTreeItem->setStyleSheet(oldSheet);
  7756. curTreeItem->setProperty("bgColor", 0);
  7757. } else if (oldPreset == 0) {
  7758. curTreeItem->setStyleSheet(
  7759. "background: none");
  7760. curTreeItem->setProperty("bgColor", 0);
  7761. } else {
  7762. curTreeItem->setStyleSheet("");
  7763. curTreeItem->setProperty("bgColor",
  7764. oldPreset - 1);
  7765. }
  7766. curTreeItem->style()->unpolish(curTreeItem);
  7767. curTreeItem->style()->polish(curTreeItem);
  7768. };
  7769. QColorDialog::ColorDialogOptions options =
  7770. QColorDialog::ShowAlphaChannel;
  7771. const char *oldColor =
  7772. obs_data_get_string(curPrivData, "color");
  7773. const char *customColor = *oldColor != 0 ? oldColor
  7774. : "#55FF0000";
  7775. #ifndef _WIN32
  7776. options |= QColorDialog::DontUseNativeDialog;
  7777. #endif
  7778. QColorDialog *colorDialog = new QColorDialog(this);
  7779. colorDialog->setOptions(options);
  7780. colorDialog->setCurrentColor(QColor(customColor));
  7781. connect(colorDialog, &QColorDialog::currentColorChanged,
  7782. liveChangeColor);
  7783. connect(colorDialog, &QColorDialog::colorSelected,
  7784. changedColor);
  7785. connect(colorDialog, &QColorDialog::rejected, rejected);
  7786. colorDialog->open();
  7787. } else {
  7788. for (int x = 0; x < selectedItems.count(); x++) {
  7789. SourceTreeItem *treeItem =
  7790. ui->sources->GetItemWidget(
  7791. selectedItems[x].row());
  7792. treeItem->setStyleSheet("background: none");
  7793. treeItem->setProperty("bgColor", preset);
  7794. treeItem->style()->unpolish(treeItem);
  7795. treeItem->style()->polish(treeItem);
  7796. OBSSceneItem sceneItem = ui->sources->Get(
  7797. selectedItems[x].row());
  7798. OBSDataAutoRelease privData =
  7799. obs_sceneitem_get_private_settings(
  7800. sceneItem);
  7801. obs_data_set_int(privData, "color-preset",
  7802. preset);
  7803. obs_data_set_string(privData, "color", "");
  7804. }
  7805. }
  7806. }
  7807. }
  7808. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  7809. {
  7810. int i = 0;
  7811. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  7812. OBSSceneItem item = ui->sources->Get(i);
  7813. int64_t id = obs_sceneitem_get_id(sceneItem);
  7814. while (treeItem && obs_sceneitem_get_id(item) != id) {
  7815. i++;
  7816. treeItem = ui->sources->GetItemWidget(i);
  7817. item = ui->sources->Get(i);
  7818. }
  7819. if (treeItem)
  7820. return treeItem;
  7821. return nullptr;
  7822. }
  7823. void OBSBasic::on_autoConfigure_triggered()
  7824. {
  7825. AutoConfig test(this);
  7826. test.setModal(true);
  7827. test.show();
  7828. test.exec();
  7829. }
  7830. void OBSBasic::on_stats_triggered()
  7831. {
  7832. if (!stats.isNull()) {
  7833. stats->show();
  7834. stats->raise();
  7835. return;
  7836. }
  7837. OBSBasicStats *statsDlg;
  7838. statsDlg = new OBSBasicStats(nullptr);
  7839. statsDlg->show();
  7840. stats = statsDlg;
  7841. }
  7842. void OBSBasic::on_actionShowAbout_triggered()
  7843. {
  7844. if (about)
  7845. about->close();
  7846. about = new OBSAbout(this);
  7847. about->show();
  7848. about->setAttribute(Qt::WA_DeleteOnClose, true);
  7849. }
  7850. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  7851. {
  7852. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  7853. action->setProperty("uuid", dock->property("uuid").toString());
  7854. action->setCheckable(true);
  7855. assignDockToggle(dock, action);
  7856. extraDocks.push_back(dock);
  7857. bool lock = ui->lockDocks->isChecked();
  7858. QDockWidget::DockWidgetFeatures features =
  7859. lock ? QDockWidget::NoDockWidgetFeatures
  7860. : (QDockWidget::DockWidgetClosable |
  7861. QDockWidget::DockWidgetMovable |
  7862. QDockWidget::DockWidgetFloatable);
  7863. dock->setFeatures(features);
  7864. /* prune deleted docks */
  7865. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7866. if (!extraDocks[i]) {
  7867. extraDocks.removeAt(i);
  7868. }
  7869. }
  7870. return action;
  7871. }
  7872. OBSBasic *OBSBasic::Get()
  7873. {
  7874. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  7875. }
  7876. bool OBSBasic::StreamingActive()
  7877. {
  7878. if (!outputHandler)
  7879. return false;
  7880. return outputHandler->StreamingActive();
  7881. }
  7882. bool OBSBasic::RecordingActive()
  7883. {
  7884. if (!outputHandler)
  7885. return false;
  7886. return outputHandler->RecordingActive();
  7887. }
  7888. bool OBSBasic::ReplayBufferActive()
  7889. {
  7890. if (!outputHandler)
  7891. return false;
  7892. return outputHandler->ReplayBufferActive();
  7893. }
  7894. bool OBSBasic::VirtualCamActive()
  7895. {
  7896. if (!outputHandler)
  7897. return false;
  7898. return outputHandler->VirtualCamActive();
  7899. }
  7900. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  7901. : QStyledItemDelegate(parent)
  7902. {
  7903. }
  7904. void SceneRenameDelegate::setEditorData(QWidget *editor,
  7905. const QModelIndex &index) const
  7906. {
  7907. QStyledItemDelegate::setEditorData(editor, index);
  7908. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7909. if (lineEdit)
  7910. lineEdit->selectAll();
  7911. }
  7912. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  7913. {
  7914. if (event->type() == QEvent::KeyPress) {
  7915. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  7916. if (keyEvent->key() == Qt::Key_Escape) {
  7917. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7918. if (lineEdit)
  7919. lineEdit->undo();
  7920. }
  7921. }
  7922. return QStyledItemDelegate::eventFilter(editor, event);
  7923. }
  7924. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  7925. {
  7926. if (!error.isEmpty())
  7927. return;
  7928. patronJson = QT_TO_UTF8(text);
  7929. }
  7930. void OBSBasic::PauseRecording()
  7931. {
  7932. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7933. os_atomic_load_bool(&recording_paused))
  7934. return;
  7935. obs_output_t *output = outputHandler->fileOutput;
  7936. if (obs_output_pause(output, true)) {
  7937. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  7938. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  7939. pause->blockSignals(true);
  7940. pause->setChecked(true);
  7941. pause->blockSignals(false);
  7942. ui->statusbar->RecordingPaused();
  7943. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  7944. if (trayIcon && trayIcon->isVisible()) {
  7945. #ifdef __APPLE__
  7946. QIcon trayIconFile =
  7947. QIcon(":/res/images/obs_paused_macos.svg");
  7948. trayIconFile.setIsMask(true);
  7949. #else
  7950. QIcon trayIconFile =
  7951. QIcon(":/res/images/obs_paused.png");
  7952. #endif
  7953. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  7954. trayIconFile));
  7955. }
  7956. os_atomic_set_bool(&recording_paused, true);
  7957. if (replay)
  7958. replay->setEnabled(false);
  7959. if (api)
  7960. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  7961. if (os_atomic_load_bool(&replaybuf_active))
  7962. ShowReplayBufferPauseWarning();
  7963. }
  7964. }
  7965. void OBSBasic::UnpauseRecording()
  7966. {
  7967. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7968. !os_atomic_load_bool(&recording_paused))
  7969. return;
  7970. obs_output_t *output = outputHandler->fileOutput;
  7971. if (obs_output_pause(output, false)) {
  7972. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  7973. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  7974. pause->blockSignals(true);
  7975. pause->setChecked(false);
  7976. pause->blockSignals(false);
  7977. ui->statusbar->RecordingUnpaused();
  7978. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  7979. if (trayIcon && trayIcon->isVisible()) {
  7980. #ifdef __APPLE__
  7981. QIcon trayIconFile =
  7982. QIcon(":/res/images/tray_active_macos.svg");
  7983. trayIconFile.setIsMask(true);
  7984. #else
  7985. QIcon trayIconFile =
  7986. QIcon(":/res/images/tray_active.png");
  7987. #endif
  7988. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  7989. trayIconFile));
  7990. }
  7991. os_atomic_set_bool(&recording_paused, false);
  7992. if (replay)
  7993. replay->setEnabled(true);
  7994. if (api)
  7995. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  7996. }
  7997. }
  7998. void OBSBasic::PauseToggled()
  7999. {
  8000. if (!pause || !outputHandler || !outputHandler->fileOutput)
  8001. return;
  8002. obs_output_t *output = outputHandler->fileOutput;
  8003. bool enable = !obs_output_paused(output);
  8004. if (enable)
  8005. PauseRecording();
  8006. else
  8007. UnpauseRecording();
  8008. }
  8009. void OBSBasic::UpdatePause(bool activate)
  8010. {
  8011. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  8012. pause.reset();
  8013. return;
  8014. }
  8015. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8016. bool adv = astrcmpi(mode, "Advanced") == 0;
  8017. bool shared;
  8018. if (adv) {
  8019. const char *recType =
  8020. config_get_string(basicConfig, "AdvOut", "RecType");
  8021. if (astrcmpi(recType, "FFmpeg") == 0) {
  8022. shared = config_get_bool(basicConfig, "AdvOut",
  8023. "FFOutputToFile");
  8024. } else {
  8025. const char *recordEncoder = config_get_string(
  8026. basicConfig, "AdvOut", "RecEncoder");
  8027. shared = astrcmpi(recordEncoder, "none") == 0;
  8028. }
  8029. } else {
  8030. const char *quality = config_get_string(
  8031. basicConfig, "SimpleOutput", "RecQuality");
  8032. shared = strcmp(quality, "Stream") == 0;
  8033. }
  8034. if (!shared) {
  8035. pause.reset(new QPushButton());
  8036. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8037. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8038. pause->setCheckable(true);
  8039. pause->setChecked(false);
  8040. pause->setProperty("themeID",
  8041. QVariant(QStringLiteral("pauseIconSmall")));
  8042. QSizePolicy sp;
  8043. sp.setHeightForWidth(true);
  8044. pause->setSizePolicy(sp);
  8045. connect(pause.data(), &QAbstractButton::clicked, this,
  8046. &OBSBasic::PauseToggled);
  8047. ui->recordingLayout->addWidget(pause.data());
  8048. } else {
  8049. pause.reset();
  8050. }
  8051. }
  8052. void OBSBasic::UpdateReplayBuffer(bool activate)
  8053. {
  8054. if (!activate || !outputHandler ||
  8055. !outputHandler->ReplayBufferActive()) {
  8056. replay.reset();
  8057. return;
  8058. }
  8059. replay.reset(new QPushButton());
  8060. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  8061. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  8062. replay->setChecked(false);
  8063. replay->setProperty("themeID",
  8064. QVariant(QStringLiteral("replayIconSmall")));
  8065. QSizePolicy sp;
  8066. sp.setHeightForWidth(true);
  8067. replay->setSizePolicy(sp);
  8068. connect(replay.data(), &QAbstractButton::clicked, this,
  8069. &OBSBasic::ReplayBufferSave);
  8070. replayLayout->addWidget(replay.data());
  8071. setTabOrder(replayLayout->itemAt(0)->widget(),
  8072. replayLayout->itemAt(1)->widget());
  8073. setTabOrder(replayLayout->itemAt(1)->widget(),
  8074. ui->buttonsVLayout->itemAt(3)->widget());
  8075. }
  8076. #define MBYTE (1024ULL * 1024ULL)
  8077. #define MBYTES_LEFT_STOP_REC 50ULL
  8078. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8079. const char *OBSBasic::GetCurrentOutputPath()
  8080. {
  8081. const char *path = nullptr;
  8082. const char *mode = config_get_string(Config(), "Output", "Mode");
  8083. if (strcmp(mode, "Advanced") == 0) {
  8084. const char *advanced_mode =
  8085. config_get_string(Config(), "AdvOut", "RecType");
  8086. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8087. path = config_get_string(Config(), "AdvOut",
  8088. "FFFilePath");
  8089. } else {
  8090. path = config_get_string(Config(), "AdvOut",
  8091. "RecFilePath");
  8092. }
  8093. } else {
  8094. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8095. }
  8096. return path;
  8097. }
  8098. void OBSBasic::OutputPathInvalidMessage()
  8099. {
  8100. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8101. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8102. QTStr("Output.BadPath.Text"));
  8103. }
  8104. bool OBSBasic::OutputPathValid()
  8105. {
  8106. const char *mode = config_get_string(Config(), "Output", "Mode");
  8107. if (strcmp(mode, "Advanced") == 0) {
  8108. const char *advanced_mode =
  8109. config_get_string(Config(), "AdvOut", "RecType");
  8110. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8111. bool is_local = config_get_bool(Config(), "AdvOut",
  8112. "FFOutputToFile");
  8113. if (!is_local)
  8114. return true;
  8115. }
  8116. }
  8117. const char *path = GetCurrentOutputPath();
  8118. return path && *path && QDir(path).exists();
  8119. }
  8120. void OBSBasic::DiskSpaceMessage()
  8121. {
  8122. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8123. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8124. QTStr("Output.RecordNoSpace.Msg"));
  8125. }
  8126. bool OBSBasic::LowDiskSpace()
  8127. {
  8128. const char *path;
  8129. path = GetCurrentOutputPath();
  8130. if (!path)
  8131. return false;
  8132. uint64_t num_bytes = os_get_free_disk_space(path);
  8133. if (num_bytes < (MAX_BYTES_LEFT))
  8134. return true;
  8135. else
  8136. return false;
  8137. }
  8138. void OBSBasic::CheckDiskSpaceRemaining()
  8139. {
  8140. if (LowDiskSpace()) {
  8141. StopRecording();
  8142. StopReplayBuffer();
  8143. DiskSpaceMessage();
  8144. }
  8145. }
  8146. void OBSBasic::ScenesReordered()
  8147. {
  8148. OBSProjector::UpdateMultiviewProjectors();
  8149. }
  8150. void OBSBasic::ResetStatsHotkey()
  8151. {
  8152. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8153. foreach(OBSBasicStats * s, list) s->Reset();
  8154. }
  8155. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  8156. {
  8157. QWidget *widget = childAt(pos);
  8158. const char *className = nullptr;
  8159. QString objName;
  8160. if (widget != nullptr) {
  8161. className = widget->metaObject()->className();
  8162. objName = widget->objectName();
  8163. }
  8164. QPoint globalPos = mapToGlobal(pos);
  8165. if (className && strstr(className, "Dock") != nullptr &&
  8166. !objName.isEmpty()) {
  8167. if (objName.compare("scenesDock") == 0) {
  8168. ui->scenes->customContextMenuRequested(globalPos);
  8169. } else if (objName.compare("sourcesDock") == 0) {
  8170. ui->sources->customContextMenuRequested(globalPos);
  8171. } else if (objName.compare("mixerDock") == 0) {
  8172. StackedMixerAreaContextMenuRequested();
  8173. }
  8174. } else if (!className) {
  8175. ui->menuDocks->exec(globalPos);
  8176. }
  8177. }
  8178. void OBSBasic::UpdateProjectorHideCursor()
  8179. {
  8180. for (size_t i = 0; i < projectors.size(); i++)
  8181. projectors[i]->SetHideCursor();
  8182. }
  8183. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8184. {
  8185. for (size_t i = 0; i < projectors.size(); i++)
  8186. SetAlwaysOnTop(projectors[i], top);
  8187. }
  8188. void OBSBasic::ResetProjectors()
  8189. {
  8190. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8191. ClearProjectors();
  8192. LoadSavedProjectors(savedProjectorList);
  8193. OpenSavedProjectors();
  8194. }
  8195. void OBSBasic::on_sourcePropertiesButton_clicked()
  8196. {
  8197. on_actionSourceProperties_triggered();
  8198. }
  8199. void OBSBasic::on_sourceFiltersButton_clicked()
  8200. {
  8201. OpenFilters();
  8202. }
  8203. void OBSBasic::on_sourceInteractButton_clicked()
  8204. {
  8205. on_actionInteract_triggered();
  8206. }
  8207. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8208. {
  8209. ui->statusbar->clearMessage();
  8210. ui->statusbar->showMessage(message, 10000);
  8211. }
  8212. void OBSBasic::UpdatePreviewSafeAreas()
  8213. {
  8214. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8215. "ShowSafeAreas");
  8216. }
  8217. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8218. {
  8219. if (!SetDisplayAffinitySupported())
  8220. return;
  8221. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8222. "BasicWindow",
  8223. "HideOBSWindowsFromCapture");
  8224. // Don't hide projectors, those are designed to be visible / captured
  8225. if (window->property("isOBSProjectorWindow") == true)
  8226. return;
  8227. #ifdef _WIN32
  8228. HWND hwnd = (HWND)window->winId();
  8229. DWORD curAffinity;
  8230. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  8231. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  8232. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  8233. else if (!hideFromCapture && curAffinity != WDA_NONE)
  8234. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  8235. }
  8236. #else
  8237. // TODO: Implement for other platforms if possible. Don't forget to
  8238. // implement SetDisplayAffinitySupported too!
  8239. UNUSED_PARAMETER(hideFromCapture);
  8240. #endif
  8241. }