window-basic-main.cpp 273 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059
  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,
  2532. "wasapi_process_output_capture") ==
  2533. 0) {
  2534. ApplicationAudioCaptureToolbar *c =
  2535. new ApplicationAudioCaptureToolbar(
  2536. ui->emptySpace, source);
  2537. c->Init();
  2538. ui->emptySpace->layout()->addWidget(c);
  2539. } else if (strcmp(id, "window_capture") == 0 ||
  2540. strcmp(id, "xcomposite_input") == 0) {
  2541. WindowCaptureToolbar *c =
  2542. new WindowCaptureToolbar(ui->emptySpace,
  2543. source);
  2544. c->Init();
  2545. ui->emptySpace->layout()->addWidget(c);
  2546. } else if (strcmp(id, "monitor_capture") == 0 ||
  2547. strcmp(id, "display_capture") == 0 ||
  2548. strcmp(id, "xshm_input") == 0) {
  2549. DisplayCaptureToolbar *c =
  2550. new DisplayCaptureToolbar(
  2551. ui->emptySpace, source);
  2552. c->Init();
  2553. ui->emptySpace->layout()->addWidget(c);
  2554. } else if (strcmp(id, "dshow_input") == 0) {
  2555. DeviceCaptureToolbar *c =
  2556. new DeviceCaptureToolbar(ui->emptySpace,
  2557. source);
  2558. ui->emptySpace->layout()->addWidget(c);
  2559. } else if (strcmp(id, "game_capture") == 0) {
  2560. GameCaptureToolbar *c = new GameCaptureToolbar(
  2561. ui->emptySpace, source);
  2562. ui->emptySpace->layout()->addWidget(c);
  2563. } else if (strcmp(id, "image_source") == 0) {
  2564. ImageSourceToolbar *c = new ImageSourceToolbar(
  2565. ui->emptySpace, source);
  2566. ui->emptySpace->layout()->addWidget(c);
  2567. } else if (strcmp(id, "color_source") == 0) {
  2568. ColorSourceToolbar *c = new ColorSourceToolbar(
  2569. ui->emptySpace, source);
  2570. ui->emptySpace->layout()->addWidget(c);
  2571. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2572. strcmp(id, "text_gdiplus") == 0) {
  2573. TextSourceToolbar *c = new TextSourceToolbar(
  2574. ui->emptySpace, source);
  2575. ui->emptySpace->layout()->addWidget(c);
  2576. }
  2577. } else if (contextBarSize == ContextBarSize_Minimized) {
  2578. ClearContextBar();
  2579. }
  2580. QIcon icon;
  2581. if (strcmp(id, "scene") == 0)
  2582. icon = GetSceneIcon();
  2583. else if (strcmp(id, "group") == 0)
  2584. icon = GetGroupIcon();
  2585. else
  2586. icon = GetSourceIcon(id);
  2587. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2588. ui->contextSourceIcon->setPixmap(pixmap);
  2589. ui->contextSourceIconSpacer->hide();
  2590. ui->contextSourceIcon->show();
  2591. const char *name = obs_source_get_name(source);
  2592. ui->contextSourceLabel->setText(name);
  2593. ui->sourceFiltersButton->setEnabled(true);
  2594. ui->sourcePropertiesButton->setEnabled(
  2595. obs_source_configurable(source));
  2596. } else {
  2597. ClearContextBar();
  2598. ui->contextSourceIcon->hide();
  2599. ui->contextSourceIconSpacer->show();
  2600. ui->contextSourceLabel->setText(
  2601. QTStr("ContextBar.NoSelectedSource"));
  2602. ui->sourceFiltersButton->setEnabled(false);
  2603. ui->sourcePropertiesButton->setEnabled(false);
  2604. ui->sourceInteractButton->setVisible(false);
  2605. }
  2606. if (contextBarSize == ContextBarSize_Normal) {
  2607. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  2608. ui->sourceFiltersButton->setText(QTStr("Filters"));
  2609. ui->sourceInteractButton->setText(QTStr("Interact"));
  2610. } else {
  2611. ui->sourcePropertiesButton->setText("");
  2612. ui->sourceFiltersButton->setText("");
  2613. ui->sourceInteractButton->setText("");
  2614. }
  2615. }
  2616. static inline bool SourceMixerHidden(obs_source_t *source)
  2617. {
  2618. OBSDataAutoRelease priv_settings =
  2619. obs_source_get_private_settings(source);
  2620. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2621. return hidden;
  2622. }
  2623. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2624. {
  2625. OBSDataAutoRelease priv_settings =
  2626. obs_source_get_private_settings(source);
  2627. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2628. }
  2629. void OBSBasic::GetAudioSourceFilters()
  2630. {
  2631. QAction *action = reinterpret_cast<QAction *>(sender());
  2632. VolControl *vol = action->property("volControl").value<VolControl *>();
  2633. obs_source_t *source = vol->GetSource();
  2634. CreateFiltersWindow(source);
  2635. }
  2636. void OBSBasic::GetAudioSourceProperties()
  2637. {
  2638. QAction *action = reinterpret_cast<QAction *>(sender());
  2639. VolControl *vol = action->property("volControl").value<VolControl *>();
  2640. obs_source_t *source = vol->GetSource();
  2641. CreatePropertiesWindow(source);
  2642. }
  2643. void OBSBasic::HideAudioControl()
  2644. {
  2645. QAction *action = reinterpret_cast<QAction *>(sender());
  2646. VolControl *vol = action->property("volControl").value<VolControl *>();
  2647. obs_source_t *source = vol->GetSource();
  2648. if (!SourceMixerHidden(source)) {
  2649. SetSourceMixerHidden(source, true);
  2650. DeactivateAudioSource(source);
  2651. }
  2652. }
  2653. void OBSBasic::UnhideAllAudioControls()
  2654. {
  2655. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2656. {
  2657. if (!obs_source_active(source))
  2658. return true;
  2659. if (!SourceMixerHidden(source))
  2660. return true;
  2661. SetSourceMixerHidden(source, false);
  2662. ActivateAudioSource(source);
  2663. return true;
  2664. };
  2665. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2666. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2667. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2668. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2669. }
  2670. void OBSBasic::ToggleHideMixer()
  2671. {
  2672. OBSSceneItem item = GetCurrentSceneItem();
  2673. OBSSource source = obs_sceneitem_get_source(item);
  2674. if (!SourceMixerHidden(source)) {
  2675. SetSourceMixerHidden(source, true);
  2676. DeactivateAudioSource(source);
  2677. } else {
  2678. SetSourceMixerHidden(source, false);
  2679. ActivateAudioSource(source);
  2680. }
  2681. }
  2682. void OBSBasic::MixerRenameSource()
  2683. {
  2684. QAction *action = reinterpret_cast<QAction *>(sender());
  2685. VolControl *vol = action->property("volControl").value<VolControl *>();
  2686. OBSSource source = vol->GetSource();
  2687. const char *prevName = obs_source_get_name(source);
  2688. for (;;) {
  2689. string name;
  2690. bool accepted = NameDialog::AskForName(
  2691. this, QTStr("Basic.Main.MixerRename.Title"),
  2692. QTStr("Basic.Main.MixerRename.Text"), name,
  2693. QT_UTF8(prevName));
  2694. if (!accepted)
  2695. return;
  2696. if (name.empty()) {
  2697. OBSMessageBox::warning(this,
  2698. QTStr("NoNameEntered.Title"),
  2699. QTStr("NoNameEntered.Text"));
  2700. continue;
  2701. }
  2702. OBSSourceAutoRelease sourceTest =
  2703. obs_get_source_by_name(name.c_str());
  2704. if (sourceTest) {
  2705. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2706. QTStr("NameExists.Text"));
  2707. continue;
  2708. }
  2709. obs_source_set_name(source, name.c_str());
  2710. break;
  2711. }
  2712. }
  2713. static inline bool SourceVolumeLocked(obs_source_t *source)
  2714. {
  2715. OBSDataAutoRelease priv_settings =
  2716. obs_source_get_private_settings(source);
  2717. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2718. return lock;
  2719. }
  2720. void OBSBasic::LockVolumeControl(bool lock)
  2721. {
  2722. QAction *action = reinterpret_cast<QAction *>(sender());
  2723. VolControl *vol = action->property("volControl").value<VolControl *>();
  2724. obs_source_t *source = vol->GetSource();
  2725. OBSDataAutoRelease priv_settings =
  2726. obs_source_get_private_settings(source);
  2727. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2728. vol->EnableSlider(!lock);
  2729. }
  2730. void OBSBasic::VolControlContextMenu()
  2731. {
  2732. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2733. /* ------------------- */
  2734. QAction lockAction(QTStr("LockVolume"), this);
  2735. lockAction.setCheckable(true);
  2736. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2737. QAction hideAction(QTStr("Hide"), this);
  2738. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2739. QAction mixerRenameAction(QTStr("Rename"), this);
  2740. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2741. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2742. QAction filtersAction(QTStr("Filters"), this);
  2743. QAction propertiesAction(QTStr("Properties"), this);
  2744. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2745. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2746. toggleControlLayoutAction.setCheckable(true);
  2747. toggleControlLayoutAction.setChecked(config_get_bool(
  2748. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2749. /* ------------------- */
  2750. connect(&hideAction, &QAction::triggered, this,
  2751. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2752. connect(&unhideAllAction, &QAction::triggered, this,
  2753. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2754. connect(&lockAction, &QAction::toggled, this,
  2755. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2756. connect(&mixerRenameAction, &QAction::triggered, this,
  2757. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2758. connect(&copyFiltersAction, &QAction::triggered, this,
  2759. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2760. connect(&pasteFiltersAction, &QAction::triggered, this,
  2761. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2762. connect(&filtersAction, &QAction::triggered, this,
  2763. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2764. connect(&propertiesAction, &QAction::triggered, this,
  2765. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2766. connect(&advPropAction, &QAction::triggered, this,
  2767. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2768. Qt::DirectConnection);
  2769. /* ------------------- */
  2770. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2771. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2772. /* ------------------- */
  2773. hideAction.setProperty("volControl",
  2774. QVariant::fromValue<VolControl *>(vol));
  2775. lockAction.setProperty("volControl",
  2776. QVariant::fromValue<VolControl *>(vol));
  2777. mixerRenameAction.setProperty("volControl",
  2778. QVariant::fromValue<VolControl *>(vol));
  2779. copyFiltersAction.setProperty("volControl",
  2780. QVariant::fromValue<VolControl *>(vol));
  2781. pasteFiltersAction.setProperty("volControl",
  2782. QVariant::fromValue<VolControl *>(vol));
  2783. filtersAction.setProperty("volControl",
  2784. QVariant::fromValue<VolControl *>(vol));
  2785. propertiesAction.setProperty("volControl",
  2786. QVariant::fromValue<VolControl *>(vol));
  2787. /* ------------------- */
  2788. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  2789. 0);
  2790. OBSSourceAutoRelease source =
  2791. obs_weak_source_get_source(copyFiltersSource);
  2792. if (source) {
  2793. pasteFiltersAction.setEnabled(true);
  2794. } else {
  2795. pasteFiltersAction.setEnabled(false);
  2796. }
  2797. QMenu popup;
  2798. vol->SetContextMenu(&popup);
  2799. popup.addAction(&lockAction);
  2800. popup.addSeparator();
  2801. popup.addAction(&unhideAllAction);
  2802. popup.addAction(&hideAction);
  2803. popup.addAction(&mixerRenameAction);
  2804. popup.addSeparator();
  2805. popup.addAction(&copyFiltersAction);
  2806. popup.addAction(&pasteFiltersAction);
  2807. popup.addSeparator();
  2808. popup.addAction(&toggleControlLayoutAction);
  2809. popup.addSeparator();
  2810. popup.addAction(&filtersAction);
  2811. popup.addAction(&propertiesAction);
  2812. popup.addAction(&advPropAction);
  2813. popup.exec(QCursor::pos());
  2814. vol->SetContextMenu(nullptr);
  2815. }
  2816. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2817. {
  2818. StackedMixerAreaContextMenuRequested();
  2819. }
  2820. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2821. {
  2822. StackedMixerAreaContextMenuRequested();
  2823. }
  2824. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2825. {
  2826. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2827. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2828. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2829. toggleControlLayoutAction.setCheckable(true);
  2830. toggleControlLayoutAction.setChecked(config_get_bool(
  2831. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2832. /* ------------------- */
  2833. connect(&unhideAllAction, &QAction::triggered, this,
  2834. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2835. connect(&advPropAction, &QAction::triggered, this,
  2836. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2837. Qt::DirectConnection);
  2838. /* ------------------- */
  2839. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2840. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2841. /* ------------------- */
  2842. QMenu popup;
  2843. popup.addAction(&unhideAllAction);
  2844. popup.addSeparator();
  2845. popup.addAction(&toggleControlLayoutAction);
  2846. popup.addSeparator();
  2847. popup.addAction(&advPropAction);
  2848. popup.exec(QCursor::pos());
  2849. }
  2850. void OBSBasic::ToggleMixerLayout(bool vertical)
  2851. {
  2852. if (vertical) {
  2853. ui->stackedMixerArea->setMinimumSize(180, 220);
  2854. ui->stackedMixerArea->setCurrentIndex(1);
  2855. } else {
  2856. ui->stackedMixerArea->setMinimumSize(220, 0);
  2857. ui->stackedMixerArea->setCurrentIndex(0);
  2858. }
  2859. }
  2860. void OBSBasic::ToggleVolControlLayout()
  2861. {
  2862. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2863. "VerticalVolControl");
  2864. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2865. vertical);
  2866. ToggleMixerLayout(vertical);
  2867. // We need to store it so we can delete current and then add
  2868. // at the right order
  2869. vector<OBSSource> sources;
  2870. for (size_t i = 0; i != volumes.size(); i++)
  2871. sources.emplace_back(volumes[i]->GetSource());
  2872. ClearVolumeControls();
  2873. for (const auto &source : sources)
  2874. ActivateAudioSource(source);
  2875. }
  2876. void OBSBasic::ActivateAudioSource(OBSSource source)
  2877. {
  2878. if (SourceMixerHidden(source))
  2879. return;
  2880. if (!obs_source_active(source))
  2881. return;
  2882. if (!obs_source_audio_active(source))
  2883. return;
  2884. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2885. "VerticalVolControl");
  2886. VolControl *vol = new VolControl(source, true, vertical);
  2887. vol->EnableSlider(!SourceVolumeLocked(source));
  2888. double meterDecayRate =
  2889. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2890. vol->SetMeterDecayRate(meterDecayRate);
  2891. uint32_t peakMeterTypeIdx =
  2892. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2893. enum obs_peak_meter_type peakMeterType;
  2894. switch (peakMeterTypeIdx) {
  2895. case 0:
  2896. peakMeterType = SAMPLE_PEAK_METER;
  2897. break;
  2898. case 1:
  2899. peakMeterType = TRUE_PEAK_METER;
  2900. break;
  2901. default:
  2902. peakMeterType = SAMPLE_PEAK_METER;
  2903. break;
  2904. }
  2905. vol->setPeakMeterType(peakMeterType);
  2906. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2907. connect(vol, &QWidget::customContextMenuRequested, this,
  2908. &OBSBasic::VolControlContextMenu);
  2909. connect(vol, &VolControl::ConfigClicked, this,
  2910. &OBSBasic::VolControlContextMenu);
  2911. InsertQObjectByName(volumes, vol);
  2912. for (auto volume : volumes) {
  2913. if (vertical)
  2914. ui->vVolControlLayout->addWidget(volume);
  2915. else
  2916. ui->hVolControlLayout->addWidget(volume);
  2917. }
  2918. }
  2919. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2920. {
  2921. for (size_t i = 0; i < volumes.size(); i++) {
  2922. if (volumes[i]->GetSource() == source) {
  2923. delete volumes[i];
  2924. volumes.erase(volumes.begin() + i);
  2925. break;
  2926. }
  2927. }
  2928. }
  2929. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2930. {
  2931. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2932. !obs_source_is_group(source)) {
  2933. int count = ui->scenes->count();
  2934. if (count == 1) {
  2935. OBSMessageBox::information(this,
  2936. QTStr("FinalScene.Title"),
  2937. QTStr("FinalScene.Text"));
  2938. return false;
  2939. }
  2940. }
  2941. const char *name = obs_source_get_name(source);
  2942. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  2943. QMessageBox remove_source(this);
  2944. remove_source.setText(text);
  2945. QPushButton *Yes =
  2946. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2947. remove_source.setDefaultButton(Yes);
  2948. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2949. remove_source.setIcon(QMessageBox::Question);
  2950. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2951. remove_source.exec();
  2952. return Yes == remove_source.clickedButton();
  2953. }
  2954. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2955. #if defined(ENABLE_SPARKLE_UPDATER)
  2956. void init_sparkle_updater(bool update_to_undeployed);
  2957. void trigger_sparkle_update();
  2958. #endif
  2959. void OBSBasic::TimedCheckForUpdates()
  2960. {
  2961. if (App()->IsUpdaterDisabled())
  2962. return;
  2963. if (!config_get_bool(App()->GlobalConfig(), "General",
  2964. "EnableAutoUpdates"))
  2965. return;
  2966. #if defined(ENABLE_SPARKLE_UPDATER)
  2967. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2968. "UpdateToUndeployed"));
  2969. #elif _WIN32
  2970. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2971. "LastUpdateCheck");
  2972. uint32_t lastVersion =
  2973. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2974. if (lastVersion < LIBOBS_API_VER) {
  2975. lastUpdate = 0;
  2976. config_set_int(App()->GlobalConfig(), "General",
  2977. "LastUpdateCheck", 0);
  2978. }
  2979. long long t = (long long)time(nullptr);
  2980. long long secs = t - lastUpdate;
  2981. if (secs > UPDATE_CHECK_INTERVAL)
  2982. CheckForUpdates(false);
  2983. #endif
  2984. }
  2985. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2986. {
  2987. #if defined(ENABLE_SPARKLE_UPDATER)
  2988. trigger_sparkle_update();
  2989. #elif _WIN32
  2990. ui->actionCheckForUpdates->setEnabled(false);
  2991. if (updateCheckThread && updateCheckThread->isRunning())
  2992. return;
  2993. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2994. updateCheckThread->start();
  2995. #endif
  2996. UNUSED_PARAMETER(manualUpdate);
  2997. }
  2998. void OBSBasic::updateCheckFinished()
  2999. {
  3000. ui->actionCheckForUpdates->setEnabled(true);
  3001. }
  3002. void OBSBasic::DuplicateSelectedScene()
  3003. {
  3004. OBSScene curScene = GetCurrentScene();
  3005. if (!curScene)
  3006. return;
  3007. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3008. QString format{obs_source_get_name(curSceneSource)};
  3009. format += " %1";
  3010. int i = 2;
  3011. QString placeHolderText = format.arg(i);
  3012. OBSSourceAutoRelease source = nullptr;
  3013. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3014. placeHolderText = format.arg(++i);
  3015. }
  3016. for (;;) {
  3017. string name;
  3018. bool accepted = NameDialog::AskForName(
  3019. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3020. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3021. placeHolderText);
  3022. if (!accepted)
  3023. return;
  3024. if (name.empty()) {
  3025. OBSMessageBox::warning(this,
  3026. QTStr("NoNameEntered.Title"),
  3027. QTStr("NoNameEntered.Text"));
  3028. continue;
  3029. }
  3030. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3031. if (source) {
  3032. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3033. QTStr("NameExists.Text"));
  3034. obs_source_release(source);
  3035. continue;
  3036. }
  3037. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3038. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3039. source = obs_scene_get_source(scene);
  3040. SetCurrentScene(source, true);
  3041. auto undo = [](const std::string &data) {
  3042. OBSSourceAutoRelease source =
  3043. obs_get_source_by_name(data.c_str());
  3044. obs_source_remove(source);
  3045. };
  3046. auto redo = [this, name](const std::string &data) {
  3047. OBSSourceAutoRelease source =
  3048. obs_get_source_by_name(data.c_str());
  3049. obs_scene_t *scene = obs_scene_from_source(source);
  3050. scene = obs_scene_duplicate(scene, name.c_str(),
  3051. OBS_SCENE_DUP_REFS);
  3052. source = obs_scene_get_source(scene);
  3053. SetCurrentScene(source.Get(), true);
  3054. };
  3055. undo_s.add_action(
  3056. QTStr("Undo.Scene.Duplicate")
  3057. .arg(obs_source_get_name(source)),
  3058. undo, redo, obs_source_get_name(source),
  3059. obs_source_get_name(obs_scene_get_source(curScene)));
  3060. break;
  3061. }
  3062. }
  3063. static bool save_undo_source_enum(obs_scene_t *scene, obs_sceneitem_t *item,
  3064. void *p)
  3065. {
  3066. UNUSED_PARAMETER(scene);
  3067. obs_source_t *source = obs_sceneitem_get_source(item);
  3068. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3069. return true;
  3070. obs_data_array_t *array = (obs_data_array_t *)p;
  3071. /* check if the source is already stored in the array */
  3072. const char *name = obs_source_get_name(source);
  3073. const size_t count = obs_data_array_count(array);
  3074. for (size_t i = 0; i < count; i++) {
  3075. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3076. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3077. return true;
  3078. }
  3079. if (obs_source_is_group(source))
  3080. obs_scene_enum_items(obs_group_from_source(source),
  3081. save_undo_source_enum, p);
  3082. OBSDataAutoRelease source_data = obs_save_source(source);
  3083. obs_data_array_push_back(array, source_data);
  3084. return true;
  3085. }
  3086. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3087. {
  3088. obs_source_remove(source);
  3089. auto cb = [](void *unused, obs_source_t *source) {
  3090. UNUSED_PARAMETER(unused);
  3091. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3092. obs_scene_prune_sources(obs_scene_from_source(source));
  3093. return true;
  3094. };
  3095. obs_enum_scenes(cb, NULL);
  3096. }
  3097. void OBSBasic::RemoveSelectedScene()
  3098. {
  3099. OBSScene scene = GetCurrentScene();
  3100. obs_source_t *source = obs_scene_get_source(scene);
  3101. if (!source || !QueryRemoveSource(source)) {
  3102. return;
  3103. }
  3104. /* ------------------------------ */
  3105. /* save all sources in scene */
  3106. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3107. obs_data_array_create();
  3108. obs_scene_enum_items(scene, save_undo_source_enum,
  3109. sources_in_deleted_scene);
  3110. OBSDataAutoRelease scene_data = obs_save_source(source);
  3111. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3112. /* ----------------------------------------------- */
  3113. /* save all scenes and groups the scene is used in */
  3114. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3115. obs_data_array_create();
  3116. struct other_scenes_cb_data {
  3117. obs_source_t *oldScene;
  3118. obs_data_array_t *scene_used_in_other_scenes;
  3119. } other_scenes_cb_data;
  3120. other_scenes_cb_data.oldScene = source;
  3121. other_scenes_cb_data.scene_used_in_other_scenes =
  3122. scene_used_in_other_scenes;
  3123. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3124. struct other_scenes_cb_data *data =
  3125. (struct other_scenes_cb_data *)data_ptr;
  3126. if (strcmp(obs_source_get_name(scene),
  3127. obs_source_get_name(data->oldScene)) == 0)
  3128. return true;
  3129. obs_sceneitem_t *item = obs_scene_find_source(
  3130. obs_group_or_scene_from_source(scene),
  3131. obs_source_get_name(data->oldScene));
  3132. if (item) {
  3133. OBSDataAutoRelease scene_data =
  3134. obs_save_source(obs_scene_get_source(
  3135. obs_sceneitem_get_scene(item)));
  3136. obs_data_array_push_back(
  3137. data->scene_used_in_other_scenes, scene_data);
  3138. }
  3139. return true;
  3140. };
  3141. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3142. /* --------------------------- */
  3143. /* undo/redo */
  3144. auto undo = [this](const std::string &json) {
  3145. OBSDataAutoRelease base =
  3146. obs_data_create_from_json(json.c_str());
  3147. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3148. obs_data_get_array(base, "sources_in_deleted_scene");
  3149. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3150. obs_data_get_array(base, "scene_used_in_other_scenes");
  3151. int savedIndex = (int)obs_data_get_int(base, "index");
  3152. std::vector<OBSSource> sources;
  3153. /* create missing sources */
  3154. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3155. sources.reserve(count);
  3156. for (size_t i = 0; i < count; i++) {
  3157. OBSDataAutoRelease data = obs_data_array_item(
  3158. sources_in_deleted_scene, i);
  3159. const char *name = obs_data_get_string(data, "name");
  3160. OBSSourceAutoRelease source =
  3161. obs_get_source_by_name(name);
  3162. if (!source) {
  3163. source = obs_load_source(data);
  3164. sources.push_back(source.Get());
  3165. }
  3166. }
  3167. /* actually load sources now */
  3168. for (obs_source_t *source : sources)
  3169. obs_source_load2(source);
  3170. /* Add scene to scenes and groups it was nested in */
  3171. for (size_t i = 0;
  3172. i < obs_data_array_count(scene_used_in_other_scenes);
  3173. i++) {
  3174. OBSDataAutoRelease data = obs_data_array_item(
  3175. scene_used_in_other_scenes, i);
  3176. const char *name = obs_data_get_string(data, "name");
  3177. OBSSourceAutoRelease source =
  3178. obs_get_source_by_name(name);
  3179. OBSDataAutoRelease settings =
  3180. obs_data_get_obj(data, "settings");
  3181. OBSDataArrayAutoRelease items =
  3182. obs_data_get_array(settings, "items");
  3183. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3184. std::vector<OBSSource> existing_sources;
  3185. auto cb = [](obs_scene_t *scene, obs_sceneitem_t *item,
  3186. void *data) {
  3187. UNUSED_PARAMETER(scene);
  3188. std::vector<OBSSource> *existing =
  3189. (std::vector<OBSSource> *)data;
  3190. OBSSource source =
  3191. obs_sceneitem_get_source(item);
  3192. obs_sceneitem_remove(item);
  3193. existing->push_back(source);
  3194. return true;
  3195. };
  3196. obs_scene_enum_items(
  3197. obs_group_or_scene_from_source(source), cb,
  3198. (void *)&existing_sources);
  3199. /* Re-add sources to the scene */
  3200. obs_sceneitems_add(
  3201. obs_group_or_scene_from_source(source), items);
  3202. }
  3203. obs_source_t *scene_source = sources.back();
  3204. OBSScene scene = obs_scene_from_source(scene_source);
  3205. SetCurrentScene(scene, true);
  3206. /* set original index in list box */
  3207. ui->scenes->blockSignals(true);
  3208. int curIndex = ui->scenes->currentRow();
  3209. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3210. ui->scenes->insertItem(savedIndex, item);
  3211. ui->scenes->setCurrentRow(savedIndex);
  3212. currentScene = scene.Get();
  3213. ui->scenes->blockSignals(false);
  3214. };
  3215. auto redo = [](const std::string &name) {
  3216. OBSSourceAutoRelease source =
  3217. obs_get_source_by_name(name.c_str());
  3218. RemoveSceneAndReleaseNested(source);
  3219. };
  3220. OBSDataAutoRelease data = obs_data_create();
  3221. obs_data_set_array(data, "sources_in_deleted_scene",
  3222. sources_in_deleted_scene);
  3223. obs_data_set_array(data, "scene_used_in_other_scenes",
  3224. scene_used_in_other_scenes);
  3225. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3226. const char *scene_name = obs_source_get_name(source);
  3227. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3228. obs_data_get_json(data), scene_name);
  3229. /* --------------------------- */
  3230. /* remove */
  3231. RemoveSceneAndReleaseNested(source);
  3232. if (api)
  3233. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3234. }
  3235. void OBSBasic::ReorderSources(OBSScene scene)
  3236. {
  3237. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3238. return;
  3239. ui->sources->ReorderItems();
  3240. SaveProject();
  3241. }
  3242. void OBSBasic::RefreshSources(OBSScene scene)
  3243. {
  3244. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3245. return;
  3246. ui->sources->RefreshItems();
  3247. SaveProject();
  3248. }
  3249. /* OBS Callbacks */
  3250. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3251. {
  3252. OBSBasic *window = static_cast<OBSBasic *>(data);
  3253. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3254. QMetaObject::invokeMethod(window, "ReorderSources",
  3255. Q_ARG(OBSScene, OBSScene(scene)));
  3256. }
  3257. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3258. {
  3259. OBSBasic *window = static_cast<OBSBasic *>(data);
  3260. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3261. QMetaObject::invokeMethod(window, "RefreshSources",
  3262. Q_ARG(OBSScene, OBSScene(scene)));
  3263. }
  3264. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3265. {
  3266. OBSBasic *window = static_cast<OBSBasic *>(data);
  3267. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3268. QMetaObject::invokeMethod(window, "AddSceneItem",
  3269. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3270. }
  3271. void OBSBasic::SourceCreated(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. "AddScene", WaitConnection(),
  3277. Q_ARG(OBSSource, OBSSource(source)));
  3278. }
  3279. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3280. {
  3281. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3282. if (obs_scene_from_source(source) != NULL)
  3283. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3284. "RemoveScene",
  3285. Q_ARG(OBSSource, OBSSource(source)));
  3286. }
  3287. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3288. {
  3289. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3290. uint32_t flags = obs_source_get_output_flags(source);
  3291. if (flags & OBS_SOURCE_AUDIO)
  3292. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3293. "ActivateAudioSource",
  3294. Q_ARG(OBSSource, OBSSource(source)));
  3295. }
  3296. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3297. {
  3298. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3299. uint32_t flags = obs_source_get_output_flags(source);
  3300. if (flags & OBS_SOURCE_AUDIO)
  3301. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3302. "DeactivateAudioSource",
  3303. Q_ARG(OBSSource, OBSSource(source)));
  3304. }
  3305. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3306. {
  3307. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3308. if (obs_source_active(source))
  3309. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3310. "ActivateAudioSource",
  3311. Q_ARG(OBSSource, OBSSource(source)));
  3312. }
  3313. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3314. {
  3315. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3316. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3317. "DeactivateAudioSource",
  3318. Q_ARG(OBSSource, OBSSource(source)));
  3319. }
  3320. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3321. {
  3322. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3323. const char *newName = calldata_string(params, "new_name");
  3324. const char *prevName = calldata_string(params, "prev_name");
  3325. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3326. "RenameSources", Q_ARG(OBSSource, source),
  3327. Q_ARG(QString, QT_UTF8(newName)),
  3328. Q_ARG(QString, QT_UTF8(prevName)));
  3329. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3330. }
  3331. void OBSBasic::DrawBackdrop(float cx, float cy)
  3332. {
  3333. if (!box)
  3334. return;
  3335. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3336. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3337. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3338. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3339. vec4 colorVal;
  3340. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3341. gs_effect_set_vec4(color, &colorVal);
  3342. gs_technique_begin(tech);
  3343. gs_technique_begin_pass(tech, 0);
  3344. gs_matrix_push();
  3345. gs_matrix_identity();
  3346. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3347. gs_load_vertexbuffer(box);
  3348. gs_draw(GS_TRISTRIP, 0, 0);
  3349. gs_matrix_pop();
  3350. gs_technique_end_pass(tech);
  3351. gs_technique_end(tech);
  3352. gs_load_vertexbuffer(nullptr);
  3353. GS_DEBUG_MARKER_END();
  3354. }
  3355. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  3356. {
  3357. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3358. OBSBasic *window = static_cast<OBSBasic *>(data);
  3359. obs_video_info ovi;
  3360. obs_get_video_info(&ovi);
  3361. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3362. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3363. gs_viewport_push();
  3364. gs_projection_push();
  3365. obs_display_t *display = window->ui->preview->GetDisplay();
  3366. uint32_t width, height;
  3367. obs_display_size(display, &width, &height);
  3368. float right = float(width) - window->previewX;
  3369. float bottom = float(height) - window->previewY;
  3370. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3371. 100.0f);
  3372. window->ui->preview->DrawOverflow();
  3373. /* --------------------------------------- */
  3374. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3375. -100.0f, 100.0f);
  3376. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3377. window->previewCY);
  3378. if (window->IsPreviewProgramMode()) {
  3379. window->DrawBackdrop(float(ovi.base_width),
  3380. float(ovi.base_height));
  3381. OBSScene scene = window->GetCurrentScene();
  3382. obs_source_t *source = obs_scene_get_source(scene);
  3383. if (source)
  3384. obs_source_video_render(source);
  3385. } else {
  3386. obs_render_main_texture_src_color_only();
  3387. }
  3388. gs_load_vertexbuffer(nullptr);
  3389. /* --------------------------------------- */
  3390. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3391. 100.0f);
  3392. gs_reset_viewport();
  3393. window->ui->preview->DrawSceneEditing();
  3394. uint32_t targetCX = window->previewCX;
  3395. uint32_t targetCY = window->previewCY;
  3396. if (window->drawSafeAreas) {
  3397. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3398. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3399. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3400. targetCY);
  3401. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3402. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3403. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3404. }
  3405. /* --------------------------------------- */
  3406. gs_projection_pop();
  3407. gs_viewport_pop();
  3408. GS_DEBUG_MARKER_END();
  3409. UNUSED_PARAMETER(cx);
  3410. UNUSED_PARAMETER(cy);
  3411. }
  3412. /* Main class functions */
  3413. obs_service_t *OBSBasic::GetService()
  3414. {
  3415. if (!service) {
  3416. service =
  3417. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3418. obs_service_release(service);
  3419. }
  3420. return service;
  3421. }
  3422. void OBSBasic::SetService(obs_service_t *newService)
  3423. {
  3424. if (newService) {
  3425. service = newService;
  3426. }
  3427. }
  3428. int OBSBasic::GetTransitionDuration()
  3429. {
  3430. return ui->transitionDuration->value();
  3431. }
  3432. bool OBSBasic::Active() const
  3433. {
  3434. if (!outputHandler)
  3435. return false;
  3436. return outputHandler->Active();
  3437. }
  3438. #ifdef _WIN32
  3439. #define IS_WIN32 1
  3440. #else
  3441. #define IS_WIN32 0
  3442. #endif
  3443. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3444. {
  3445. return obs_reset_video(ovi);
  3446. }
  3447. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3448. {
  3449. const char *scaleTypeStr =
  3450. config_get_string(basicConfig, "Video", "ScaleType");
  3451. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3452. return OBS_SCALE_BILINEAR;
  3453. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3454. return OBS_SCALE_LANCZOS;
  3455. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3456. return OBS_SCALE_AREA;
  3457. else
  3458. return OBS_SCALE_BICUBIC;
  3459. }
  3460. static inline enum video_format GetVideoFormatFromName(const char *name)
  3461. {
  3462. if (astrcmpi(name, "I420") == 0)
  3463. return VIDEO_FORMAT_I420;
  3464. else if (astrcmpi(name, "NV12") == 0)
  3465. return VIDEO_FORMAT_NV12;
  3466. else if (astrcmpi(name, "I444") == 0)
  3467. return VIDEO_FORMAT_I444;
  3468. else if (astrcmpi(name, "I010") == 0)
  3469. return VIDEO_FORMAT_I010;
  3470. else if (astrcmpi(name, "P010") == 0)
  3471. return VIDEO_FORMAT_P010;
  3472. #if 0 //currently unsupported
  3473. else if (astrcmpi(name, "YVYU") == 0)
  3474. return VIDEO_FORMAT_YVYU;
  3475. else if (astrcmpi(name, "YUY2") == 0)
  3476. return VIDEO_FORMAT_YUY2;
  3477. else if (astrcmpi(name, "UYVY") == 0)
  3478. return VIDEO_FORMAT_UYVY;
  3479. #endif
  3480. else
  3481. return VIDEO_FORMAT_RGBA;
  3482. }
  3483. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3484. {
  3485. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3486. if (strcmp(name, "601") == 0)
  3487. colorspace = VIDEO_CS_601;
  3488. else if (strcmp(name, "709") == 0)
  3489. colorspace = VIDEO_CS_709;
  3490. else if (strcmp(name, "2100PQ") == 0)
  3491. colorspace = VIDEO_CS_2100_PQ;
  3492. else if (strcmp(name, "2100HLG") == 0)
  3493. colorspace = VIDEO_CS_2100_HLG;
  3494. return colorspace;
  3495. }
  3496. void OBSBasic::ResetUI()
  3497. {
  3498. bool studioPortraitLayout = config_get_bool(
  3499. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3500. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3501. "StudioModeLabels");
  3502. if (studioPortraitLayout)
  3503. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3504. else
  3505. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3506. if (previewProgramMode)
  3507. ui->previewLabel->setHidden(!labels);
  3508. if (programLabel)
  3509. programLabel->setHidden(!labels);
  3510. }
  3511. int OBSBasic::ResetVideo()
  3512. {
  3513. if (outputHandler && outputHandler->Active())
  3514. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3515. ProfileScope("OBSBasic::ResetVideo");
  3516. struct obs_video_info ovi;
  3517. int ret;
  3518. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3519. const char *colorFormat =
  3520. config_get_string(basicConfig, "Video", "ColorFormat");
  3521. const char *colorSpace =
  3522. config_get_string(basicConfig, "Video", "ColorSpace");
  3523. const char *colorRange =
  3524. config_get_string(basicConfig, "Video", "ColorRange");
  3525. ovi.graphics_module = App()->GetRenderModule();
  3526. ovi.base_width =
  3527. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3528. ovi.base_height =
  3529. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3530. ovi.output_width =
  3531. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3532. ovi.output_height =
  3533. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3534. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3535. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3536. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3537. : VIDEO_RANGE_PARTIAL;
  3538. ovi.adapter =
  3539. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3540. ovi.gpu_conversion = true;
  3541. ovi.scale_type = GetScaleType(basicConfig);
  3542. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3543. ovi.base_width = 1920;
  3544. ovi.base_height = 1080;
  3545. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3546. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3547. }
  3548. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3549. ovi.output_width = ovi.base_width;
  3550. ovi.output_height = ovi.base_height;
  3551. config_set_uint(basicConfig, "Video", "OutputCX",
  3552. ovi.base_width);
  3553. config_set_uint(basicConfig, "Video", "OutputCY",
  3554. ovi.base_height);
  3555. }
  3556. ret = AttemptToResetVideo(&ovi);
  3557. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3558. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3559. blog(LOG_WARNING, "Tried to reset when "
  3560. "already active");
  3561. return ret;
  3562. }
  3563. /* Try OpenGL if DirectX fails on windows */
  3564. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3565. blog(LOG_WARNING,
  3566. "Failed to initialize obs video (%d) "
  3567. "with graphics_module='%s', retrying "
  3568. "with graphics_module='%s'",
  3569. ret, ovi.graphics_module, DL_OPENGL);
  3570. ovi.graphics_module = DL_OPENGL;
  3571. ret = AttemptToResetVideo(&ovi);
  3572. }
  3573. } else if (ret == OBS_VIDEO_SUCCESS) {
  3574. ResizePreview(ovi.base_width, ovi.base_height);
  3575. if (program)
  3576. ResizeProgram(ovi.base_width, ovi.base_height);
  3577. }
  3578. if (ret == OBS_VIDEO_SUCCESS) {
  3579. const float sdr_white_level = (float)config_get_uint(
  3580. basicConfig, "Video", "SdrWhiteLevel");
  3581. const float hdr_nominal_peak_level = (float)config_get_uint(
  3582. basicConfig, "Video", "HdrNominalPeakLevel");
  3583. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  3584. OBSBasicStats::InitializeValues();
  3585. OBSProjector::UpdateMultiviewProjectors();
  3586. }
  3587. return ret;
  3588. }
  3589. bool OBSBasic::ResetAudio()
  3590. {
  3591. ProfileScope("OBSBasic::ResetAudio");
  3592. struct obs_audio_info2 ai = {};
  3593. ai.samples_per_sec =
  3594. config_get_uint(basicConfig, "Audio", "SampleRate");
  3595. const char *channelSetupStr =
  3596. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3597. if (strcmp(channelSetupStr, "Mono") == 0)
  3598. ai.speakers = SPEAKERS_MONO;
  3599. else if (strcmp(channelSetupStr, "2.1") == 0)
  3600. ai.speakers = SPEAKERS_2POINT1;
  3601. else if (strcmp(channelSetupStr, "4.0") == 0)
  3602. ai.speakers = SPEAKERS_4POINT0;
  3603. else if (strcmp(channelSetupStr, "4.1") == 0)
  3604. ai.speakers = SPEAKERS_4POINT1;
  3605. else if (strcmp(channelSetupStr, "5.1") == 0)
  3606. ai.speakers = SPEAKERS_5POINT1;
  3607. else if (strcmp(channelSetupStr, "7.1") == 0)
  3608. ai.speakers = SPEAKERS_7POINT1;
  3609. else
  3610. ai.speakers = SPEAKERS_STEREO;
  3611. bool lowLatencyAudioBuffering = config_get_bool(
  3612. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  3613. if (lowLatencyAudioBuffering) {
  3614. ai.max_buffering_ms = 20;
  3615. ai.fixed_buffering = true;
  3616. }
  3617. return obs_reset_audio2(&ai);
  3618. }
  3619. extern char *get_new_source_name(const char *name, const char *format);
  3620. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3621. const char *deviceDesc, int channel)
  3622. {
  3623. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3624. OBSSourceAutoRelease source;
  3625. OBSDataAutoRelease settings;
  3626. source = obs_get_output_source(channel);
  3627. if (source) {
  3628. if (disable) {
  3629. obs_set_output_source(channel, nullptr);
  3630. } else {
  3631. settings = obs_source_get_settings(source);
  3632. const char *oldId =
  3633. obs_data_get_string(settings, "device_id");
  3634. if (strcmp(oldId, deviceId) != 0) {
  3635. obs_data_set_string(settings, "device_id",
  3636. deviceId);
  3637. obs_source_update(source, settings);
  3638. }
  3639. }
  3640. } else if (!disable) {
  3641. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  3642. settings = obs_data_create();
  3643. obs_data_set_string(settings, "device_id", deviceId);
  3644. source = obs_source_create(sourceId, name, settings, nullptr);
  3645. obs_set_output_source(channel, source);
  3646. }
  3647. }
  3648. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3649. {
  3650. QSize targetSize;
  3651. bool isFixedScaling;
  3652. obs_video_info ovi;
  3653. /* resize preview panel to fix to the top section of the window */
  3654. targetSize = GetPixelSize(ui->preview);
  3655. isFixedScaling = ui->preview->IsFixedScaling();
  3656. obs_get_video_info(&ovi);
  3657. if (isFixedScaling) {
  3658. previewScale = ui->preview->GetScalingAmount();
  3659. GetCenterPosFromFixedScale(
  3660. int(cx), int(cy),
  3661. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3662. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3663. previewY, previewScale);
  3664. previewX += ui->preview->GetScrollX();
  3665. previewY += ui->preview->GetScrollY();
  3666. } else {
  3667. GetScaleAndCenterPos(int(cx), int(cy),
  3668. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3669. targetSize.height() -
  3670. PREVIEW_EDGE_SIZE * 2,
  3671. previewX, previewY, previewScale);
  3672. }
  3673. previewX += float(PREVIEW_EDGE_SIZE);
  3674. previewY += float(PREVIEW_EDGE_SIZE);
  3675. }
  3676. void OBSBasic::CloseDialogs()
  3677. {
  3678. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3679. if (!childDialogs.isEmpty()) {
  3680. for (int i = 0; i < childDialogs.size(); ++i) {
  3681. childDialogs.at(i)->close();
  3682. }
  3683. }
  3684. if (!stats.isNull())
  3685. stats->close(); //call close to save Stats geometry
  3686. if (!remux.isNull())
  3687. remux->close();
  3688. }
  3689. void OBSBasic::EnumDialogs()
  3690. {
  3691. visDialogs.clear();
  3692. modalDialogs.clear();
  3693. visMsgBoxes.clear();
  3694. /* fill list of Visible dialogs and Modal dialogs */
  3695. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3696. for (QDialog *dialog : dialogs) {
  3697. if (dialog->isVisible())
  3698. visDialogs.append(dialog);
  3699. if (dialog->isModal())
  3700. modalDialogs.append(dialog);
  3701. }
  3702. /* fill list of Visible message boxes */
  3703. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3704. for (QMessageBox *msgbox : msgBoxes) {
  3705. if (msgbox->isVisible())
  3706. visMsgBoxes.append(msgbox);
  3707. }
  3708. }
  3709. void OBSBasic::ClearProjectors()
  3710. {
  3711. for (size_t i = 0; i < projectors.size(); i++) {
  3712. if (projectors[i])
  3713. delete projectors[i];
  3714. }
  3715. projectors.clear();
  3716. }
  3717. void OBSBasic::ClearSceneData()
  3718. {
  3719. disableSaving++;
  3720. setCursor(Qt::WaitCursor);
  3721. CloseDialogs();
  3722. ClearVolumeControls();
  3723. ClearListItems(ui->scenes);
  3724. ui->sources->Clear();
  3725. ClearQuickTransitions();
  3726. ui->transitions->clear();
  3727. ClearProjectors();
  3728. for (int i = 0; i < MAX_CHANNELS; i++)
  3729. obs_set_output_source(i, nullptr);
  3730. lastScene = nullptr;
  3731. swapScene = nullptr;
  3732. programScene = nullptr;
  3733. prevFTBSource = nullptr;
  3734. clipboard.clear();
  3735. copyFiltersSource = nullptr;
  3736. copyFilter = nullptr;
  3737. auto cb = [](void *unused, obs_source_t *source) {
  3738. obs_source_remove(source);
  3739. UNUSED_PARAMETER(unused);
  3740. return true;
  3741. };
  3742. obs_enum_scenes(cb, nullptr);
  3743. obs_enum_sources(cb, nullptr);
  3744. if (api)
  3745. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3746. undo_s.clear();
  3747. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  3748. * that deleteLater events are processed at this point */
  3749. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  3750. do {
  3751. QApplication::sendPostedEvents(nullptr);
  3752. } while (obs_wait_for_destroy_queue());
  3753. unsetCursor();
  3754. disableSaving--;
  3755. blog(LOG_INFO, "All scene data cleared");
  3756. blog(LOG_INFO, "------------------------------------------------");
  3757. }
  3758. void OBSBasic::closeEvent(QCloseEvent *event)
  3759. {
  3760. /* Do not close window if inside of a temporary event loop because we
  3761. * could be inside of an Auth::LoadUI call. Keep trying once per
  3762. * second until we've exit any known sub-loops. */
  3763. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3764. QTimer::singleShot(1000, this, SLOT(close()));
  3765. event->ignore();
  3766. return;
  3767. }
  3768. #if YOUTUBE_ENABLED
  3769. /* Also don't close the window if the youtube stream check is active */
  3770. if (youtubeStreamCheckThread) {
  3771. QTimer::singleShot(1000, this, SLOT(close()));
  3772. event->ignore();
  3773. return;
  3774. }
  3775. #endif
  3776. if (isVisible())
  3777. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3778. "geometry",
  3779. saveGeometry().toBase64().constData());
  3780. bool confirmOnExit =
  3781. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  3782. if (confirmOnExit && outputHandler && outputHandler->Active()) {
  3783. SetShowing(true);
  3784. QMessageBox::StandardButton button = OBSMessageBox::question(
  3785. this, QTStr("ConfirmExit.Title"),
  3786. QTStr("ConfirmExit.Text"));
  3787. if (button == QMessageBox::No) {
  3788. event->ignore();
  3789. restart = false;
  3790. return;
  3791. }
  3792. }
  3793. if (remux && !remux->close()) {
  3794. event->ignore();
  3795. restart = false;
  3796. return;
  3797. }
  3798. QWidget::closeEvent(event);
  3799. if (!event->isAccepted())
  3800. return;
  3801. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3802. closing = true;
  3803. if (introCheckThread)
  3804. introCheckThread->wait();
  3805. if (whatsNewInitThread)
  3806. whatsNewInitThread->wait();
  3807. if (updateCheckThread)
  3808. updateCheckThread->wait();
  3809. if (logUploadThread)
  3810. logUploadThread->wait();
  3811. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  3812. devicePropertiesThread->wait();
  3813. devicePropertiesThread.reset();
  3814. }
  3815. QApplication::sendPostedEvents(nullptr);
  3816. signalHandlers.clear();
  3817. Auth::Save();
  3818. SaveProjectNow();
  3819. auth.reset();
  3820. delete extraBrowsers;
  3821. ui->preview->DestroyDisplay();
  3822. if (program)
  3823. program->DestroyDisplay();
  3824. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3825. saveState().toBase64().constData());
  3826. #ifdef BROWSER_AVAILABLE
  3827. SaveExtraBrowserDocks();
  3828. ClearExtraBrowserDocks();
  3829. #endif
  3830. if (api)
  3831. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  3832. disableSaving++;
  3833. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3834. * sources, etc) so that all references are released before shutdown */
  3835. ClearSceneData();
  3836. if (api)
  3837. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3838. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  3839. }
  3840. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  3841. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  3842. #else
  3843. bool OBSBasic::nativeEvent(const QByteArray &, void *message, long *)
  3844. #endif
  3845. {
  3846. #ifdef _WIN32
  3847. const MSG &msg = *static_cast<MSG *>(message);
  3848. switch (msg.message) {
  3849. case WM_MOVE:
  3850. for (OBSQTDisplay *const display :
  3851. findChildren<OBSQTDisplay *>()) {
  3852. display->OnMove();
  3853. }
  3854. break;
  3855. case WM_DISPLAYCHANGE:
  3856. for (OBSQTDisplay *const display :
  3857. findChildren<OBSQTDisplay *>()) {
  3858. display->OnDisplayChange();
  3859. }
  3860. }
  3861. #else
  3862. UNUSED_PARAMETER(message);
  3863. #endif
  3864. return false;
  3865. }
  3866. void OBSBasic::changeEvent(QEvent *event)
  3867. {
  3868. if (event->type() == QEvent::WindowStateChange) {
  3869. QWindowStateChangeEvent *stateEvent =
  3870. (QWindowStateChangeEvent *)event;
  3871. if (isMinimized()) {
  3872. if (trayIcon && trayIcon->isVisible() &&
  3873. sysTrayMinimizeToTray()) {
  3874. ToggleShowHide();
  3875. return;
  3876. }
  3877. if (previewEnabled)
  3878. EnablePreviewDisplay(false);
  3879. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3880. isVisible()) {
  3881. if (previewEnabled)
  3882. EnablePreviewDisplay(true);
  3883. }
  3884. }
  3885. }
  3886. void OBSBasic::on_actionShow_Recordings_triggered()
  3887. {
  3888. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3889. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3890. const char *adv_path =
  3891. strcmp(type, "Standard")
  3892. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3893. : config_get_string(basicConfig, "AdvOut",
  3894. "RecFilePath");
  3895. const char *path = strcmp(mode, "Advanced")
  3896. ? config_get_string(basicConfig,
  3897. "SimpleOutput",
  3898. "FilePath")
  3899. : adv_path;
  3900. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3901. }
  3902. void OBSBasic::on_actionRemux_triggered()
  3903. {
  3904. if (!remux.isNull()) {
  3905. remux->show();
  3906. remux->raise();
  3907. return;
  3908. }
  3909. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3910. const char *path = strcmp(mode, "Advanced")
  3911. ? config_get_string(basicConfig,
  3912. "SimpleOutput",
  3913. "FilePath")
  3914. : config_get_string(basicConfig, "AdvOut",
  3915. "RecFilePath");
  3916. OBSRemux *remuxDlg;
  3917. remuxDlg = new OBSRemux(path, this);
  3918. remuxDlg->show();
  3919. remux = remuxDlg;
  3920. }
  3921. void OBSBasic::on_action_Settings_triggered()
  3922. {
  3923. static bool settings_already_executing = false;
  3924. /* Do not load settings window if inside of a temporary event loop
  3925. * because we could be inside of an Auth::LoadUI call. Keep trying
  3926. * once per second until we've exit any known sub-loops. */
  3927. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3928. QTimer::singleShot(1000, this,
  3929. SLOT(on_action_Settings_triggered()));
  3930. return;
  3931. }
  3932. if (settings_already_executing) {
  3933. return;
  3934. }
  3935. settings_already_executing = true;
  3936. {
  3937. OBSBasicSettings settings(this);
  3938. settings.exec();
  3939. }
  3940. settings_already_executing = false;
  3941. if (restart) {
  3942. QMessageBox::StandardButton button = OBSMessageBox::question(
  3943. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3944. if (button == QMessageBox::Yes)
  3945. close();
  3946. else
  3947. restart = false;
  3948. }
  3949. }
  3950. static inline void AddMissingFiles(void *data, obs_source_t *source)
  3951. {
  3952. obs_missing_files_t *f = (obs_missing_files_t *)data;
  3953. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  3954. obs_missing_files_append(f, sf);
  3955. obs_missing_files_destroy(sf);
  3956. }
  3957. void OBSBasic::on_actionShowMissingFiles_triggered()
  3958. {
  3959. obs_missing_files_t *files = obs_missing_files_create();
  3960. auto cb_sources = [](void *data, obs_source_t *source) {
  3961. AddMissingFiles(data, source);
  3962. return true;
  3963. };
  3964. obs_enum_sources(cb_sources, files);
  3965. auto cb_transitions = [](void *data, obs_source_t *source) {
  3966. if (obs_source_get_type(source) != OBS_SOURCE_TYPE_TRANSITION)
  3967. return true;
  3968. AddMissingFiles(data, source);
  3969. return true;
  3970. };
  3971. obs_enum_all_sources(cb_transitions, files);
  3972. if (obs_missing_files_count(files) > 0) {
  3973. /* When loading the missing files dialog on launch, the
  3974. * window hasn't fully initialized by this point on macOS,
  3975. * so put this at the end of the current task queue. Fixes
  3976. * a bug where the window is behind OBS on startup. */
  3977. QTimer::singleShot(0, [this, files] {
  3978. missDialog = new OBSMissingFiles(files, this);
  3979. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  3980. missDialog->show();
  3981. missDialog->raise();
  3982. });
  3983. } else {
  3984. obs_missing_files_destroy(files);
  3985. /* Only raise dialog if triggered manually */
  3986. if (!disableSaving)
  3987. OBSMessageBox::information(
  3988. this, QTStr("MissingFiles.NoMissing.Title"),
  3989. QTStr("MissingFiles.NoMissing.Text"));
  3990. }
  3991. }
  3992. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3993. {
  3994. if (advAudioWindow != nullptr) {
  3995. advAudioWindow->raise();
  3996. return;
  3997. }
  3998. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3999. "BasicWindow", "ShowSourceIcons");
  4000. advAudioWindow = new OBSBasicAdvAudio(this);
  4001. advAudioWindow->show();
  4002. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4003. advAudioWindow->SetIconsVisible(iconsVisible);
  4004. }
  4005. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4006. QListWidgetItem *prev)
  4007. {
  4008. obs_source_t *source = NULL;
  4009. if (current) {
  4010. obs_scene_t *scene;
  4011. scene = GetOBSRef<OBSScene>(current);
  4012. source = obs_scene_get_source(scene);
  4013. currentScene = scene;
  4014. } else {
  4015. currentScene = NULL;
  4016. }
  4017. SetCurrentScene(source);
  4018. if (api)
  4019. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4020. UpdateContextBar();
  4021. UNUSED_PARAMETER(prev);
  4022. }
  4023. void OBSBasic::EditSceneName()
  4024. {
  4025. ui->scenesDock->removeAction(renameScene);
  4026. QListWidgetItem *item = ui->scenes->currentItem();
  4027. Qt::ItemFlags flags = item->flags();
  4028. item->setFlags(flags | Qt::ItemIsEditable);
  4029. ui->scenes->editItem(item);
  4030. item->setFlags(flags);
  4031. }
  4032. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  4033. const char *slot)
  4034. {
  4035. QAction *action;
  4036. QList<QScreen *> screens = QGuiApplication::screens();
  4037. for (int i = 0; i < screens.size(); i++) {
  4038. QScreen *screen = screens[i];
  4039. QRect screenGeometry = screen->geometry();
  4040. qreal ratio = screen->devicePixelRatio();
  4041. QString name = "";
  4042. #ifdef _WIN32
  4043. QTextStream fullname(&name);
  4044. fullname << GetMonitorName(screen->name());
  4045. fullname << " (";
  4046. fullname << (i + 1);
  4047. fullname << ")";
  4048. #elif defined(__APPLE__)
  4049. name = screen->name();
  4050. #else
  4051. name = screen->model().simplified();
  4052. if (name.length() > 1 && name.endsWith("-"))
  4053. name.chop(1);
  4054. #endif
  4055. name = name.simplified();
  4056. if (name.length() == 0) {
  4057. name = QString("%1 %2")
  4058. .arg(QTStr("Display"))
  4059. .arg(QString::number(i + 1));
  4060. }
  4061. QString str =
  4062. QString("%1: %2x%3 @ %4,%5")
  4063. .arg(name,
  4064. QString::number(screenGeometry.width() *
  4065. ratio),
  4066. QString::number(screenGeometry.height() *
  4067. ratio),
  4068. QString::number(screenGeometry.x()),
  4069. QString::number(screenGeometry.y()));
  4070. action = parent->addAction(str, target, slot);
  4071. action->setProperty("monitor", i);
  4072. }
  4073. }
  4074. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4075. {
  4076. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4077. QMenu popup(this);
  4078. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4079. popup.addAction(QTStr("Add"), this,
  4080. SLOT(on_actionAddScene_triggered()));
  4081. if (item) {
  4082. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4083. copyFilters->setEnabled(false);
  4084. connect(copyFilters, SIGNAL(triggered()), this,
  4085. SLOT(SceneCopyFilters()));
  4086. QAction *pasteFilters =
  4087. new QAction(QTStr("Paste.Filters"), this);
  4088. pasteFilters->setEnabled(
  4089. !obs_weak_source_expired(copyFiltersSource));
  4090. connect(pasteFilters, SIGNAL(triggered()), this,
  4091. SLOT(ScenePasteFilters()));
  4092. popup.addSeparator();
  4093. popup.addAction(QTStr("Duplicate"), this,
  4094. SLOT(DuplicateSelectedScene()));
  4095. popup.addAction(copyFilters);
  4096. popup.addAction(pasteFilters);
  4097. popup.addSeparator();
  4098. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  4099. popup.addAction(QTStr("Remove"), this,
  4100. SLOT(RemoveSelectedScene()));
  4101. popup.addSeparator();
  4102. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4103. SLOT(on_actionSceneUp_triggered()));
  4104. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4105. this, SLOT(on_actionSceneDown_triggered()));
  4106. order.addSeparator();
  4107. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4108. this, SLOT(MoveSceneToTop()));
  4109. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4110. this, SLOT(MoveSceneToBottom()));
  4111. popup.addMenu(&order);
  4112. popup.addSeparator();
  4113. delete sceneProjectorMenu;
  4114. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4115. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4116. SLOT(OpenSceneProjector()));
  4117. popup.addMenu(sceneProjectorMenu);
  4118. QAction *sceneWindow = popup.addAction(
  4119. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  4120. popup.addAction(sceneWindow);
  4121. popup.addAction(QTStr("Screenshot.Scene"), this,
  4122. SLOT(ScreenshotScene()));
  4123. popup.addSeparator();
  4124. popup.addAction(QTStr("Filters"), this,
  4125. SLOT(OpenSceneFilters()));
  4126. popup.addSeparator();
  4127. delete perSceneTransitionMenu;
  4128. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4129. popup.addMenu(perSceneTransitionMenu);
  4130. /* ---------------------- */
  4131. QAction *multiviewAction =
  4132. popup.addAction(QTStr("ShowInMultiview"));
  4133. OBSSource source = GetCurrentSceneSource();
  4134. OBSDataAutoRelease data =
  4135. obs_source_get_private_settings(source);
  4136. obs_data_set_default_bool(data, "show_in_multiview", true);
  4137. bool show = obs_data_get_bool(data, "show_in_multiview");
  4138. multiviewAction->setCheckable(true);
  4139. multiviewAction->setChecked(show);
  4140. auto showInMultiview = [](OBSData data) {
  4141. bool show =
  4142. obs_data_get_bool(data, "show_in_multiview");
  4143. obs_data_set_bool(data, "show_in_multiview", !show);
  4144. OBSProjector::UpdateMultiviewProjectors();
  4145. };
  4146. connect(multiviewAction, &QAction::triggered,
  4147. std::bind(showInMultiview, data.Get()));
  4148. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4149. }
  4150. popup.addSeparator();
  4151. bool grid = ui->scenes->GetGridMode();
  4152. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4153. : QTStr("Basic.Main.GridMode"),
  4154. this);
  4155. connect(gridAction, SIGNAL(triggered()), this,
  4156. SLOT(GridActionClicked()));
  4157. popup.addAction(gridAction);
  4158. popup.exec(QCursor::pos());
  4159. }
  4160. void OBSBasic::GridActionClicked()
  4161. {
  4162. bool gridMode = !ui->scenes->GetGridMode();
  4163. ui->scenes->SetGridMode(gridMode);
  4164. }
  4165. void OBSBasic::on_actionAddScene_triggered()
  4166. {
  4167. string name;
  4168. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4169. int i = 2;
  4170. QString placeHolderText = format.arg(i);
  4171. OBSSourceAutoRelease source = nullptr;
  4172. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4173. placeHolderText = format.arg(++i);
  4174. }
  4175. bool accepted = NameDialog::AskForName(
  4176. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4177. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4178. if (accepted) {
  4179. if (name.empty()) {
  4180. OBSMessageBox::warning(this,
  4181. QTStr("NoNameEntered.Title"),
  4182. QTStr("NoNameEntered.Text"));
  4183. on_actionAddScene_triggered();
  4184. return;
  4185. }
  4186. OBSSourceAutoRelease source =
  4187. obs_get_source_by_name(name.c_str());
  4188. if (source) {
  4189. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4190. QTStr("NameExists.Text"));
  4191. on_actionAddScene_triggered();
  4192. return;
  4193. }
  4194. auto undo_fn = [](const std::string &data) {
  4195. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4196. if (t) {
  4197. obs_source_release(t);
  4198. obs_source_remove(t);
  4199. }
  4200. };
  4201. auto redo_fn = [this](const std::string &data) {
  4202. OBSSceneAutoRelease scene =
  4203. obs_scene_create(data.c_str());
  4204. obs_source_t *source = obs_scene_get_source(scene);
  4205. SetCurrentScene(source, true);
  4206. };
  4207. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4208. undo_fn, redo_fn, name, name);
  4209. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4210. obs_source_t *scene_source = obs_scene_get_source(scene);
  4211. SetCurrentScene(scene_source);
  4212. }
  4213. }
  4214. void OBSBasic::on_actionRemoveScene_triggered()
  4215. {
  4216. RemoveSelectedScene();
  4217. }
  4218. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4219. {
  4220. int idx = ui->scenes->currentRow();
  4221. if (idx == -1 || idx == invalidIdx)
  4222. return;
  4223. ui->scenes->blockSignals(true);
  4224. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4225. if (!relative)
  4226. idx = 0;
  4227. ui->scenes->insertItem(idx + offset, item);
  4228. ui->scenes->setCurrentRow(idx + offset);
  4229. item->setSelected(true);
  4230. currentScene = GetOBSRef<OBSScene>(item).Get();
  4231. ui->scenes->blockSignals(false);
  4232. OBSProjector::UpdateMultiviewProjectors();
  4233. }
  4234. void OBSBasic::on_actionSceneUp_triggered()
  4235. {
  4236. ChangeSceneIndex(true, -1, 0);
  4237. }
  4238. void OBSBasic::on_actionSceneDown_triggered()
  4239. {
  4240. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4241. }
  4242. void OBSBasic::MoveSceneToTop()
  4243. {
  4244. ChangeSceneIndex(false, 0, 0);
  4245. }
  4246. void OBSBasic::MoveSceneToBottom()
  4247. {
  4248. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4249. ui->scenes->count() - 1);
  4250. }
  4251. void OBSBasic::EditSceneItemName()
  4252. {
  4253. int idx = GetTopSelectedSourceItem();
  4254. ui->sources->Edit(idx);
  4255. }
  4256. void OBSBasic::SetDeinterlacingMode()
  4257. {
  4258. QAction *action = reinterpret_cast<QAction *>(sender());
  4259. obs_deinterlace_mode mode =
  4260. (obs_deinterlace_mode)action->property("mode").toInt();
  4261. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4262. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4263. obs_source_set_deinterlace_mode(source, mode);
  4264. }
  4265. void OBSBasic::SetDeinterlacingOrder()
  4266. {
  4267. QAction *action = reinterpret_cast<QAction *>(sender());
  4268. obs_deinterlace_field_order order =
  4269. (obs_deinterlace_field_order)action->property("order").toInt();
  4270. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4271. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4272. obs_source_set_deinterlace_field_order(source, order);
  4273. }
  4274. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4275. {
  4276. obs_deinterlace_mode deinterlaceMode =
  4277. obs_source_get_deinterlace_mode(source);
  4278. obs_deinterlace_field_order deinterlaceOrder =
  4279. obs_source_get_deinterlace_field_order(source);
  4280. QAction *action;
  4281. #define ADD_MODE(name, mode) \
  4282. action = menu->addAction(QTStr("" name), this, \
  4283. SLOT(SetDeinterlacingMode())); \
  4284. action->setProperty("mode", (int)mode); \
  4285. action->setCheckable(true); \
  4286. action->setChecked(deinterlaceMode == mode);
  4287. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4288. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4289. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4290. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4291. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4292. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4293. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4294. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4295. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4296. #undef ADD_MODE
  4297. menu->addSeparator();
  4298. #define ADD_ORDER(name, order) \
  4299. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4300. SLOT(SetDeinterlacingOrder())); \
  4301. action->setProperty("order", (int)order); \
  4302. action->setCheckable(true); \
  4303. action->setChecked(deinterlaceOrder == order);
  4304. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4305. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4306. #undef ADD_ORDER
  4307. return menu;
  4308. }
  4309. void OBSBasic::SetScaleFilter()
  4310. {
  4311. QAction *action = reinterpret_cast<QAction *>(sender());
  4312. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4313. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4314. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4315. }
  4316. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4317. {
  4318. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4319. QAction *action;
  4320. #define ADD_MODE(name, mode) \
  4321. action = \
  4322. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  4323. action->setProperty("mode", (int)mode); \
  4324. action->setCheckable(true); \
  4325. action->setChecked(scaleFilter == mode);
  4326. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4327. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4328. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4329. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4330. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4331. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4332. #undef ADD_MODE
  4333. return menu;
  4334. }
  4335. void OBSBasic::SetBlendingMethod()
  4336. {
  4337. QAction *action = reinterpret_cast<QAction *>(sender());
  4338. obs_blending_method method =
  4339. (obs_blending_method)action->property("method").toInt();
  4340. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4341. obs_sceneitem_set_blending_method(sceneItem, method);
  4342. }
  4343. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4344. {
  4345. obs_blending_method blendingMethod =
  4346. obs_sceneitem_get_blending_method(item);
  4347. QAction *action;
  4348. #define ADD_MODE(name, method) \
  4349. action = menu->addAction(QTStr("" name), this, \
  4350. SLOT(SetBlendingMethod())); \
  4351. action->setProperty("method", (int)method); \
  4352. action->setCheckable(true); \
  4353. action->setChecked(blendingMethod == method);
  4354. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4355. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4356. #undef ADD_MODE
  4357. return menu;
  4358. }
  4359. void OBSBasic::SetBlendingMode()
  4360. {
  4361. QAction *action = reinterpret_cast<QAction *>(sender());
  4362. obs_blending_type mode =
  4363. (obs_blending_type)action->property("mode").toInt();
  4364. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4365. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4366. }
  4367. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4368. {
  4369. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4370. QAction *action;
  4371. #define ADD_MODE(name, mode) \
  4372. action = menu->addAction(QTStr("" name), this, \
  4373. SLOT(SetBlendingMode())); \
  4374. action->setProperty("mode", (int)mode); \
  4375. action->setCheckable(true); \
  4376. action->setChecked(blendingMode == mode);
  4377. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4378. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4379. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4380. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4381. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4382. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4383. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4384. #undef ADD_MODE
  4385. return menu;
  4386. }
  4387. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4388. QWidgetAction *widgetAction,
  4389. ColorSelect *select,
  4390. obs_sceneitem_t *item)
  4391. {
  4392. QAction *action;
  4393. menu->setStyleSheet(QString(
  4394. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4395. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4396. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4397. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4398. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4399. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4400. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4401. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4402. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4403. obs_data_release(privData);
  4404. obs_data_set_default_int(privData, "color-preset", 0);
  4405. int preset = obs_data_get_int(privData, "color-preset");
  4406. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  4407. action->setCheckable(true);
  4408. action->setProperty("bgColor", 0);
  4409. action->setChecked(preset == 0);
  4410. action = menu->addAction(QTStr("CustomColor"), this,
  4411. +SLOT(ColorChange()));
  4412. action->setCheckable(true);
  4413. action->setProperty("bgColor", 1);
  4414. action->setChecked(preset == 1);
  4415. menu->addSeparator();
  4416. widgetAction->setDefaultWidget(select);
  4417. for (int i = 1; i < 9; i++) {
  4418. stringstream button;
  4419. button << "preset" << i;
  4420. QPushButton *colorButton =
  4421. select->findChild<QPushButton *>(button.str().c_str());
  4422. if (preset == i + 1)
  4423. colorButton->setStyleSheet("border: 2px solid black");
  4424. colorButton->setProperty("bgColor", i);
  4425. select->connect(colorButton, SIGNAL(released()), this,
  4426. SLOT(ColorChange()));
  4427. }
  4428. menu->addAction(widgetAction);
  4429. return menu;
  4430. }
  4431. ColorSelect::ColorSelect(QWidget *parent)
  4432. : QWidget(parent), ui(new Ui::ColorSelect)
  4433. {
  4434. ui->setupUi(this);
  4435. }
  4436. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4437. {
  4438. QMenu popup(this);
  4439. delete previewProjectorSource;
  4440. delete sourceProjector;
  4441. delete scaleFilteringMenu;
  4442. delete blendingMethodMenu;
  4443. delete blendingModeMenu;
  4444. delete colorMenu;
  4445. delete colorWidgetAction;
  4446. delete colorSelect;
  4447. delete deinterlaceMenu;
  4448. if (preview) {
  4449. QAction *action = popup.addAction(
  4450. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4451. SLOT(TogglePreview()));
  4452. action->setCheckable(true);
  4453. action->setChecked(
  4454. obs_display_enabled(ui->preview->GetDisplay()));
  4455. if (IsPreviewProgramMode())
  4456. action->setEnabled(false);
  4457. popup.addAction(ui->actionLockPreview);
  4458. popup.addMenu(ui->scalingMenu);
  4459. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4460. AddProjectorMenuMonitors(previewProjectorSource, this,
  4461. SLOT(OpenPreviewProjector()));
  4462. popup.addMenu(previewProjectorSource);
  4463. QAction *previewWindow =
  4464. popup.addAction(QTStr("PreviewWindow"), this,
  4465. SLOT(OpenPreviewWindow()));
  4466. popup.addAction(previewWindow);
  4467. popup.addAction(QTStr("Screenshot.Preview"), this,
  4468. SLOT(ScreenshotScene()));
  4469. popup.addSeparator();
  4470. }
  4471. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4472. if (addSourceMenu)
  4473. popup.addMenu(addSourceMenu);
  4474. if (ui->sources->MultipleBaseSelected()) {
  4475. popup.addSeparator();
  4476. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4477. SLOT(GroupSelectedItems()));
  4478. } else if (ui->sources->GroupsSelected()) {
  4479. popup.addSeparator();
  4480. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4481. SLOT(UngroupSelectedGroups()));
  4482. }
  4483. popup.addSeparator();
  4484. popup.addAction(ui->actionCopySource);
  4485. popup.addAction(ui->actionPasteRef);
  4486. popup.addAction(ui->actionPasteDup);
  4487. popup.addSeparator();
  4488. popup.addSeparator();
  4489. popup.addAction(ui->actionCopyFilters);
  4490. popup.addAction(ui->actionPasteFilters);
  4491. popup.addSeparator();
  4492. if (idx != -1) {
  4493. if (addSourceMenu)
  4494. popup.addSeparator();
  4495. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4496. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4497. uint32_t flags = obs_source_get_output_flags(source);
  4498. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4499. OBS_SOURCE_ASYNC_VIDEO;
  4500. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4501. colorMenu = new QMenu(QTStr("ChangeBG"));
  4502. colorWidgetAction = new QWidgetAction(colorMenu);
  4503. colorSelect = new ColorSelect(colorMenu);
  4504. popup.addMenu(AddBackgroundColorMenu(
  4505. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4506. popup.addAction(QTStr("Rename"), this,
  4507. SLOT(EditSceneItemName()));
  4508. popup.addAction(QTStr("Remove"), this,
  4509. SLOT(on_actionRemoveSource_triggered()));
  4510. popup.addSeparator();
  4511. popup.addMenu(ui->orderMenu);
  4512. popup.addMenu(ui->transformMenu);
  4513. popup.addSeparator();
  4514. if (hasAudio) {
  4515. QAction *actionHideMixer =
  4516. popup.addAction(QTStr("HideMixer"), this,
  4517. SLOT(ToggleHideMixer()));
  4518. actionHideMixer->setCheckable(true);
  4519. actionHideMixer->setChecked(SourceMixerHidden(source));
  4520. popup.addSeparator();
  4521. }
  4522. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4523. popup.addMenu(
  4524. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4525. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4526. popup.addMenu(AddBlendingModeMenu(blendingModeMenu, sceneItem));
  4527. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4528. popup.addMenu(
  4529. AddBlendingMethodMenu(blendingMethodMenu, sceneItem));
  4530. if (isAsyncVideo) {
  4531. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4532. popup.addMenu(
  4533. AddDeinterlacingMenu(deinterlaceMenu, source));
  4534. }
  4535. popup.addSeparator();
  4536. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4537. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4538. popup.addSeparator();
  4539. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4540. AddProjectorMenuMonitors(sourceProjector, this,
  4541. SLOT(OpenSourceProjector()));
  4542. popup.addMenu(sourceProjector);
  4543. popup.addAction(QTStr("SourceWindow"), this,
  4544. SLOT(OpenSourceWindow()));
  4545. popup.addAction(QTStr("Screenshot.Source"), this,
  4546. SLOT(ScreenshotSelectedSource()));
  4547. popup.addSeparator();
  4548. if (flags & OBS_SOURCE_INTERACTION)
  4549. popup.addAction(QTStr("Interact"), this,
  4550. SLOT(on_actionInteract_triggered()));
  4551. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4552. QAction *action = popup.addAction(
  4553. QTStr("Properties"), this,
  4554. SLOT(on_actionSourceProperties_triggered()));
  4555. action->setEnabled(obs_source_configurable(source));
  4556. }
  4557. popup.exec(QCursor::pos());
  4558. }
  4559. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4560. {
  4561. if (ui->scenes->count()) {
  4562. QModelIndex idx = ui->sources->indexAt(pos);
  4563. CreateSourcePopupMenu(idx.row(), false);
  4564. }
  4565. }
  4566. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4567. {
  4568. if (!witem)
  4569. return;
  4570. if (IsPreviewProgramMode()) {
  4571. bool doubleClickSwitch =
  4572. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4573. "TransitionOnDoubleClick");
  4574. if (doubleClickSwitch)
  4575. TransitionClicked();
  4576. }
  4577. }
  4578. static inline bool should_show_properties(obs_source_t *source, const char *id)
  4579. {
  4580. if (!source)
  4581. return false;
  4582. if (strcmp(id, "group") == 0)
  4583. return false;
  4584. if (!obs_source_configurable(source))
  4585. return false;
  4586. uint32_t caps = obs_source_get_output_flags(source);
  4587. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  4588. return false;
  4589. return true;
  4590. }
  4591. void OBSBasic::AddSource(const char *id)
  4592. {
  4593. if (id && *id) {
  4594. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  4595. sourceSelect.exec();
  4596. if (should_show_properties(sourceSelect.newSource, id)) {
  4597. CreatePropertiesWindow(sourceSelect.newSource);
  4598. }
  4599. }
  4600. }
  4601. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4602. {
  4603. const char *unversioned_type;
  4604. const char *type;
  4605. bool foundValues = false;
  4606. bool foundDeprecated = false;
  4607. size_t idx = 0;
  4608. QMenu *popup = new QMenu(QTStr("Add"), this);
  4609. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4610. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4611. QList<QAction *> actions = menu->actions();
  4612. for (QAction *menuAction : actions) {
  4613. if (menuAction->text().compare(name) >= 0)
  4614. return menuAction;
  4615. }
  4616. return (QAction *)nullptr;
  4617. };
  4618. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4619. const char *name) {
  4620. QString qname = QT_UTF8(name);
  4621. QAction *popupItem = new QAction(qname, this);
  4622. popupItem->setData(QT_UTF8(type));
  4623. connect(popupItem, SIGNAL(triggered(bool)), this,
  4624. SLOT(AddSourceFromAction()));
  4625. QIcon icon;
  4626. if (strcmp(type, "scene") == 0)
  4627. icon = GetSceneIcon();
  4628. else
  4629. icon = GetSourceIcon(type);
  4630. popupItem->setIcon(icon);
  4631. QAction *after = getActionAfter(popup, qname);
  4632. popup->insertAction(after, popupItem);
  4633. };
  4634. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4635. const char *name = obs_source_get_display_name(type);
  4636. uint32_t caps = obs_get_source_output_flags(type);
  4637. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4638. continue;
  4639. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4640. addSource(popup, unversioned_type, name);
  4641. } else {
  4642. addSource(deprecated, unversioned_type, name);
  4643. foundDeprecated = true;
  4644. }
  4645. foundValues = true;
  4646. }
  4647. addSource(popup, "scene", Str("Basic.Scene"));
  4648. popup->addSeparator();
  4649. QAction *addGroup = new QAction(QTStr("Group"), this);
  4650. addGroup->setData(QT_UTF8("group"));
  4651. addGroup->setIcon(GetGroupIcon());
  4652. connect(addGroup, SIGNAL(triggered(bool)), this,
  4653. SLOT(AddSourceFromAction()));
  4654. popup->addAction(addGroup);
  4655. if (!foundDeprecated) {
  4656. delete deprecated;
  4657. deprecated = nullptr;
  4658. }
  4659. if (!foundValues) {
  4660. delete popup;
  4661. popup = nullptr;
  4662. } else if (foundDeprecated) {
  4663. popup->addSeparator();
  4664. popup->addMenu(deprecated);
  4665. }
  4666. return popup;
  4667. }
  4668. void OBSBasic::AddSourceFromAction()
  4669. {
  4670. QAction *action = qobject_cast<QAction *>(sender());
  4671. if (!action)
  4672. return;
  4673. AddSource(QT_TO_UTF8(action->data().toString()));
  4674. }
  4675. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4676. {
  4677. if (!GetCurrentScene()) {
  4678. // Tell the user he needs a scene first (help beginners).
  4679. OBSMessageBox::information(
  4680. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4681. QTStr("Basic.Main.AddSourceHelp.Text"));
  4682. return;
  4683. }
  4684. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4685. if (popup)
  4686. popup->exec(pos);
  4687. }
  4688. void OBSBasic::on_actionAddSource_triggered()
  4689. {
  4690. AddSourcePopupMenu(QCursor::pos());
  4691. }
  4692. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4693. {
  4694. vector<OBSSceneItem> &items =
  4695. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4696. if (obs_sceneitem_selected(item)) {
  4697. items.emplace_back(item);
  4698. } else if (obs_sceneitem_is_group(item)) {
  4699. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4700. }
  4701. return true;
  4702. };
  4703. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  4704. std::vector<obs_source_t *> *sources)
  4705. {
  4706. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  4707. if (!sources) {
  4708. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  4709. } else {
  4710. for (obs_source_t *source : *sources) {
  4711. obs_data_t *source_data = obs_save_source(source);
  4712. obs_data_array_push_back(undo_array, source_data);
  4713. obs_data_release(source_data);
  4714. }
  4715. }
  4716. OBSDataAutoRelease scene_data =
  4717. obs_save_source(obs_scene_get_source(scene));
  4718. obs_data_array_push_back(undo_array, scene_data);
  4719. OBSDataAutoRelease data = obs_data_create();
  4720. obs_data_set_array(data, "array", undo_array);
  4721. obs_data_get_json(data);
  4722. return data.Get();
  4723. }
  4724. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  4725. {
  4726. auto sources = static_cast<std::vector<OBSSource> *>(p);
  4727. sources->push_back(obs_sceneitem_get_source(item));
  4728. return true;
  4729. }
  4730. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  4731. OBSData undo_data, OBSData redo_data)
  4732. {
  4733. auto undo_redo = [this](const std::string &json) {
  4734. OBSDataAutoRelease base =
  4735. obs_data_create_from_json(json.c_str());
  4736. OBSDataArrayAutoRelease array =
  4737. obs_data_get_array(base, "array");
  4738. std::vector<OBSSource> sources;
  4739. std::vector<OBSSource> old_sources;
  4740. /* create missing sources */
  4741. const size_t count = obs_data_array_count(array);
  4742. sources.reserve(count);
  4743. for (size_t i = 0; i < count; i++) {
  4744. OBSDataAutoRelease data = obs_data_array_item(array, i);
  4745. const char *name = obs_data_get_string(data, "name");
  4746. OBSSourceAutoRelease source =
  4747. obs_get_source_by_name(name);
  4748. if (!source)
  4749. source = obs_load_source(data);
  4750. sources.push_back(source.Get());
  4751. /* update scene/group settings to restore their
  4752. * contents to their saved settings */
  4753. obs_scene_t *scene =
  4754. obs_group_or_scene_from_source(source);
  4755. if (scene) {
  4756. obs_scene_enum_items(scene, add_source_enum,
  4757. &old_sources);
  4758. OBSDataAutoRelease scene_settings =
  4759. obs_data_get_obj(data, "settings");
  4760. obs_source_update(source, scene_settings);
  4761. }
  4762. }
  4763. /* actually load sources now */
  4764. for (obs_source_t *source : sources)
  4765. obs_source_load2(source);
  4766. ui->sources->RefreshItems();
  4767. };
  4768. const char *undo_json = obs_data_get_last_json(undo_data);
  4769. const char *redo_json = obs_data_get_last_json(redo_data);
  4770. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  4771. redo_json);
  4772. }
  4773. void OBSBasic::on_actionRemoveSource_triggered()
  4774. {
  4775. vector<OBSSceneItem> items;
  4776. OBSScene scene = GetCurrentScene();
  4777. obs_source_t *scene_source = obs_scene_get_source(scene);
  4778. obs_scene_enum_items(scene, remove_items, &items);
  4779. if (!items.size())
  4780. return;
  4781. /* ------------------------------------- */
  4782. /* confirm action with user */
  4783. bool confirmed = false;
  4784. if (items.size() > 1) {
  4785. QString text = QTStr("ConfirmRemove.TextMultiple")
  4786. .arg(QString::number(items.size()));
  4787. QMessageBox remove_items(this);
  4788. remove_items.setText(text);
  4789. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4790. QMessageBox::YesRole);
  4791. remove_items.setDefaultButton(Yes);
  4792. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4793. remove_items.setIcon(QMessageBox::Question);
  4794. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4795. remove_items.exec();
  4796. confirmed = Yes == remove_items.clickedButton();
  4797. } else {
  4798. OBSSceneItem &item = items[0];
  4799. obs_source_t *source = obs_sceneitem_get_source(item);
  4800. if (source && QueryRemoveSource(source))
  4801. confirmed = true;
  4802. }
  4803. if (!confirmed)
  4804. return;
  4805. /* ----------------------------------------------- */
  4806. /* save undo data */
  4807. OBSData undo_data = BackupScene(scene_source);
  4808. /* ----------------------------------------------- */
  4809. /* remove items */
  4810. for (auto &item : items)
  4811. obs_sceneitem_remove(item);
  4812. /* ----------------------------------------------- */
  4813. /* save redo data */
  4814. OBSData redo_data = BackupScene(scene_source);
  4815. /* ----------------------------------------------- */
  4816. /* add undo/redo action */
  4817. QString action_name;
  4818. if (items.size() > 1) {
  4819. action_name = QTStr("Undo.Sources.Multi")
  4820. .arg(QString::number(items.size()));
  4821. } else {
  4822. QString str = QTStr("Undo.Delete");
  4823. action_name = str.arg(obs_source_get_name(
  4824. obs_sceneitem_get_source(items[0])));
  4825. }
  4826. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  4827. }
  4828. void OBSBasic::on_actionInteract_triggered()
  4829. {
  4830. OBSSceneItem item = GetCurrentSceneItem();
  4831. OBSSource source = obs_sceneitem_get_source(item);
  4832. if (source)
  4833. CreateInteractionWindow(source);
  4834. }
  4835. void OBSBasic::on_actionSourceProperties_triggered()
  4836. {
  4837. OBSSceneItem item = GetCurrentSceneItem();
  4838. OBSSource source = obs_sceneitem_get_source(item);
  4839. if (source)
  4840. CreatePropertiesWindow(source);
  4841. }
  4842. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  4843. const QString &action_name)
  4844. {
  4845. OBSSceneItem item = GetCurrentSceneItem();
  4846. obs_source_t *source = obs_sceneitem_get_source(item);
  4847. if (!source)
  4848. return;
  4849. OBSScene scene = GetCurrentScene();
  4850. std::vector<obs_source_t *> sources;
  4851. if (scene != obs_sceneitem_get_scene(item))
  4852. sources.push_back(
  4853. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  4854. OBSData undo_data = BackupScene(scene, &sources);
  4855. obs_sceneitem_set_order(item, movement);
  4856. const char *source_name = obs_source_get_name(source);
  4857. const char *scene_name =
  4858. obs_source_get_name(obs_scene_get_source(scene));
  4859. OBSData redo_data = BackupScene(scene, &sources);
  4860. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  4861. undo_data, redo_data);
  4862. }
  4863. void OBSBasic::on_actionSourceUp_triggered()
  4864. {
  4865. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4866. }
  4867. void OBSBasic::on_actionSourceDown_triggered()
  4868. {
  4869. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4870. }
  4871. void OBSBasic::on_actionMoveUp_triggered()
  4872. {
  4873. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4874. }
  4875. void OBSBasic::on_actionMoveDown_triggered()
  4876. {
  4877. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4878. }
  4879. void OBSBasic::on_actionMoveToTop_triggered()
  4880. {
  4881. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  4882. }
  4883. void OBSBasic::on_actionMoveToBottom_triggered()
  4884. {
  4885. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  4886. }
  4887. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4888. {
  4889. char logDir[512];
  4890. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4891. return nullptr;
  4892. string path = logDir;
  4893. path += "/";
  4894. path += log;
  4895. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4896. if (!file)
  4897. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4898. return file;
  4899. }
  4900. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4901. {
  4902. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4903. if (!fileString)
  4904. return;
  4905. if (!*fileString)
  4906. return;
  4907. ui->menuLogFiles->setEnabled(false);
  4908. #if defined(_WIN32)
  4909. ui->menuCrashLogs->setEnabled(false);
  4910. #endif
  4911. stringstream ss;
  4912. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4913. << CurrentDateTimeString() << "\n\n"
  4914. << fileString;
  4915. if (logUploadThread) {
  4916. logUploadThread->wait();
  4917. }
  4918. RemoteTextThread *thread =
  4919. new RemoteTextThread("https://obsproject.com/logs/upload",
  4920. "text/plain", ss.str().c_str());
  4921. logUploadThread.reset(thread);
  4922. if (crash) {
  4923. connect(thread, &RemoteTextThread::Result, this,
  4924. &OBSBasic::crashUploadFinished);
  4925. } else {
  4926. connect(thread, &RemoteTextThread::Result, this,
  4927. &OBSBasic::logUploadFinished);
  4928. }
  4929. logUploadThread->start();
  4930. }
  4931. void OBSBasic::on_actionShowLogs_triggered()
  4932. {
  4933. char logDir[512];
  4934. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4935. return;
  4936. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4937. QDesktopServices::openUrl(url);
  4938. }
  4939. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4940. {
  4941. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  4942. }
  4943. void OBSBasic::on_actionUploadLastLog_triggered()
  4944. {
  4945. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  4946. }
  4947. void OBSBasic::on_actionViewCurrentLog_triggered()
  4948. {
  4949. if (!logView)
  4950. logView = new OBSLogViewer();
  4951. logView->show();
  4952. logView->setWindowState(
  4953. (logView->windowState() & ~Qt::WindowMinimized) |
  4954. Qt::WindowActive);
  4955. logView->activateWindow();
  4956. logView->raise();
  4957. }
  4958. void OBSBasic::on_actionShowCrashLogs_triggered()
  4959. {
  4960. char logDir[512];
  4961. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4962. return;
  4963. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4964. QDesktopServices::openUrl(url);
  4965. }
  4966. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4967. {
  4968. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  4969. }
  4970. void OBSBasic::on_actionCheckForUpdates_triggered()
  4971. {
  4972. CheckForUpdates(true);
  4973. }
  4974. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4975. {
  4976. ui->menuLogFiles->setEnabled(true);
  4977. #if defined(_WIN32)
  4978. ui->menuCrashLogs->setEnabled(true);
  4979. #endif
  4980. if (text.isEmpty()) {
  4981. OBSMessageBox::critical(
  4982. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4983. error);
  4984. return;
  4985. }
  4986. openLogDialog(text, false);
  4987. }
  4988. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  4989. {
  4990. ui->menuLogFiles->setEnabled(true);
  4991. #if defined(_WIN32)
  4992. ui->menuCrashLogs->setEnabled(true);
  4993. #endif
  4994. if (text.isEmpty()) {
  4995. OBSMessageBox::critical(
  4996. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4997. error);
  4998. return;
  4999. }
  5000. openLogDialog(text, true);
  5001. }
  5002. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5003. {
  5004. OBSDataAutoRelease returnData =
  5005. obs_data_create_from_json(QT_TO_UTF8(text));
  5006. string resURL = obs_data_get_string(returnData, "url");
  5007. QString logURL = resURL.c_str();
  5008. OBSLogReply logDialog(this, logURL, crash);
  5009. logDialog.exec();
  5010. }
  5011. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5012. obs_source_t *source, const string &name)
  5013. {
  5014. const char *prevName = obs_source_get_name(source);
  5015. if (name == prevName)
  5016. return;
  5017. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5018. QListWidgetItem *listItem = listWidget->currentItem();
  5019. if (foundSource || name.empty()) {
  5020. listItem->setText(QT_UTF8(prevName));
  5021. if (foundSource) {
  5022. OBSMessageBox::warning(parent,
  5023. QTStr("NameExists.Title"),
  5024. QTStr("NameExists.Text"));
  5025. } else if (name.empty()) {
  5026. OBSMessageBox::warning(parent,
  5027. QTStr("NoNameEntered.Title"),
  5028. QTStr("NoNameEntered.Text"));
  5029. }
  5030. } else {
  5031. auto undo = [prev = std::string(prevName)](
  5032. const std::string &data) {
  5033. OBSSourceAutoRelease source =
  5034. obs_get_source_by_name(data.c_str());
  5035. obs_source_set_name(source, prev.c_str());
  5036. };
  5037. auto redo = [name](const std::string &data) {
  5038. OBSSourceAutoRelease source =
  5039. obs_get_source_by_name(data.c_str());
  5040. obs_source_set_name(source, name.c_str());
  5041. };
  5042. std::string undo_data(name);
  5043. std::string redo_data(prevName);
  5044. parent->undo_s.add_action(
  5045. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5046. undo_data, redo_data);
  5047. listItem->setText(QT_UTF8(name.c_str()));
  5048. obs_source_set_name(source, name.c_str());
  5049. }
  5050. }
  5051. void OBSBasic::SceneNameEdited(QWidget *editor,
  5052. QAbstractItemDelegate::EndEditHint endHint)
  5053. {
  5054. OBSScene scene = GetCurrentScene();
  5055. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5056. string text = QT_TO_UTF8(edit->text().trimmed());
  5057. if (!scene)
  5058. return;
  5059. obs_source_t *source = obs_scene_get_source(scene);
  5060. RenameListItem(this, ui->scenes, source, text);
  5061. ui->scenesDock->addAction(renameScene);
  5062. if (api)
  5063. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5064. UNUSED_PARAMETER(endHint);
  5065. }
  5066. void OBSBasic::OpenFilters(OBSSource source)
  5067. {
  5068. if (source == nullptr) {
  5069. OBSSceneItem item = GetCurrentSceneItem();
  5070. source = obs_sceneitem_get_source(item);
  5071. }
  5072. CreateFiltersWindow(source);
  5073. }
  5074. void OBSBasic::OpenProperties(OBSSource source)
  5075. {
  5076. if (source == nullptr) {
  5077. OBSSceneItem item = GetCurrentSceneItem();
  5078. source = obs_sceneitem_get_source(item);
  5079. }
  5080. CreatePropertiesWindow(source);
  5081. }
  5082. void OBSBasic::OpenInteraction(OBSSource source)
  5083. {
  5084. if (source == nullptr) {
  5085. OBSSceneItem item = GetCurrentSceneItem();
  5086. source = obs_sceneitem_get_source(item);
  5087. }
  5088. CreateInteractionWindow(source);
  5089. }
  5090. void OBSBasic::OpenSceneFilters()
  5091. {
  5092. OBSScene scene = GetCurrentScene();
  5093. OBSSource source = obs_scene_get_source(scene);
  5094. CreateFiltersWindow(source);
  5095. }
  5096. #define RECORDING_START \
  5097. "==== Recording Start ==============================================="
  5098. #define RECORDING_STOP \
  5099. "==== Recording Stop ================================================"
  5100. #define REPLAY_BUFFER_START \
  5101. "==== Replay Buffer Start ==========================================="
  5102. #define REPLAY_BUFFER_STOP \
  5103. "==== Replay Buffer Stop ============================================"
  5104. #define STREAMING_START \
  5105. "==== Streaming Start ==============================================="
  5106. #define STREAMING_STOP \
  5107. "==== Streaming Stop ================================================"
  5108. #define VIRTUAL_CAM_START \
  5109. "==== Virtual Camera Start =========================================="
  5110. #define VIRTUAL_CAM_STOP \
  5111. "==== Virtual Camera Stop ==========================================="
  5112. void OBSBasic::DisplayStreamStartError()
  5113. {
  5114. QString message = !outputHandler->lastError.empty()
  5115. ? QTStr(outputHandler->lastError.c_str())
  5116. : QTStr("Output.StartFailedGeneric");
  5117. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5118. ui->streamButton->setEnabled(true);
  5119. ui->streamButton->setChecked(false);
  5120. if (sysTrayStream) {
  5121. sysTrayStream->setText(ui->streamButton->text());
  5122. sysTrayStream->setEnabled(true);
  5123. }
  5124. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5125. }
  5126. #if YOUTUBE_ENABLED
  5127. void OBSBasic::YouTubeActionDialogOk(const QString &id, const QString &key,
  5128. bool autostart, bool autostop,
  5129. bool start_now)
  5130. {
  5131. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5132. obs_service_t *service_obj = GetService();
  5133. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5134. const std::string a_key = QT_TO_UTF8(key);
  5135. obs_data_set_string(settings, "key", a_key.c_str());
  5136. const std::string an_id = QT_TO_UTF8(id);
  5137. obs_data_set_string(settings, "stream_id", an_id.c_str());
  5138. obs_service_update(service_obj, settings);
  5139. autoStartBroadcast = autostart;
  5140. autoStopBroadcast = autostop;
  5141. broadcastReady = true;
  5142. if (start_now)
  5143. QMetaObject::invokeMethod(this, "StartStreaming");
  5144. }
  5145. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5146. {
  5147. YoutubeApiWrappers *apiYouTube(
  5148. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5149. if (!apiYouTube) {
  5150. /* technically we should never get here -Jim */
  5151. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5152. Qt::QueuedConnection);
  5153. youtubeStreamCheckThread->deleteLater();
  5154. blog(LOG_ERROR, "==========================================");
  5155. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5156. blog(LOG_ERROR, "==========================================");
  5157. return;
  5158. }
  5159. int timeout = 0;
  5160. json11::Json json;
  5161. QString id = key.c_str();
  5162. while (StreamingActive()) {
  5163. if (timeout == 14) {
  5164. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5165. Qt::QueuedConnection);
  5166. break;
  5167. }
  5168. if (!apiYouTube->FindStream(id, json)) {
  5169. QMetaObject::invokeMethod(this,
  5170. "DisplayStreamStartError",
  5171. Qt::QueuedConnection);
  5172. QMetaObject::invokeMethod(this, "StopStreaming",
  5173. Qt::QueuedConnection);
  5174. break;
  5175. }
  5176. auto item = json["items"][0];
  5177. auto status = item["status"]["streamStatus"].string_value();
  5178. if (status == "active") {
  5179. QMetaObject::invokeMethod(ui->broadcastButton,
  5180. "setEnabled",
  5181. Q_ARG(bool, true));
  5182. break;
  5183. } else {
  5184. QThread::sleep(1);
  5185. timeout++;
  5186. }
  5187. }
  5188. youtubeStreamCheckThread->deleteLater();
  5189. }
  5190. void OBSBasic::ShowYouTubeAutoStartWarning()
  5191. {
  5192. auto msgBox = []() {
  5193. QMessageBox msgbox(App()->GetMainWindow());
  5194. msgbox.setWindowTitle(QTStr(
  5195. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5196. msgbox.setText(
  5197. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5198. msgbox.setIcon(QMessageBox::Icon::Information);
  5199. msgbox.addButton(QMessageBox::Ok);
  5200. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5201. msgbox.setCheckBox(cb);
  5202. msgbox.exec();
  5203. if (cb->isChecked()) {
  5204. config_set_bool(App()->GlobalConfig(), "General",
  5205. "WarnedAboutYouTubeAutoStart", true);
  5206. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5207. }
  5208. };
  5209. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5210. "WarnedAboutYouTubeAutoStart");
  5211. if (!warned) {
  5212. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5213. Q_ARG(VoidFunc, msgBox));
  5214. }
  5215. }
  5216. #endif
  5217. void OBSBasic::StartStreaming()
  5218. {
  5219. if (outputHandler->StreamingActive())
  5220. return;
  5221. if (disableOutputsRef)
  5222. return;
  5223. if (auth && auth->broadcastFlow()) {
  5224. if (!broadcastActive && !broadcastReady) {
  5225. ui->streamButton->setChecked(false);
  5226. QMessageBox no_broadcast(this);
  5227. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5228. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5229. QTStr("Basic.Main.SetupBroadcast"),
  5230. QMessageBox::YesRole);
  5231. no_broadcast.setDefaultButton(SetupBroadcast);
  5232. no_broadcast.addButton(QTStr("Close"),
  5233. QMessageBox::NoRole);
  5234. no_broadcast.setIcon(QMessageBox::Information);
  5235. no_broadcast.setWindowTitle(
  5236. QTStr("Output.NoBroadcast.Title"));
  5237. no_broadcast.exec();
  5238. if (no_broadcast.clickedButton() == SetupBroadcast)
  5239. QMetaObject::invokeMethod(this,
  5240. "SetupBroadcast");
  5241. return;
  5242. }
  5243. }
  5244. if (!outputHandler->SetupStreaming(service)) {
  5245. DisplayStreamStartError();
  5246. return;
  5247. }
  5248. if (api)
  5249. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5250. SaveProject();
  5251. ui->streamButton->setEnabled(false);
  5252. ui->streamButton->setChecked(false);
  5253. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5254. ui->broadcastButton->setChecked(false);
  5255. if (sysTrayStream) {
  5256. sysTrayStream->setEnabled(false);
  5257. sysTrayStream->setText(ui->streamButton->text());
  5258. }
  5259. if (!outputHandler->StartStreaming(service)) {
  5260. DisplayStreamStartError();
  5261. return;
  5262. }
  5263. if (!autoStartBroadcast) {
  5264. ui->broadcastButton->setText(
  5265. QTStr("Basic.Main.StartBroadcast"));
  5266. ui->broadcastButton->setProperty("broadcastState", "ready");
  5267. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5268. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5269. // well, we need to disable button while stream is not active
  5270. ui->broadcastButton->setEnabled(false);
  5271. } else {
  5272. if (!autoStopBroadcast) {
  5273. ui->broadcastButton->setText(
  5274. QTStr("Basic.Main.StopBroadcast"));
  5275. } else {
  5276. ui->broadcastButton->setText(
  5277. QTStr("Basic.Main.AutoStopEnabled"));
  5278. ui->broadcastButton->setEnabled(false);
  5279. }
  5280. ui->broadcastButton->setProperty("broadcastState", "active");
  5281. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5282. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5283. broadcastActive = true;
  5284. }
  5285. bool recordWhenStreaming = config_get_bool(
  5286. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5287. if (recordWhenStreaming)
  5288. StartRecording();
  5289. bool replayBufferWhileStreaming = config_get_bool(
  5290. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5291. if (replayBufferWhileStreaming)
  5292. StartReplayBuffer();
  5293. #if YOUTUBE_ENABLED
  5294. if (!autoStartBroadcast)
  5295. OBSBasic::ShowYouTubeAutoStartWarning();
  5296. #endif
  5297. }
  5298. void OBSBasic::BroadcastButtonClicked()
  5299. {
  5300. if (!broadcastReady ||
  5301. (!broadcastActive && !outputHandler->StreamingActive())) {
  5302. SetupBroadcast();
  5303. if (broadcastReady)
  5304. ui->broadcastButton->setChecked(true);
  5305. return;
  5306. }
  5307. if (!autoStartBroadcast) {
  5308. #if YOUTUBE_ENABLED
  5309. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5310. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5311. if (ytAuth.get()) {
  5312. if (!ytAuth->StartLatestBroadcast()) {
  5313. auto last_error = ytAuth->GetLastError();
  5314. if (last_error.isEmpty())
  5315. last_error = QTStr(
  5316. "YouTube.Actions.Error.YouTubeApi");
  5317. if (!ytAuth->GetTranslatedError(last_error))
  5318. last_error =
  5319. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5320. .arg(last_error,
  5321. ytAuth->GetBroadcastId());
  5322. OBSMessageBox::warning(
  5323. this,
  5324. QTStr("Output.BroadcastStartFailed"),
  5325. last_error, true);
  5326. ui->broadcastButton->setChecked(false);
  5327. return;
  5328. }
  5329. }
  5330. #endif
  5331. broadcastActive = true;
  5332. autoStartBroadcast = true; // and clear the flag
  5333. if (!autoStopBroadcast) {
  5334. ui->broadcastButton->setText(
  5335. QTStr("Basic.Main.StopBroadcast"));
  5336. } else {
  5337. ui->broadcastButton->setText(
  5338. QTStr("Basic.Main.AutoStopEnabled"));
  5339. ui->broadcastButton->setEnabled(false);
  5340. }
  5341. ui->broadcastButton->setProperty("broadcastState", "active");
  5342. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5343. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5344. } else if (!autoStopBroadcast) {
  5345. #if YOUTUBE_ENABLED
  5346. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5347. "WarnBeforeStoppingStream");
  5348. if (confirm && isVisible()) {
  5349. QMessageBox::StandardButton button = OBSMessageBox::question(
  5350. this, QTStr("ConfirmStop.Title"),
  5351. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5352. QMessageBox::Yes | QMessageBox::No,
  5353. QMessageBox::No);
  5354. if (button == QMessageBox::No) {
  5355. ui->broadcastButton->setChecked(true);
  5356. return;
  5357. }
  5358. }
  5359. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5360. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5361. if (ytAuth.get()) {
  5362. if (!ytAuth->StopLatestBroadcast()) {
  5363. auto last_error = ytAuth->GetLastError();
  5364. if (last_error.isEmpty())
  5365. last_error = QTStr(
  5366. "YouTube.Actions.Error.YouTubeApi");
  5367. if (!ytAuth->GetTranslatedError(last_error))
  5368. last_error =
  5369. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5370. .arg(last_error,
  5371. ytAuth->GetBroadcastId());
  5372. OBSMessageBox::warning(
  5373. this,
  5374. QTStr("Output.BroadcastStopFailed"),
  5375. last_error, true);
  5376. }
  5377. }
  5378. #endif
  5379. broadcastActive = false;
  5380. broadcastReady = false;
  5381. autoStopBroadcast = true;
  5382. QMetaObject::invokeMethod(this, "StopStreaming");
  5383. SetBroadcastFlowEnabled(true);
  5384. }
  5385. }
  5386. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5387. {
  5388. ui->broadcastButton->setEnabled(enabled);
  5389. ui->broadcastButton->setVisible(enabled);
  5390. ui->broadcastButton->setChecked(broadcastReady);
  5391. ui->broadcastButton->setProperty("broadcastState", "idle");
  5392. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5393. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5394. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5395. }
  5396. void OBSBasic::SetupBroadcast()
  5397. {
  5398. #if YOUTUBE_ENABLED
  5399. Auth *const auth = GetAuth();
  5400. if (IsYouTubeService(auth->service())) {
  5401. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5402. connect(&dialog, &OBSYoutubeActions::ok, this,
  5403. &OBSBasic::YouTubeActionDialogOk);
  5404. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5405. if (result != QDialog::Accepted) {
  5406. if (!broadcastReady)
  5407. ui->broadcastButton->setChecked(false);
  5408. }
  5409. }
  5410. #endif
  5411. }
  5412. #ifdef _WIN32
  5413. static inline void UpdateProcessPriority()
  5414. {
  5415. const char *priority = config_get_string(App()->GlobalConfig(),
  5416. "General", "ProcessPriority");
  5417. if (priority && strcmp(priority, "Normal") != 0)
  5418. SetProcessPriority(priority);
  5419. }
  5420. static inline void ClearProcessPriority()
  5421. {
  5422. const char *priority = config_get_string(App()->GlobalConfig(),
  5423. "General", "ProcessPriority");
  5424. if (priority && strcmp(priority, "Normal") != 0)
  5425. SetProcessPriority("Normal");
  5426. }
  5427. #else
  5428. #define UpdateProcessPriority() \
  5429. do { \
  5430. } while (false)
  5431. #define ClearProcessPriority() \
  5432. do { \
  5433. } while (false)
  5434. #endif
  5435. inline void OBSBasic::OnActivate(bool force)
  5436. {
  5437. if (ui->profileMenu->isEnabled() || force) {
  5438. ui->profileMenu->setEnabled(false);
  5439. ui->autoConfigure->setEnabled(false);
  5440. App()->IncrementSleepInhibition();
  5441. UpdateProcessPriority();
  5442. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5443. if (trayIcon && trayIcon->isVisible()) {
  5444. #ifdef __APPLE__
  5445. QIcon trayMask =
  5446. QIcon(":/res/images/tray_active_macos.svg");
  5447. trayMask.setIsMask(true);
  5448. trayIcon->setIcon(
  5449. QIcon::fromTheme("obs-tray", trayMask));
  5450. #else
  5451. trayIcon->setIcon(QIcon::fromTheme(
  5452. "obs-tray-active",
  5453. QIcon(":/res/images/tray_active.png")));
  5454. #endif
  5455. }
  5456. }
  5457. }
  5458. extern volatile bool recording_paused;
  5459. extern volatile bool replaybuf_active;
  5460. inline void OBSBasic::OnDeactivate()
  5461. {
  5462. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5463. ui->profileMenu->setEnabled(true);
  5464. ui->autoConfigure->setEnabled(true);
  5465. App()->DecrementSleepInhibition();
  5466. ClearProcessPriority();
  5467. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5468. if (trayIcon && trayIcon->isVisible()) {
  5469. #ifdef __APPLE__
  5470. QIcon trayIconFile =
  5471. QIcon(":/res/images/obs_macos.svg");
  5472. trayIconFile.setIsMask(true);
  5473. #else
  5474. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5475. #endif
  5476. trayIcon->setIcon(
  5477. QIcon::fromTheme("obs-tray", trayIconFile));
  5478. }
  5479. } else if (outputHandler->Active() && trayIcon &&
  5480. trayIcon->isVisible()) {
  5481. if (os_atomic_load_bool(&recording_paused)) {
  5482. #ifdef __APPLE__
  5483. QIcon trayIconFile =
  5484. QIcon(":/res/images/obs_paused_macos.svg");
  5485. trayIconFile.setIsMask(true);
  5486. #else
  5487. QIcon trayIconFile =
  5488. QIcon(":/res/images/obs_paused.png");
  5489. #endif
  5490. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5491. trayIconFile));
  5492. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5493. } else {
  5494. #ifdef __APPLE__
  5495. QIcon trayIconFile =
  5496. QIcon(":/res/images/tray_active_macos.svg");
  5497. trayIconFile.setIsMask(true);
  5498. #else
  5499. QIcon trayIconFile =
  5500. QIcon(":/res/images/tray_active.png");
  5501. #endif
  5502. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5503. trayIconFile));
  5504. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5505. }
  5506. }
  5507. }
  5508. void OBSBasic::StopStreaming()
  5509. {
  5510. SaveProject();
  5511. if (outputHandler->StreamingActive())
  5512. outputHandler->StopStreaming(streamingStopping);
  5513. // special case: force reset broadcast state if
  5514. // no autostart and no autostop selected
  5515. if (!autoStartBroadcast && !broadcastActive) {
  5516. broadcastActive = false;
  5517. autoStartBroadcast = true;
  5518. autoStopBroadcast = true;
  5519. broadcastReady = false;
  5520. }
  5521. if (autoStopBroadcast) {
  5522. broadcastActive = false;
  5523. broadcastReady = false;
  5524. }
  5525. OnDeactivate();
  5526. bool recordWhenStreaming = config_get_bool(
  5527. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5528. bool keepRecordingWhenStreamStops =
  5529. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5530. "KeepRecordingWhenStreamStops");
  5531. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5532. StopRecording();
  5533. bool replayBufferWhileStreaming = config_get_bool(
  5534. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5535. bool keepReplayBufferStreamStops =
  5536. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5537. "KeepReplayBufferStreamStops");
  5538. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5539. StopReplayBuffer();
  5540. }
  5541. void OBSBasic::ForceStopStreaming()
  5542. {
  5543. SaveProject();
  5544. if (outputHandler->StreamingActive())
  5545. outputHandler->StopStreaming(true);
  5546. // special case: force reset broadcast state if
  5547. // no autostart and no autostop selected
  5548. if (!autoStartBroadcast && !broadcastActive) {
  5549. broadcastActive = false;
  5550. autoStartBroadcast = true;
  5551. autoStopBroadcast = true;
  5552. broadcastReady = false;
  5553. }
  5554. if (autoStopBroadcast) {
  5555. broadcastActive = false;
  5556. broadcastReady = false;
  5557. }
  5558. OnDeactivate();
  5559. bool recordWhenStreaming = config_get_bool(
  5560. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5561. bool keepRecordingWhenStreamStops =
  5562. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5563. "KeepRecordingWhenStreamStops");
  5564. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5565. StopRecording();
  5566. bool replayBufferWhileStreaming = config_get_bool(
  5567. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5568. bool keepReplayBufferStreamStops =
  5569. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5570. "KeepReplayBufferStreamStops");
  5571. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5572. StopReplayBuffer();
  5573. }
  5574. void OBSBasic::StreamDelayStarting(int sec)
  5575. {
  5576. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5577. ui->streamButton->setEnabled(true);
  5578. ui->streamButton->setChecked(true);
  5579. if (sysTrayStream) {
  5580. sysTrayStream->setText(ui->streamButton->text());
  5581. sysTrayStream->setEnabled(true);
  5582. }
  5583. if (!startStreamMenu.isNull())
  5584. startStreamMenu->deleteLater();
  5585. startStreamMenu = new QMenu();
  5586. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  5587. SLOT(StopStreaming()));
  5588. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5589. SLOT(ForceStopStreaming()));
  5590. ui->streamButton->setMenu(startStreamMenu);
  5591. ui->statusbar->StreamDelayStarting(sec);
  5592. OnActivate();
  5593. }
  5594. void OBSBasic::StreamDelayStopping(int sec)
  5595. {
  5596. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5597. ui->streamButton->setEnabled(true);
  5598. ui->streamButton->setChecked(false);
  5599. if (sysTrayStream) {
  5600. sysTrayStream->setText(ui->streamButton->text());
  5601. sysTrayStream->setEnabled(true);
  5602. }
  5603. if (!startStreamMenu.isNull())
  5604. startStreamMenu->deleteLater();
  5605. startStreamMenu = new QMenu();
  5606. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  5607. SLOT(StartStreaming()));
  5608. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5609. SLOT(ForceStopStreaming()));
  5610. ui->streamButton->setMenu(startStreamMenu);
  5611. ui->statusbar->StreamDelayStopping(sec);
  5612. if (api)
  5613. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5614. }
  5615. void OBSBasic::StreamingStart()
  5616. {
  5617. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5618. ui->streamButton->setEnabled(true);
  5619. ui->streamButton->setChecked(true);
  5620. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  5621. if (sysTrayStream) {
  5622. sysTrayStream->setText(ui->streamButton->text());
  5623. sysTrayStream->setEnabled(true);
  5624. }
  5625. #if YOUTUBE_ENABLED
  5626. if (!autoStartBroadcast) {
  5627. // get a current stream key
  5628. obs_service_t *service_obj = GetService();
  5629. OBSDataAutoRelease settings =
  5630. obs_service_get_settings(service_obj);
  5631. std::string key = obs_data_get_string(settings, "stream_id");
  5632. if (!key.empty() && !youtubeStreamCheckThread) {
  5633. youtubeStreamCheckThread = CreateQThread(
  5634. [this, key] { YoutubeStreamCheck(key); });
  5635. youtubeStreamCheckThread->setObjectName(
  5636. "YouTubeStreamCheckThread");
  5637. youtubeStreamCheckThread->start();
  5638. }
  5639. }
  5640. #endif
  5641. if (api)
  5642. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  5643. OnActivate();
  5644. blog(LOG_INFO, STREAMING_START);
  5645. }
  5646. void OBSBasic::StreamStopping()
  5647. {
  5648. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  5649. if (sysTrayStream)
  5650. sysTrayStream->setText(ui->streamButton->text());
  5651. streamingStopping = true;
  5652. if (api)
  5653. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5654. }
  5655. void OBSBasic::StreamingStop(int code, QString last_error)
  5656. {
  5657. const char *errorDescription = "";
  5658. DStr errorMessage;
  5659. bool use_last_error = false;
  5660. bool encode_error = false;
  5661. switch (code) {
  5662. case OBS_OUTPUT_BAD_PATH:
  5663. errorDescription = Str("Output.ConnectFail.BadPath");
  5664. break;
  5665. case OBS_OUTPUT_CONNECT_FAILED:
  5666. use_last_error = true;
  5667. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  5668. break;
  5669. case OBS_OUTPUT_INVALID_STREAM:
  5670. errorDescription = Str("Output.ConnectFail.InvalidStream");
  5671. break;
  5672. case OBS_OUTPUT_ENCODE_ERROR:
  5673. encode_error = true;
  5674. break;
  5675. default:
  5676. case OBS_OUTPUT_ERROR:
  5677. use_last_error = true;
  5678. errorDescription = Str("Output.ConnectFail.Error");
  5679. break;
  5680. case OBS_OUTPUT_DISCONNECTED:
  5681. /* doesn't happen if output is set to reconnect. note that
  5682. * reconnects are handled in the output, not in the UI */
  5683. use_last_error = true;
  5684. errorDescription = Str("Output.ConnectFail.Disconnected");
  5685. }
  5686. if (use_last_error && !last_error.isEmpty())
  5687. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5688. QT_TO_UTF8(last_error));
  5689. else
  5690. dstr_copy(errorMessage, errorDescription);
  5691. ui->statusbar->StreamStopped();
  5692. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5693. ui->streamButton->setEnabled(true);
  5694. ui->streamButton->setChecked(false);
  5695. if (sysTrayStream) {
  5696. sysTrayStream->setText(ui->streamButton->text());
  5697. sysTrayStream->setEnabled(true);
  5698. }
  5699. streamingStopping = false;
  5700. if (api)
  5701. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  5702. OnDeactivate();
  5703. blog(LOG_INFO, STREAMING_STOP);
  5704. if (encode_error) {
  5705. QString msg =
  5706. last_error.isEmpty()
  5707. ? QTStr("Output.StreamEncodeError.Msg")
  5708. : QTStr("Output.StreamEncodeError.Msg.LastError")
  5709. .arg(last_error);
  5710. OBSMessageBox::information(
  5711. this, QTStr("Output.StreamEncodeError.Title"), msg);
  5712. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5713. OBSMessageBox::information(this,
  5714. QTStr("Output.ConnectFail.Title"),
  5715. QT_UTF8(errorMessage));
  5716. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5717. SysTrayNotify(QT_UTF8(errorDescription),
  5718. QSystemTrayIcon::Warning);
  5719. }
  5720. if (!startStreamMenu.isNull()) {
  5721. ui->streamButton->setMenu(nullptr);
  5722. startStreamMenu->deleteLater();
  5723. startStreamMenu = nullptr;
  5724. }
  5725. // Reset broadcast button state/text
  5726. if (!broadcastActive)
  5727. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  5728. }
  5729. void OBSBasic::AutoRemux(QString input, bool no_show)
  5730. {
  5731. bool autoRemux = config_get_bool(Config(), "Video", "AutoRemux");
  5732. if (!autoRemux)
  5733. return;
  5734. const char *recType = config_get_string(Config(), "AdvOut", "RecType");
  5735. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  5736. if (ffmpegOutput)
  5737. return;
  5738. if (input.isEmpty())
  5739. return;
  5740. QFileInfo fi(input);
  5741. QString suffix = fi.suffix();
  5742. /* do not remux if lossless */
  5743. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  5744. return;
  5745. }
  5746. QString path = fi.path();
  5747. QString output = input;
  5748. output.resize(output.size() - suffix.size());
  5749. output += "mp4";
  5750. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  5751. if (!no_show)
  5752. remux->show();
  5753. remux->AutoRemux(input, output);
  5754. }
  5755. void OBSBasic::StartRecording()
  5756. {
  5757. if (outputHandler->RecordingActive())
  5758. return;
  5759. if (disableOutputsRef)
  5760. return;
  5761. if (!OutputPathValid()) {
  5762. OutputPathInvalidMessage();
  5763. ui->recordButton->setChecked(false);
  5764. return;
  5765. }
  5766. if (LowDiskSpace()) {
  5767. DiskSpaceMessage();
  5768. ui->recordButton->setChecked(false);
  5769. return;
  5770. }
  5771. if (api)
  5772. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  5773. SaveProject();
  5774. if (!outputHandler->StartRecording())
  5775. ui->recordButton->setChecked(false);
  5776. }
  5777. void OBSBasic::RecordStopping()
  5778. {
  5779. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  5780. if (sysTrayRecord)
  5781. sysTrayRecord->setText(ui->recordButton->text());
  5782. recordingStopping = true;
  5783. if (api)
  5784. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  5785. }
  5786. void OBSBasic::StopRecording()
  5787. {
  5788. SaveProject();
  5789. if (outputHandler->RecordingActive())
  5790. outputHandler->StopRecording(recordingStopping);
  5791. OnDeactivate();
  5792. }
  5793. void OBSBasic::RecordingStart()
  5794. {
  5795. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  5796. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  5797. ui->recordButton->setChecked(true);
  5798. if (sysTrayRecord)
  5799. sysTrayRecord->setText(ui->recordButton->text());
  5800. recordingStopping = false;
  5801. if (api)
  5802. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  5803. if (!diskFullTimer->isActive())
  5804. diskFullTimer->start(1000);
  5805. OnActivate();
  5806. UpdatePause();
  5807. blog(LOG_INFO, RECORDING_START);
  5808. }
  5809. void OBSBasic::RecordingStop(int code, QString last_error)
  5810. {
  5811. ui->statusbar->RecordingStopped();
  5812. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  5813. ui->recordButton->setChecked(false);
  5814. if (sysTrayRecord)
  5815. sysTrayRecord->setText(ui->recordButton->text());
  5816. blog(LOG_INFO, RECORDING_STOP);
  5817. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5818. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5819. QTStr("Output.RecordFail.Unsupported"));
  5820. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  5821. QString msg =
  5822. last_error.isEmpty()
  5823. ? QTStr("Output.RecordError.EncodeErrorMsg")
  5824. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  5825. .arg(last_error);
  5826. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  5827. msg);
  5828. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5829. OBSMessageBox::warning(this,
  5830. QTStr("Output.RecordNoSpace.Title"),
  5831. QTStr("Output.RecordNoSpace.Msg"));
  5832. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5833. const char *errorDescription;
  5834. DStr errorMessage;
  5835. bool use_last_error = true;
  5836. errorDescription = Str("Output.RecordError.Msg");
  5837. if (use_last_error && !last_error.isEmpty())
  5838. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5839. QT_TO_UTF8(last_error));
  5840. else
  5841. dstr_copy(errorMessage, errorDescription);
  5842. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5843. QT_UTF8(errorMessage));
  5844. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5845. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5846. QSystemTrayIcon::Warning);
  5847. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5848. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5849. QSystemTrayIcon::Warning);
  5850. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5851. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5852. QSystemTrayIcon::Warning);
  5853. } else if (code == OBS_OUTPUT_SUCCESS) {
  5854. if (outputHandler) {
  5855. std::string path = outputHandler->lastRecordingPath;
  5856. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5857. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  5858. }
  5859. }
  5860. if (api)
  5861. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  5862. if (diskFullTimer->isActive())
  5863. diskFullTimer->stop();
  5864. AutoRemux(outputHandler->lastRecordingPath.c_str());
  5865. OnDeactivate();
  5866. UpdatePause(false);
  5867. }
  5868. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  5869. {
  5870. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5871. ShowStatusBarMessage(str.arg(lastRecordingPath));
  5872. AutoRemux(lastRecordingPath, true);
  5873. }
  5874. void OBSBasic::ShowReplayBufferPauseWarning()
  5875. {
  5876. auto msgBox = []() {
  5877. QMessageBox msgbox(App()->GetMainWindow());
  5878. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  5879. "PauseWarning.Title"));
  5880. msgbox.setText(QTStr("Output.ReplayBuffer."
  5881. "PauseWarning.Text"));
  5882. msgbox.setIcon(QMessageBox::Icon::Information);
  5883. msgbox.addButton(QMessageBox::Ok);
  5884. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5885. msgbox.setCheckBox(cb);
  5886. msgbox.exec();
  5887. if (cb->isChecked()) {
  5888. config_set_bool(App()->GlobalConfig(), "General",
  5889. "WarnedAboutReplayBufferPausing", true);
  5890. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5891. }
  5892. };
  5893. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5894. "WarnedAboutReplayBufferPausing");
  5895. if (!warned) {
  5896. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5897. Q_ARG(VoidFunc, msgBox));
  5898. }
  5899. }
  5900. void OBSBasic::StartReplayBuffer()
  5901. {
  5902. if (!outputHandler || !outputHandler->replayBuffer)
  5903. return;
  5904. if (outputHandler->ReplayBufferActive())
  5905. return;
  5906. if (disableOutputsRef)
  5907. return;
  5908. if (!UIValidation::NoSourcesConfirmation(this)) {
  5909. replayBufferButton->setChecked(false);
  5910. return;
  5911. }
  5912. if (!OutputPathValid()) {
  5913. OutputPathInvalidMessage();
  5914. replayBufferButton->setChecked(false);
  5915. return;
  5916. }
  5917. if (LowDiskSpace()) {
  5918. DiskSpaceMessage();
  5919. replayBufferButton->setChecked(false);
  5920. return;
  5921. }
  5922. if (api)
  5923. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  5924. SaveProject();
  5925. if (!outputHandler->StartReplayBuffer()) {
  5926. replayBufferButton->setChecked(false);
  5927. } else if (os_atomic_load_bool(&recording_paused)) {
  5928. ShowReplayBufferPauseWarning();
  5929. }
  5930. }
  5931. void OBSBasic::ReplayBufferStopping()
  5932. {
  5933. if (!outputHandler || !outputHandler->replayBuffer)
  5934. return;
  5935. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  5936. if (sysTrayReplayBuffer)
  5937. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5938. replayBufferStopping = true;
  5939. if (api)
  5940. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  5941. }
  5942. void OBSBasic::StopReplayBuffer()
  5943. {
  5944. if (!outputHandler || !outputHandler->replayBuffer)
  5945. return;
  5946. SaveProject();
  5947. if (outputHandler->ReplayBufferActive())
  5948. outputHandler->StopReplayBuffer(replayBufferStopping);
  5949. OnDeactivate();
  5950. }
  5951. void OBSBasic::ReplayBufferStart()
  5952. {
  5953. if (!outputHandler || !outputHandler->replayBuffer)
  5954. return;
  5955. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  5956. replayBufferButton->setChecked(true);
  5957. if (sysTrayReplayBuffer)
  5958. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5959. replayBufferStopping = false;
  5960. if (api)
  5961. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  5962. OnActivate();
  5963. UpdateReplayBuffer();
  5964. blog(LOG_INFO, REPLAY_BUFFER_START);
  5965. }
  5966. void OBSBasic::ReplayBufferSave()
  5967. {
  5968. if (!outputHandler || !outputHandler->replayBuffer)
  5969. return;
  5970. if (!outputHandler->ReplayBufferActive())
  5971. return;
  5972. calldata_t cd = {0};
  5973. proc_handler_t *ph =
  5974. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5975. proc_handler_call(ph, "save", &cd);
  5976. calldata_free(&cd);
  5977. }
  5978. void OBSBasic::ReplayBufferSaved()
  5979. {
  5980. if (!outputHandler || !outputHandler->replayBuffer)
  5981. return;
  5982. if (!outputHandler->ReplayBufferActive())
  5983. return;
  5984. calldata_t cd = {0};
  5985. proc_handler_t *ph =
  5986. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5987. proc_handler_call(ph, "get_last_replay", &cd);
  5988. QString path = QT_UTF8(calldata_string(&cd, "path"));
  5989. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(path);
  5990. ShowStatusBarMessage(msg);
  5991. calldata_free(&cd);
  5992. if (api)
  5993. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  5994. AutoRemux(path);
  5995. }
  5996. void OBSBasic::ReplayBufferStop(int code)
  5997. {
  5998. if (!outputHandler || !outputHandler->replayBuffer)
  5999. return;
  6000. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  6001. replayBufferButton->setChecked(false);
  6002. if (sysTrayReplayBuffer)
  6003. sysTrayReplayBuffer->setText(replayBufferButton->text());
  6004. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6005. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6006. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6007. QTStr("Output.RecordFail.Unsupported"));
  6008. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6009. OBSMessageBox::warning(this,
  6010. QTStr("Output.RecordNoSpace.Title"),
  6011. QTStr("Output.RecordNoSpace.Msg"));
  6012. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6013. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6014. QTStr("Output.RecordError.Msg"));
  6015. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6016. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6017. QSystemTrayIcon::Warning);
  6018. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6019. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6020. QSystemTrayIcon::Warning);
  6021. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6022. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6023. QSystemTrayIcon::Warning);
  6024. }
  6025. if (api)
  6026. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6027. OnDeactivate();
  6028. UpdateReplayBuffer(false);
  6029. }
  6030. void OBSBasic::StartVirtualCam()
  6031. {
  6032. if (!outputHandler || !outputHandler->virtualCam)
  6033. return;
  6034. if (outputHandler->VirtualCamActive())
  6035. return;
  6036. if (disableOutputsRef)
  6037. return;
  6038. SaveProject();
  6039. if (!outputHandler->StartVirtualCam()) {
  6040. vcamButton->setChecked(false);
  6041. }
  6042. }
  6043. void OBSBasic::StopVirtualCam()
  6044. {
  6045. if (!outputHandler || !outputHandler->virtualCam)
  6046. return;
  6047. SaveProject();
  6048. if (outputHandler->VirtualCamActive())
  6049. outputHandler->StopVirtualCam();
  6050. OnDeactivate();
  6051. }
  6052. void OBSBasic::OnVirtualCamStart()
  6053. {
  6054. if (!outputHandler || !outputHandler->virtualCam)
  6055. return;
  6056. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  6057. if (sysTrayVirtualCam)
  6058. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6059. vcamButton->setChecked(true);
  6060. if (api)
  6061. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6062. OnActivate();
  6063. blog(LOG_INFO, VIRTUAL_CAM_START);
  6064. }
  6065. void OBSBasic::OnVirtualCamStop(int)
  6066. {
  6067. if (!outputHandler || !outputHandler->virtualCam)
  6068. return;
  6069. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  6070. if (sysTrayVirtualCam)
  6071. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6072. vcamButton->setChecked(false);
  6073. if (api)
  6074. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6075. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6076. OnDeactivate();
  6077. }
  6078. void OBSBasic::on_streamButton_clicked()
  6079. {
  6080. if (outputHandler->StreamingActive()) {
  6081. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6082. "WarnBeforeStoppingStream");
  6083. #if YOUTUBE_ENABLED
  6084. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6085. autoStopBroadcast) {
  6086. QMessageBox::StandardButton button = OBSMessageBox::question(
  6087. this, QTStr("ConfirmStop.Title"),
  6088. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6089. QMessageBox::Yes | QMessageBox::No,
  6090. QMessageBox::No);
  6091. if (button == QMessageBox::No) {
  6092. ui->streamButton->setChecked(true);
  6093. return;
  6094. }
  6095. confirm = false;
  6096. }
  6097. #endif
  6098. if (confirm && isVisible()) {
  6099. QMessageBox::StandardButton button =
  6100. OBSMessageBox::question(
  6101. this, QTStr("ConfirmStop.Title"),
  6102. QTStr("ConfirmStop.Text"),
  6103. QMessageBox::Yes | QMessageBox::No,
  6104. QMessageBox::No);
  6105. if (button == QMessageBox::No) {
  6106. ui->streamButton->setChecked(true);
  6107. return;
  6108. }
  6109. }
  6110. StopStreaming();
  6111. } else {
  6112. if (!UIValidation::NoSourcesConfirmation(this)) {
  6113. ui->streamButton->setChecked(false);
  6114. return;
  6115. }
  6116. Auth *auth = GetAuth();
  6117. auto action =
  6118. (auth && auth->external())
  6119. ? StreamSettingsAction::ContinueStream
  6120. : UIValidation::StreamSettingsConfirmation(
  6121. this, service);
  6122. switch (action) {
  6123. case StreamSettingsAction::ContinueStream:
  6124. break;
  6125. case StreamSettingsAction::OpenSettings:
  6126. on_action_Settings_triggered();
  6127. ui->streamButton->setChecked(false);
  6128. return;
  6129. case StreamSettingsAction::Cancel:
  6130. ui->streamButton->setChecked(false);
  6131. return;
  6132. }
  6133. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6134. "WarnBeforeStartingStream");
  6135. bool bwtest = false;
  6136. if (this->auth) {
  6137. OBSDataAutoRelease settings =
  6138. obs_service_get_settings(service);
  6139. bwtest = obs_data_get_bool(settings, "bwtest");
  6140. // Disable confirmation if this is going to open broadcast setup
  6141. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6142. !broadcastActive)
  6143. confirm = false;
  6144. }
  6145. if (bwtest && isVisible()) {
  6146. QMessageBox::StandardButton button =
  6147. OBSMessageBox::question(
  6148. this, QTStr("ConfirmBWTest.Title"),
  6149. QTStr("ConfirmBWTest.Text"));
  6150. if (button == QMessageBox::No) {
  6151. ui->streamButton->setChecked(false);
  6152. return;
  6153. }
  6154. } else if (confirm && isVisible()) {
  6155. QMessageBox::StandardButton button =
  6156. OBSMessageBox::question(
  6157. this, QTStr("ConfirmStart.Title"),
  6158. QTStr("ConfirmStart.Text"),
  6159. QMessageBox::Yes | QMessageBox::No,
  6160. QMessageBox::No);
  6161. if (button == QMessageBox::No) {
  6162. ui->streamButton->setChecked(false);
  6163. return;
  6164. }
  6165. }
  6166. StartStreaming();
  6167. }
  6168. }
  6169. void OBSBasic::on_recordButton_clicked()
  6170. {
  6171. if (outputHandler->RecordingActive()) {
  6172. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6173. "WarnBeforeStoppingRecord");
  6174. if (confirm && isVisible()) {
  6175. QMessageBox::StandardButton button =
  6176. OBSMessageBox::question(
  6177. this, QTStr("ConfirmStopRecord.Title"),
  6178. QTStr("ConfirmStopRecord.Text"),
  6179. QMessageBox::Yes | QMessageBox::No,
  6180. QMessageBox::No);
  6181. if (button == QMessageBox::No) {
  6182. ui->recordButton->setChecked(true);
  6183. return;
  6184. }
  6185. }
  6186. StopRecording();
  6187. } else {
  6188. if (!UIValidation::NoSourcesConfirmation(this)) {
  6189. ui->recordButton->setChecked(false);
  6190. return;
  6191. }
  6192. StartRecording();
  6193. }
  6194. }
  6195. void OBSBasic::VCamButtonClicked()
  6196. {
  6197. if (outputHandler->VirtualCamActive()) {
  6198. StopVirtualCam();
  6199. } else {
  6200. if (!UIValidation::NoSourcesConfirmation(this)) {
  6201. vcamButton->setChecked(false);
  6202. return;
  6203. }
  6204. StartVirtualCam();
  6205. }
  6206. }
  6207. void OBSBasic::on_settingsButton_clicked()
  6208. {
  6209. on_action_Settings_triggered();
  6210. }
  6211. void OBSBasic::on_actionHelpPortal_triggered()
  6212. {
  6213. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6214. QDesktopServices::openUrl(url);
  6215. }
  6216. void OBSBasic::on_actionWebsite_triggered()
  6217. {
  6218. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6219. QDesktopServices::openUrl(url);
  6220. }
  6221. void OBSBasic::on_actionDiscord_triggered()
  6222. {
  6223. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6224. QDesktopServices::openUrl(url);
  6225. }
  6226. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6227. {
  6228. char path[512];
  6229. int ret = GetConfigPath(path, 512, "obs-studio");
  6230. if (ret <= 0)
  6231. return;
  6232. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6233. }
  6234. void OBSBasic::on_actionShowProfileFolder_triggered()
  6235. {
  6236. char path[512];
  6237. int ret = GetProfilePath(path, 512, "");
  6238. if (ret <= 0)
  6239. return;
  6240. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6241. }
  6242. int OBSBasic::GetTopSelectedSourceItem()
  6243. {
  6244. QModelIndexList selectedItems =
  6245. ui->sources->selectionModel()->selectedIndexes();
  6246. return selectedItems.count() ? selectedItems[0].row() : -1;
  6247. }
  6248. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6249. {
  6250. return ui->sources->selectionModel()->selectedIndexes();
  6251. }
  6252. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  6253. {
  6254. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6255. UNUSED_PARAMETER(pos);
  6256. }
  6257. void OBSBasic::ProgramViewContextMenuRequested(const QPoint &)
  6258. {
  6259. QMenu popup(this);
  6260. QPointer<QMenu> studioProgramProjector;
  6261. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6262. AddProjectorMenuMonitors(studioProgramProjector, this,
  6263. SLOT(OpenStudioProgramProjector()));
  6264. popup.addMenu(studioProgramProjector);
  6265. QAction *studioProgramWindow =
  6266. popup.addAction(QTStr("StudioProgramWindow"), this,
  6267. SLOT(OpenStudioProgramWindow()));
  6268. popup.addAction(studioProgramWindow);
  6269. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6270. SLOT(ScreenshotProgram()));
  6271. popup.exec(QCursor::pos());
  6272. }
  6273. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  6274. {
  6275. QMenu popup(this);
  6276. delete previewProjectorMain;
  6277. QAction *action =
  6278. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6279. this, SLOT(TogglePreview()));
  6280. action->setCheckable(true);
  6281. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6282. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6283. AddProjectorMenuMonitors(previewProjectorMain, this,
  6284. SLOT(OpenPreviewProjector()));
  6285. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6286. SLOT(OpenPreviewWindow()));
  6287. popup.addMenu(previewProjectorMain);
  6288. popup.addAction(previewWindow);
  6289. popup.exec(QCursor::pos());
  6290. UNUSED_PARAMETER(pos);
  6291. }
  6292. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6293. {
  6294. #ifndef _WIN32
  6295. /* Make sure all dialogs are safely and successfully closed before
  6296. * switching the always on top mode due to the fact that windows all
  6297. * have to be recreated, so queue the actual toggle to happen after
  6298. * all events related to closing the dialogs have finished */
  6299. CloseDialogs();
  6300. #endif
  6301. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6302. Qt::QueuedConnection);
  6303. }
  6304. void OBSBasic::ToggleAlwaysOnTop()
  6305. {
  6306. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6307. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6308. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6309. show();
  6310. }
  6311. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6312. {
  6313. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6314. if (strcmp(val, "10") == 0) {
  6315. num = 10;
  6316. den = 1;
  6317. } else if (strcmp(val, "20") == 0) {
  6318. num = 20;
  6319. den = 1;
  6320. } else if (strcmp(val, "24 NTSC") == 0) {
  6321. num = 24000;
  6322. den = 1001;
  6323. } else if (strcmp(val, "25 PAL") == 0) {
  6324. num = 25;
  6325. den = 1;
  6326. } else if (strcmp(val, "29.97") == 0) {
  6327. num = 30000;
  6328. den = 1001;
  6329. } else if (strcmp(val, "48") == 0) {
  6330. num = 48;
  6331. den = 1;
  6332. } else if (strcmp(val, "50 PAL") == 0) {
  6333. num = 50;
  6334. den = 1;
  6335. } else if (strcmp(val, "59.94") == 0) {
  6336. num = 60000;
  6337. den = 1001;
  6338. } else if (strcmp(val, "60") == 0) {
  6339. num = 60;
  6340. den = 1;
  6341. } else {
  6342. num = 30;
  6343. den = 1;
  6344. }
  6345. }
  6346. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6347. {
  6348. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6349. den = 1;
  6350. }
  6351. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6352. {
  6353. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6354. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6355. }
  6356. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6357. {
  6358. num = 1000000000;
  6359. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6360. }
  6361. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6362. {
  6363. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6364. if (type == 1) //"Integer"
  6365. GetFPSInteger(num, den);
  6366. else if (type == 2) //"Fraction"
  6367. GetFPSFraction(num, den);
  6368. else if (false) //"Nanoseconds", currently not implemented
  6369. GetFPSNanoseconds(num, den);
  6370. else
  6371. GetFPSCommon(num, den);
  6372. }
  6373. config_t *OBSBasic::Config() const
  6374. {
  6375. return basicConfig;
  6376. }
  6377. void OBSBasic::UpdateEditMenu()
  6378. {
  6379. QModelIndexList items = GetAllSelectedSourceItems();
  6380. int count = items.count();
  6381. size_t filter_count = 0;
  6382. if (count == 1) {
  6383. OBSSceneItem sceneItem =
  6384. ui->sources->Get(GetTopSelectedSourceItem());
  6385. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6386. filter_count = obs_source_filter_count(source);
  6387. }
  6388. bool allowPastingDuplicate = !!clipboard.size();
  6389. for (size_t i = clipboard.size(); i > 0; i--) {
  6390. const size_t idx = i - 1;
  6391. OBSWeakSource &weak = clipboard[idx].weak_source;
  6392. if (obs_weak_source_expired(weak)) {
  6393. clipboard.erase(clipboard.begin() + idx);
  6394. continue;
  6395. }
  6396. OBSSourceAutoRelease strong =
  6397. obs_weak_source_get_source(weak.Get());
  6398. if (allowPastingDuplicate &&
  6399. obs_source_get_output_flags(strong) &
  6400. OBS_SOURCE_DO_NOT_DUPLICATE)
  6401. allowPastingDuplicate = false;
  6402. }
  6403. ui->actionCopySource->setEnabled(count > 0);
  6404. ui->actionEditTransform->setEnabled(count == 1);
  6405. ui->actionCopyTransform->setEnabled(count == 1);
  6406. ui->actionPasteTransform->setEnabled(hasCopiedTransform && count > 0);
  6407. ui->actionCopyFilters->setEnabled(filter_count > 0);
  6408. ui->actionPasteFilters->setEnabled(
  6409. !obs_weak_source_expired(copyFiltersSource) && count > 0);
  6410. ui->actionPasteRef->setEnabled(!!clipboard.size());
  6411. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6412. ui->actionMoveUp->setEnabled(count > 0);
  6413. ui->actionMoveDown->setEnabled(count > 0);
  6414. ui->actionMoveToTop->setEnabled(count > 0);
  6415. ui->actionMoveToBottom->setEnabled(count > 0);
  6416. bool canTransform = false;
  6417. for (int i = 0; i < count; i++) {
  6418. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  6419. if (!obs_sceneitem_locked(item))
  6420. canTransform = true;
  6421. }
  6422. ui->actionResetTransform->setEnabled(canTransform);
  6423. ui->actionRotate90CW->setEnabled(canTransform);
  6424. ui->actionRotate90CCW->setEnabled(canTransform);
  6425. ui->actionRotate180->setEnabled(canTransform);
  6426. ui->actionFlipHorizontal->setEnabled(canTransform);
  6427. ui->actionFlipVertical->setEnabled(canTransform);
  6428. ui->actionFitToScreen->setEnabled(canTransform);
  6429. ui->actionStretchToScreen->setEnabled(canTransform);
  6430. ui->actionCenterToScreen->setEnabled(canTransform);
  6431. ui->actionVerticalCenter->setEnabled(canTransform);
  6432. ui->actionHorizontalCenter->setEnabled(canTransform);
  6433. }
  6434. void OBSBasic::on_actionEditTransform_triggered()
  6435. {
  6436. if (transformWindow)
  6437. transformWindow->close();
  6438. if (!GetCurrentSceneItem())
  6439. return;
  6440. transformWindow = new OBSBasicTransform(this);
  6441. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  6442. &OBSBasicTransform::OnSceneChanged);
  6443. transformWindow->show();
  6444. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  6445. }
  6446. void OBSBasic::on_actionCopyTransform_triggered()
  6447. {
  6448. OBSSceneItem item = GetCurrentSceneItem();
  6449. obs_sceneitem_get_info(item, &copiedTransformInfo);
  6450. obs_sceneitem_get_crop(item, &copiedCropInfo);
  6451. ui->actionPasteTransform->setEnabled(true);
  6452. hasCopiedTransform = true;
  6453. }
  6454. void undo_redo(const std::string &data)
  6455. {
  6456. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  6457. OBSSourceAutoRelease source =
  6458. obs_get_source_by_name(obs_data_get_string(dat, "scene_name"));
  6459. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  6460. ->SetCurrentScene(source.Get(), true);
  6461. obs_scene_load_transform_states(data.c_str());
  6462. }
  6463. void OBSBasic::on_actionPasteTransform_triggered()
  6464. {
  6465. OBSDataAutoRelease wrapper =
  6466. obs_scene_save_transform_states(GetCurrentScene(), false);
  6467. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  6468. if (!obs_sceneitem_selected(item))
  6469. return true;
  6470. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  6471. obs_sceneitem_defer_update_begin(item);
  6472. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  6473. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  6474. obs_sceneitem_defer_update_end(item);
  6475. return true;
  6476. };
  6477. obs_scene_enum_items(GetCurrentScene(), func, this);
  6478. OBSDataAutoRelease rwrapper =
  6479. obs_scene_save_transform_states(GetCurrentScene(), false);
  6480. std::string undo_data(obs_data_get_json(wrapper));
  6481. std::string redo_data(obs_data_get_json(rwrapper));
  6482. undo_s.add_action(
  6483. QTStr("Undo.Transform.Paste")
  6484. .arg(obs_source_get_name(GetCurrentSceneSource())),
  6485. undo_redo, undo_redo, undo_data, redo_data);
  6486. }
  6487. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  6488. {
  6489. if (obs_sceneitem_is_group(item))
  6490. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  6491. if (!obs_sceneitem_selected(item))
  6492. return true;
  6493. if (obs_sceneitem_locked(item))
  6494. return true;
  6495. obs_sceneitem_defer_update_begin(item);
  6496. obs_transform_info info;
  6497. vec2_set(&info.pos, 0.0f, 0.0f);
  6498. vec2_set(&info.scale, 1.0f, 1.0f);
  6499. info.rot = 0.0f;
  6500. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  6501. info.bounds_type = OBS_BOUNDS_NONE;
  6502. info.bounds_alignment = OBS_ALIGN_CENTER;
  6503. vec2_set(&info.bounds, 0.0f, 0.0f);
  6504. obs_sceneitem_set_info(item, &info);
  6505. obs_sceneitem_crop crop = {};
  6506. obs_sceneitem_set_crop(item, &crop);
  6507. obs_sceneitem_defer_update_end(item);
  6508. UNUSED_PARAMETER(scene);
  6509. UNUSED_PARAMETER(param);
  6510. return true;
  6511. }
  6512. void OBSBasic::on_actionResetTransform_triggered()
  6513. {
  6514. obs_scene_t *scene = GetCurrentScene();
  6515. OBSDataAutoRelease wrapper =
  6516. obs_scene_save_transform_states(scene, false);
  6517. obs_scene_enum_items(scene, reset_tr, nullptr);
  6518. OBSDataAutoRelease rwrapper =
  6519. obs_scene_save_transform_states(scene, false);
  6520. std::string undo_data(obs_data_get_json(wrapper));
  6521. std::string redo_data(obs_data_get_json(rwrapper));
  6522. undo_s.add_action(
  6523. QTStr("Undo.Transform.Reset")
  6524. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  6525. undo_redo, undo_redo, undo_data, redo_data);
  6526. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  6527. }
  6528. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  6529. {
  6530. matrix4 boxTransform;
  6531. obs_sceneitem_get_box_transform(item, &boxTransform);
  6532. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  6533. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  6534. auto GetMinPos = [&](float x, float y) {
  6535. vec3 pos;
  6536. vec3_set(&pos, x, y, 0.0f);
  6537. vec3_transform(&pos, &pos, &boxTransform);
  6538. vec3_min(&tl, &tl, &pos);
  6539. vec3_max(&br, &br, &pos);
  6540. };
  6541. GetMinPos(0.0f, 0.0f);
  6542. GetMinPos(1.0f, 0.0f);
  6543. GetMinPos(0.0f, 1.0f);
  6544. GetMinPos(1.0f, 1.0f);
  6545. }
  6546. static vec3 GetItemTL(obs_sceneitem_t *item)
  6547. {
  6548. vec3 tl, br;
  6549. GetItemBox(item, tl, br);
  6550. return tl;
  6551. }
  6552. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  6553. {
  6554. vec3 newTL;
  6555. vec2 pos;
  6556. obs_sceneitem_get_pos(item, &pos);
  6557. newTL = GetItemTL(item);
  6558. pos.x += tl.x - newTL.x;
  6559. pos.y += tl.y - newTL.y;
  6560. obs_sceneitem_set_pos(item, &pos);
  6561. }
  6562. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  6563. void *param)
  6564. {
  6565. if (obs_sceneitem_is_group(item))
  6566. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  6567. param);
  6568. if (!obs_sceneitem_selected(item))
  6569. return true;
  6570. if (obs_sceneitem_locked(item))
  6571. return true;
  6572. float rot = *reinterpret_cast<float *>(param);
  6573. vec3 tl = GetItemTL(item);
  6574. rot += obs_sceneitem_get_rot(item);
  6575. if (rot >= 360.0f)
  6576. rot -= 360.0f;
  6577. else if (rot <= -360.0f)
  6578. rot += 360.0f;
  6579. obs_sceneitem_set_rot(item, rot);
  6580. obs_sceneitem_force_update_transform(item);
  6581. SetItemTL(item, tl);
  6582. UNUSED_PARAMETER(scene);
  6583. return true;
  6584. };
  6585. void OBSBasic::on_actionRotate90CW_triggered()
  6586. {
  6587. float f90CW = 90.0f;
  6588. OBSDataAutoRelease wrapper =
  6589. obs_scene_save_transform_states(GetCurrentScene(), false);
  6590. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  6591. OBSDataAutoRelease rwrapper =
  6592. obs_scene_save_transform_states(GetCurrentScene(), false);
  6593. std::string undo_data(obs_data_get_json(wrapper));
  6594. std::string redo_data(obs_data_get_json(rwrapper));
  6595. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6596. .arg(obs_source_get_name(obs_scene_get_source(
  6597. GetCurrentScene()))),
  6598. undo_redo, undo_redo, undo_data, redo_data);
  6599. }
  6600. void OBSBasic::on_actionRotate90CCW_triggered()
  6601. {
  6602. float f90CCW = -90.0f;
  6603. OBSDataAutoRelease wrapper =
  6604. obs_scene_save_transform_states(GetCurrentScene(), false);
  6605. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  6606. OBSDataAutoRelease rwrapper =
  6607. obs_scene_save_transform_states(GetCurrentScene(), false);
  6608. std::string undo_data(obs_data_get_json(wrapper));
  6609. std::string redo_data(obs_data_get_json(rwrapper));
  6610. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6611. .arg(obs_source_get_name(obs_scene_get_source(
  6612. GetCurrentScene()))),
  6613. undo_redo, undo_redo, undo_data, redo_data);
  6614. }
  6615. void OBSBasic::on_actionRotate180_triggered()
  6616. {
  6617. float f180 = 180.0f;
  6618. OBSDataAutoRelease wrapper =
  6619. obs_scene_save_transform_states(GetCurrentScene(), false);
  6620. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  6621. OBSDataAutoRelease rwrapper =
  6622. obs_scene_save_transform_states(GetCurrentScene(), false);
  6623. std::string undo_data(obs_data_get_json(wrapper));
  6624. std::string redo_data(obs_data_get_json(rwrapper));
  6625. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6626. .arg(obs_source_get_name(obs_scene_get_source(
  6627. GetCurrentScene()))),
  6628. undo_redo, undo_redo, undo_data, redo_data);
  6629. }
  6630. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  6631. void *param)
  6632. {
  6633. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  6634. if (obs_sceneitem_is_group(item))
  6635. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  6636. param);
  6637. if (!obs_sceneitem_selected(item))
  6638. return true;
  6639. if (obs_sceneitem_locked(item))
  6640. return true;
  6641. vec3 tl = GetItemTL(item);
  6642. vec2 scale;
  6643. obs_sceneitem_get_scale(item, &scale);
  6644. vec2_mul(&scale, &scale, &mul);
  6645. obs_sceneitem_set_scale(item, &scale);
  6646. obs_sceneitem_force_update_transform(item);
  6647. SetItemTL(item, tl);
  6648. UNUSED_PARAMETER(scene);
  6649. return true;
  6650. }
  6651. void OBSBasic::on_actionFlipHorizontal_triggered()
  6652. {
  6653. vec2 scale;
  6654. vec2_set(&scale, -1.0f, 1.0f);
  6655. OBSDataAutoRelease wrapper =
  6656. obs_scene_save_transform_states(GetCurrentScene(), false);
  6657. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6658. &scale);
  6659. OBSDataAutoRelease rwrapper =
  6660. obs_scene_save_transform_states(GetCurrentScene(), false);
  6661. std::string undo_data(obs_data_get_json(wrapper));
  6662. std::string redo_data(obs_data_get_json(rwrapper));
  6663. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  6664. .arg(obs_source_get_name(obs_scene_get_source(
  6665. GetCurrentScene()))),
  6666. undo_redo, undo_redo, undo_data, redo_data);
  6667. }
  6668. void OBSBasic::on_actionFlipVertical_triggered()
  6669. {
  6670. vec2 scale;
  6671. vec2_set(&scale, 1.0f, -1.0f);
  6672. OBSDataAutoRelease wrapper =
  6673. obs_scene_save_transform_states(GetCurrentScene(), false);
  6674. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6675. &scale);
  6676. OBSDataAutoRelease rwrapper =
  6677. obs_scene_save_transform_states(GetCurrentScene(), false);
  6678. std::string undo_data(obs_data_get_json(wrapper));
  6679. std::string redo_data(obs_data_get_json(rwrapper));
  6680. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  6681. .arg(obs_source_get_name(obs_scene_get_source(
  6682. GetCurrentScene()))),
  6683. undo_redo, undo_redo, undo_data, redo_data);
  6684. }
  6685. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  6686. void *param)
  6687. {
  6688. obs_bounds_type boundsType =
  6689. *reinterpret_cast<obs_bounds_type *>(param);
  6690. if (obs_sceneitem_is_group(item))
  6691. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  6692. param);
  6693. if (!obs_sceneitem_selected(item))
  6694. return true;
  6695. if (obs_sceneitem_locked(item))
  6696. return true;
  6697. obs_video_info ovi;
  6698. obs_get_video_info(&ovi);
  6699. obs_transform_info itemInfo;
  6700. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  6701. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  6702. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  6703. itemInfo.rot = 0.0f;
  6704. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  6705. float(ovi.base_height));
  6706. itemInfo.bounds_type = boundsType;
  6707. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  6708. obs_sceneitem_set_info(item, &itemInfo);
  6709. UNUSED_PARAMETER(scene);
  6710. return true;
  6711. }
  6712. void OBSBasic::on_actionFitToScreen_triggered()
  6713. {
  6714. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  6715. OBSDataAutoRelease wrapper =
  6716. obs_scene_save_transform_states(GetCurrentScene(), false);
  6717. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6718. &boundsType);
  6719. OBSDataAutoRelease rwrapper =
  6720. obs_scene_save_transform_states(GetCurrentScene(), false);
  6721. std::string undo_data(obs_data_get_json(wrapper));
  6722. std::string redo_data(obs_data_get_json(rwrapper));
  6723. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  6724. .arg(obs_source_get_name(obs_scene_get_source(
  6725. GetCurrentScene()))),
  6726. undo_redo, undo_redo, undo_data, redo_data);
  6727. }
  6728. void OBSBasic::on_actionStretchToScreen_triggered()
  6729. {
  6730. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  6731. OBSDataAutoRelease wrapper =
  6732. obs_scene_save_transform_states(GetCurrentScene(), false);
  6733. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6734. &boundsType);
  6735. OBSDataAutoRelease rwrapper =
  6736. obs_scene_save_transform_states(GetCurrentScene(), false);
  6737. std::string undo_data(obs_data_get_json(wrapper));
  6738. std::string redo_data(obs_data_get_json(rwrapper));
  6739. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  6740. .arg(obs_source_get_name(obs_scene_get_source(
  6741. GetCurrentScene()))),
  6742. undo_redo, undo_redo, undo_data, redo_data);
  6743. }
  6744. enum class CenterType {
  6745. Scene,
  6746. Vertical,
  6747. Horizontal,
  6748. };
  6749. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6750. {
  6751. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  6752. vec3 tl, br, itemCenter, screenCenter, offset;
  6753. obs_video_info ovi;
  6754. obs_transform_info oti;
  6755. if (obs_sceneitem_is_group(item))
  6756. obs_sceneitem_group_enum_items(item, center_to_scene,
  6757. &centerType);
  6758. if (!obs_sceneitem_selected(item))
  6759. return true;
  6760. if (obs_sceneitem_locked(item))
  6761. return true;
  6762. obs_get_video_info(&ovi);
  6763. obs_sceneitem_get_info(item, &oti);
  6764. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  6765. 0.0f);
  6766. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  6767. GetItemBox(item, tl, br);
  6768. vec3_sub(&itemCenter, &br, &tl);
  6769. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  6770. vec3_add(&itemCenter, &itemCenter, &tl);
  6771. vec3_sub(&offset, &screenCenter, &itemCenter);
  6772. vec3_add(&tl, &tl, &offset);
  6773. vec3 itemTL = GetItemTL(item);
  6774. if (centerType == CenterType::Vertical)
  6775. tl.x = itemTL.x;
  6776. else if (centerType == CenterType::Horizontal)
  6777. tl.y = itemTL.y;
  6778. SetItemTL(item, tl);
  6779. return true;
  6780. };
  6781. void OBSBasic::on_actionCenterToScreen_triggered()
  6782. {
  6783. CenterType centerType = CenterType::Scene;
  6784. OBSDataAutoRelease wrapper =
  6785. obs_scene_save_transform_states(GetCurrentScene(), false);
  6786. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6787. OBSDataAutoRelease rwrapper =
  6788. obs_scene_save_transform_states(GetCurrentScene(), false);
  6789. std::string undo_data(obs_data_get_json(wrapper));
  6790. std::string redo_data(obs_data_get_json(rwrapper));
  6791. undo_s.add_action(QTStr("Undo.Transform.Center")
  6792. .arg(obs_source_get_name(obs_scene_get_source(
  6793. GetCurrentScene()))),
  6794. undo_redo, undo_redo, undo_data, redo_data);
  6795. }
  6796. void OBSBasic::on_actionVerticalCenter_triggered()
  6797. {
  6798. CenterType centerType = CenterType::Vertical;
  6799. OBSDataAutoRelease wrapper =
  6800. obs_scene_save_transform_states(GetCurrentScene(), false);
  6801. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6802. OBSDataAutoRelease rwrapper =
  6803. obs_scene_save_transform_states(GetCurrentScene(), false);
  6804. std::string undo_data(obs_data_get_json(wrapper));
  6805. std::string redo_data(obs_data_get_json(rwrapper));
  6806. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  6807. .arg(obs_source_get_name(obs_scene_get_source(
  6808. GetCurrentScene()))),
  6809. undo_redo, undo_redo, undo_data, redo_data);
  6810. }
  6811. void OBSBasic::on_actionHorizontalCenter_triggered()
  6812. {
  6813. CenterType centerType = CenterType::Horizontal;
  6814. OBSDataAutoRelease wrapper =
  6815. obs_scene_save_transform_states(GetCurrentScene(), false);
  6816. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6817. OBSDataAutoRelease rwrapper =
  6818. obs_scene_save_transform_states(GetCurrentScene(), false);
  6819. std::string undo_data(obs_data_get_json(wrapper));
  6820. std::string redo_data(obs_data_get_json(rwrapper));
  6821. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  6822. .arg(obs_source_get_name(obs_scene_get_source(
  6823. GetCurrentScene()))),
  6824. undo_redo, undo_redo, undo_data, redo_data);
  6825. }
  6826. void OBSBasic::EnablePreviewDisplay(bool enable)
  6827. {
  6828. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  6829. ui->preview->setVisible(enable);
  6830. ui->previewDisabledWidget->setVisible(!enable);
  6831. }
  6832. void OBSBasic::TogglePreview()
  6833. {
  6834. previewEnabled = !previewEnabled;
  6835. EnablePreviewDisplay(previewEnabled);
  6836. }
  6837. void OBSBasic::EnablePreview()
  6838. {
  6839. if (previewProgramMode)
  6840. return;
  6841. previewEnabled = true;
  6842. EnablePreviewDisplay(true);
  6843. }
  6844. void OBSBasic::DisablePreview()
  6845. {
  6846. if (previewProgramMode)
  6847. return;
  6848. previewEnabled = false;
  6849. EnablePreviewDisplay(false);
  6850. }
  6851. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6852. {
  6853. if (obs_sceneitem_locked(item))
  6854. return true;
  6855. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  6856. struct vec2 pos;
  6857. if (!obs_sceneitem_selected(item)) {
  6858. if (obs_sceneitem_is_group(item)) {
  6859. struct vec3 offset3;
  6860. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  6861. struct matrix4 matrix;
  6862. obs_sceneitem_get_draw_transform(item, &matrix);
  6863. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  6864. matrix4_inv(&matrix, &matrix);
  6865. vec3_transform(&offset3, &offset3, &matrix);
  6866. struct vec2 new_offset;
  6867. vec2_set(&new_offset, offset3.x, offset3.y);
  6868. obs_sceneitem_group_enum_items(item, nudge_callback,
  6869. &new_offset);
  6870. }
  6871. return true;
  6872. }
  6873. obs_sceneitem_get_pos(item, &pos);
  6874. vec2_add(&pos, &pos, &offset);
  6875. obs_sceneitem_set_pos(item, &pos);
  6876. return true;
  6877. }
  6878. void OBSBasic::Nudge(int dist, MoveDir dir)
  6879. {
  6880. if (ui->preview->Locked())
  6881. return;
  6882. struct vec2 offset;
  6883. vec2_set(&offset, 0.0f, 0.0f);
  6884. switch (dir) {
  6885. case MoveDir::Up:
  6886. offset.y = (float)-dist;
  6887. break;
  6888. case MoveDir::Down:
  6889. offset.y = (float)dist;
  6890. break;
  6891. case MoveDir::Left:
  6892. offset.x = (float)-dist;
  6893. break;
  6894. case MoveDir::Right:
  6895. offset.x = (float)dist;
  6896. break;
  6897. }
  6898. if (!recent_nudge) {
  6899. recent_nudge = true;
  6900. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  6901. GetCurrentScene(), true);
  6902. std::string undo_data(obs_data_get_json(wrapper));
  6903. nudge_timer = new QTimer;
  6904. QObject::connect(
  6905. nudge_timer, &QTimer::timeout,
  6906. [this, &recent_nudge = recent_nudge, undo_data]() {
  6907. OBSDataAutoRelease rwrapper =
  6908. obs_scene_save_transform_states(
  6909. GetCurrentScene(), true);
  6910. std::string redo_data(
  6911. obs_data_get_json(rwrapper));
  6912. undo_s.add_action(
  6913. QTStr("Undo.Transform")
  6914. .arg(obs_source_get_name(
  6915. GetCurrentSceneSource())),
  6916. undo_redo, undo_redo, undo_data,
  6917. redo_data);
  6918. recent_nudge = false;
  6919. });
  6920. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  6921. &QTimer::deleteLater);
  6922. nudge_timer->setSingleShot(true);
  6923. }
  6924. if (nudge_timer) {
  6925. nudge_timer->stop();
  6926. nudge_timer->start(1000);
  6927. } else {
  6928. blog(LOG_ERROR, "No nudge timer!");
  6929. }
  6930. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  6931. }
  6932. void OBSBasic::NudgeUp()
  6933. {
  6934. Nudge(1, MoveDir::Up);
  6935. }
  6936. void OBSBasic::NudgeDown()
  6937. {
  6938. Nudge(1, MoveDir::Down);
  6939. }
  6940. void OBSBasic::NudgeLeft()
  6941. {
  6942. Nudge(1, MoveDir::Left);
  6943. }
  6944. void OBSBasic::NudgeRight()
  6945. {
  6946. Nudge(1, MoveDir::Right);
  6947. }
  6948. void OBSBasic::NudgeUpFar()
  6949. {
  6950. Nudge(10, MoveDir::Up);
  6951. }
  6952. void OBSBasic::NudgeDownFar()
  6953. {
  6954. Nudge(10, MoveDir::Down);
  6955. }
  6956. void OBSBasic::NudgeLeftFar()
  6957. {
  6958. Nudge(10, MoveDir::Left);
  6959. }
  6960. void OBSBasic::NudgeRightFar()
  6961. {
  6962. Nudge(10, MoveDir::Right);
  6963. }
  6964. void OBSBasic::DeleteProjector(OBSProjector *projector)
  6965. {
  6966. for (size_t i = 0; i < projectors.size(); i++) {
  6967. if (projectors[i] == projector) {
  6968. projectors[i]->deleteLater();
  6969. projectors.erase(projectors.begin() + i);
  6970. break;
  6971. }
  6972. }
  6973. }
  6974. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  6975. ProjectorType type)
  6976. {
  6977. /* seriously? 10 monitors? */
  6978. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  6979. return nullptr;
  6980. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6981. "CloseExistingProjectors");
  6982. if (closeProjectors && monitor > -1) {
  6983. for (size_t i = projectors.size(); i > 0; i--) {
  6984. size_t idx = i - 1;
  6985. if (projectors[idx]->GetMonitor() == monitor)
  6986. DeleteProjector(projectors[idx]);
  6987. }
  6988. }
  6989. OBSProjector *projector =
  6990. new OBSProjector(nullptr, source, monitor, type);
  6991. projectors.emplace_back(projector);
  6992. return projector;
  6993. }
  6994. void OBSBasic::OpenStudioProgramProjector()
  6995. {
  6996. int monitor = sender()->property("monitor").toInt();
  6997. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  6998. }
  6999. void OBSBasic::OpenPreviewProjector()
  7000. {
  7001. int monitor = sender()->property("monitor").toInt();
  7002. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7003. }
  7004. void OBSBasic::OpenSourceProjector()
  7005. {
  7006. int monitor = sender()->property("monitor").toInt();
  7007. OBSSceneItem item = GetCurrentSceneItem();
  7008. if (!item)
  7009. return;
  7010. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7011. ProjectorType::Source);
  7012. }
  7013. void OBSBasic::OpenMultiviewProjector()
  7014. {
  7015. int monitor = sender()->property("monitor").toInt();
  7016. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7017. }
  7018. void OBSBasic::OpenSceneProjector()
  7019. {
  7020. int monitor = sender()->property("monitor").toInt();
  7021. OBSScene scene = GetCurrentScene();
  7022. if (!scene)
  7023. return;
  7024. OpenProjector(obs_scene_get_source(scene), monitor,
  7025. ProjectorType::Scene);
  7026. }
  7027. void OBSBasic::OpenStudioProgramWindow()
  7028. {
  7029. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7030. }
  7031. void OBSBasic::OpenPreviewWindow()
  7032. {
  7033. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7034. }
  7035. void OBSBasic::OpenSourceWindow()
  7036. {
  7037. OBSSceneItem item = GetCurrentSceneItem();
  7038. if (!item)
  7039. return;
  7040. OBSSource source = obs_sceneitem_get_source(item);
  7041. OpenProjector(obs_sceneitem_get_source(item), -1,
  7042. ProjectorType::Source);
  7043. }
  7044. void OBSBasic::OpenMultiviewWindow()
  7045. {
  7046. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7047. }
  7048. void OBSBasic::OpenSceneWindow()
  7049. {
  7050. OBSScene scene = GetCurrentScene();
  7051. if (!scene)
  7052. return;
  7053. OBSSource source = obs_scene_get_source(scene);
  7054. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7055. }
  7056. void OBSBasic::OpenSavedProjectors()
  7057. {
  7058. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7059. OpenSavedProjector(info);
  7060. }
  7061. }
  7062. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7063. {
  7064. if (info) {
  7065. OBSProjector *projector = nullptr;
  7066. switch (info->type) {
  7067. case ProjectorType::Source:
  7068. case ProjectorType::Scene: {
  7069. OBSSourceAutoRelease source =
  7070. obs_get_source_by_name(info->name.c_str());
  7071. if (!source)
  7072. return;
  7073. projector = OpenProjector(source, info->monitor,
  7074. info->type);
  7075. break;
  7076. }
  7077. default: {
  7078. projector = OpenProjector(nullptr, info->monitor,
  7079. info->type);
  7080. break;
  7081. }
  7082. }
  7083. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7084. QByteArray byteArray = QByteArray::fromBase64(
  7085. QByteArray(info->geometry.c_str()));
  7086. projector->restoreGeometry(byteArray);
  7087. if (!WindowPositionValid(projector->normalGeometry())) {
  7088. QRect rect = QGuiApplication::primaryScreen()
  7089. ->geometry();
  7090. projector->setGeometry(QStyle::alignedRect(
  7091. Qt::LeftToRight, Qt::AlignCenter,
  7092. size(), rect));
  7093. }
  7094. if (info->alwaysOnTopOverridden)
  7095. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7096. true);
  7097. }
  7098. }
  7099. }
  7100. void OBSBasic::on_actionFullscreenInterface_triggered()
  7101. {
  7102. if (!isFullScreen())
  7103. showFullScreen();
  7104. else
  7105. showNormal();
  7106. }
  7107. void OBSBasic::UpdateTitleBar()
  7108. {
  7109. stringstream name;
  7110. const char *profile =
  7111. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7112. const char *sceneCollection = config_get_string(
  7113. App()->GlobalConfig(), "Basic", "SceneCollection");
  7114. name << "OBS ";
  7115. if (previewProgramMode)
  7116. name << "Studio ";
  7117. name << App()->GetVersionString();
  7118. if (App()->IsPortableMode())
  7119. name << " - Portable Mode";
  7120. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7121. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7122. setWindowTitle(QT_UTF8(name.str().c_str()));
  7123. }
  7124. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7125. {
  7126. char profiles_path[512];
  7127. const char *profile =
  7128. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7129. int ret;
  7130. if (!profile)
  7131. return -1;
  7132. if (!path)
  7133. return -1;
  7134. if (!file)
  7135. file = "";
  7136. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7137. if (ret <= 0)
  7138. return ret;
  7139. if (!*file)
  7140. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7141. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7142. }
  7143. void OBSBasic::on_resetDocks_triggered(bool force)
  7144. {
  7145. /* prune deleted extra docks */
  7146. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7147. if (!extraDocks[i]) {
  7148. extraDocks.removeAt(i);
  7149. }
  7150. }
  7151. if (extraDocks.size() && !force) {
  7152. QMessageBox::StandardButton button = QMessageBox::question(
  7153. this, QTStr("ResetUIWarning.Title"),
  7154. QTStr("ResetUIWarning.Text"));
  7155. if (button == QMessageBox::No)
  7156. return;
  7157. }
  7158. /* undock/hide/center extra docks */
  7159. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7160. if (extraDocks[i]) {
  7161. extraDocks[i]->setVisible(true);
  7162. extraDocks[i]->setFloating(true);
  7163. extraDocks[i]->move(frameGeometry().topLeft() +
  7164. rect().center() -
  7165. extraDocks[i]->rect().center());
  7166. extraDocks[i]->setVisible(false);
  7167. }
  7168. }
  7169. restoreState(startingDockLayout);
  7170. int cx = width();
  7171. int cy = height();
  7172. int cx22_5 = cx * 225 / 1000;
  7173. int cx5 = cx * 5 / 100;
  7174. cy = cy * 225 / 1000;
  7175. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  7176. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7177. ui->mixerDock, ui->transitionsDock,
  7178. ui->controlsDock};
  7179. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  7180. ui->scenesDock->setVisible(true);
  7181. ui->sourcesDock->setVisible(true);
  7182. ui->mixerDock->setVisible(true);
  7183. ui->transitionsDock->setVisible(true);
  7184. ui->controlsDock->setVisible(true);
  7185. statsDock->setVisible(false);
  7186. statsDock->setFloating(true);
  7187. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7188. resizeDocks(docks, sizes, Qt::Horizontal);
  7189. activateWindow();
  7190. }
  7191. void OBSBasic::on_lockDocks_toggled(bool lock)
  7192. {
  7193. QDockWidget::DockWidgetFeatures features =
  7194. lock ? QDockWidget::NoDockWidgetFeatures
  7195. : (QDockWidget::DockWidgetClosable |
  7196. QDockWidget::DockWidgetMovable |
  7197. QDockWidget::DockWidgetFloatable);
  7198. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7199. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7200. ui->scenesDock->setFeatures(mainFeatures);
  7201. ui->sourcesDock->setFeatures(mainFeatures);
  7202. ui->mixerDock->setFeatures(mainFeatures);
  7203. ui->transitionsDock->setFeatures(mainFeatures);
  7204. ui->controlsDock->setFeatures(mainFeatures);
  7205. statsDock->setFeatures(features);
  7206. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7207. if (!extraDocks[i]) {
  7208. extraDocks.removeAt(i);
  7209. } else {
  7210. extraDocks[i]->setFeatures(features);
  7211. }
  7212. }
  7213. }
  7214. void OBSBasic::on_resetUI_triggered()
  7215. {
  7216. on_resetDocks_triggered();
  7217. ui->toggleListboxToolbars->setChecked(true);
  7218. ui->toggleContextBar->setChecked(true);
  7219. ui->toggleSourceIcons->setChecked(true);
  7220. ui->toggleStatusBar->setChecked(true);
  7221. }
  7222. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7223. {
  7224. ui->sourcesToolbar->setVisible(visible);
  7225. ui->scenesToolbar->setVisible(visible);
  7226. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7227. "ShowListboxToolbars", visible);
  7228. }
  7229. void OBSBasic::ShowContextBar()
  7230. {
  7231. on_toggleContextBar_toggled(true);
  7232. }
  7233. void OBSBasic::HideContextBar()
  7234. {
  7235. on_toggleContextBar_toggled(false);
  7236. }
  7237. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7238. {
  7239. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7240. "ShowContextToolbars", visible);
  7241. this->ui->contextContainer->setVisible(visible);
  7242. UpdateContextBar(true);
  7243. }
  7244. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7245. {
  7246. ui->statusbar->setVisible(visible);
  7247. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7248. visible);
  7249. }
  7250. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7251. {
  7252. ui->sources->SetIconsVisible(visible);
  7253. if (advAudioWindow != nullptr)
  7254. advAudioWindow->SetIconsVisible(visible);
  7255. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7256. visible);
  7257. }
  7258. void OBSBasic::on_actionLockPreview_triggered()
  7259. {
  7260. ui->preview->ToggleLocked();
  7261. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7262. }
  7263. void OBSBasic::on_scalingMenu_aboutToShow()
  7264. {
  7265. obs_video_info ovi;
  7266. obs_get_video_info(&ovi);
  7267. QAction *action = ui->actionScaleCanvas;
  7268. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7269. text = text.arg(QString::number(ovi.base_width),
  7270. QString::number(ovi.base_height));
  7271. action->setText(text);
  7272. action = ui->actionScaleOutput;
  7273. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7274. text = text.arg(QString::number(ovi.output_width),
  7275. QString::number(ovi.output_height));
  7276. action->setText(text);
  7277. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7278. ovi.output_height == ovi.base_height));
  7279. UpdatePreviewScalingMenu();
  7280. }
  7281. void OBSBasic::on_actionScaleWindow_triggered()
  7282. {
  7283. ui->preview->SetFixedScaling(false);
  7284. ui->preview->ResetScrollingOffset();
  7285. emit ui->preview->DisplayResized();
  7286. }
  7287. void OBSBasic::on_actionScaleCanvas_triggered()
  7288. {
  7289. ui->preview->SetFixedScaling(true);
  7290. ui->preview->SetScalingLevel(0);
  7291. emit ui->preview->DisplayResized();
  7292. }
  7293. void OBSBasic::on_actionScaleOutput_triggered()
  7294. {
  7295. obs_video_info ovi;
  7296. obs_get_video_info(&ovi);
  7297. ui->preview->SetFixedScaling(true);
  7298. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7299. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7300. int32_t approxScalingLevel =
  7301. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7302. ui->preview->SetScalingLevel(approxScalingLevel);
  7303. ui->preview->SetScalingAmount(scalingAmount);
  7304. emit ui->preview->DisplayResized();
  7305. }
  7306. void OBSBasic::SetShowing(bool showing)
  7307. {
  7308. if (!showing && isVisible()) {
  7309. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7310. "geometry",
  7311. saveGeometry().toBase64().constData());
  7312. /* hide all visible child dialogs */
  7313. visDlgPositions.clear();
  7314. if (!visDialogs.isEmpty()) {
  7315. for (QDialog *dlg : visDialogs) {
  7316. visDlgPositions.append(dlg->pos());
  7317. dlg->hide();
  7318. }
  7319. }
  7320. if (showHide)
  7321. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7322. QTimer::singleShot(0, this, SLOT(hide()));
  7323. if (previewEnabled)
  7324. EnablePreviewDisplay(false);
  7325. #ifdef __APPLE__
  7326. EnableOSXDockIcon(false);
  7327. #endif
  7328. } else if (showing && !isVisible()) {
  7329. if (showHide)
  7330. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7331. QTimer::singleShot(0, this, SLOT(show()));
  7332. if (previewEnabled)
  7333. EnablePreviewDisplay(true);
  7334. #ifdef __APPLE__
  7335. EnableOSXDockIcon(true);
  7336. #endif
  7337. /* raise and activate window to ensure it is on top */
  7338. raise();
  7339. activateWindow();
  7340. /* show all child dialogs that was visible earlier */
  7341. if (!visDialogs.isEmpty()) {
  7342. for (int i = 0; i < visDialogs.size(); ++i) {
  7343. QDialog *dlg = visDialogs[i];
  7344. dlg->move(visDlgPositions[i]);
  7345. dlg->show();
  7346. }
  7347. }
  7348. /* Unminimize window if it was hidden to tray instead of task
  7349. * bar. */
  7350. if (sysTrayMinimizeToTray()) {
  7351. Qt::WindowStates state;
  7352. state = windowState() & ~Qt::WindowMinimized;
  7353. state |= Qt::WindowActive;
  7354. setWindowState(state);
  7355. }
  7356. }
  7357. }
  7358. void OBSBasic::ToggleShowHide()
  7359. {
  7360. bool showing = isVisible();
  7361. if (showing) {
  7362. /* check for modal dialogs */
  7363. EnumDialogs();
  7364. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7365. return;
  7366. }
  7367. SetShowing(!showing);
  7368. }
  7369. void OBSBasic::SystemTrayInit()
  7370. {
  7371. #ifdef __APPLE__
  7372. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  7373. trayIconFile.setIsMask(true);
  7374. #else
  7375. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  7376. #endif
  7377. trayIcon.reset(new QSystemTrayIcon(
  7378. QIcon::fromTheme("obs-tray", trayIconFile), this));
  7379. trayIcon->setToolTip("OBS Studio");
  7380. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  7381. sysTrayStream = new QAction(
  7382. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  7383. : QTStr("Basic.Main.StartStreaming"),
  7384. trayIcon.data());
  7385. sysTrayRecord = new QAction(
  7386. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  7387. : QTStr("Basic.Main.StartRecording"),
  7388. trayIcon.data());
  7389. sysTrayReplayBuffer = new QAction(
  7390. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  7391. : QTStr("Basic.Main.StartReplayBuffer"),
  7392. trayIcon.data());
  7393. sysTrayVirtualCam = new QAction(
  7394. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  7395. : QTStr("Basic.Main.StartVirtualCam"),
  7396. trayIcon.data());
  7397. exit = new QAction(QTStr("Exit"), trayIcon.data());
  7398. trayMenu = new QMenu;
  7399. previewProjector = new QMenu(QTStr("PreviewProjector"));
  7400. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  7401. AddProjectorMenuMonitors(previewProjector, this,
  7402. SLOT(OpenPreviewProjector()));
  7403. AddProjectorMenuMonitors(studioProgramProjector, this,
  7404. SLOT(OpenStudioProgramProjector()));
  7405. trayMenu->addAction(showHide);
  7406. trayMenu->addSeparator();
  7407. trayMenu->addMenu(previewProjector);
  7408. trayMenu->addMenu(studioProgramProjector);
  7409. trayMenu->addSeparator();
  7410. trayMenu->addAction(sysTrayStream);
  7411. trayMenu->addAction(sysTrayRecord);
  7412. trayMenu->addAction(sysTrayReplayBuffer);
  7413. trayMenu->addAction(sysTrayVirtualCam);
  7414. trayMenu->addSeparator();
  7415. trayMenu->addAction(exit);
  7416. trayIcon->setContextMenu(trayMenu);
  7417. trayIcon->show();
  7418. if (outputHandler && !outputHandler->replayBuffer)
  7419. sysTrayReplayBuffer->setEnabled(false);
  7420. sysTrayVirtualCam->setEnabled(vcamEnabled);
  7421. if (Active())
  7422. OnActivate(true);
  7423. connect(trayIcon.data(),
  7424. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  7425. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  7426. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  7427. connect(sysTrayStream, SIGNAL(triggered()), this,
  7428. SLOT(on_streamButton_clicked()));
  7429. connect(sysTrayRecord, SIGNAL(triggered()), this,
  7430. SLOT(on_recordButton_clicked()));
  7431. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  7432. &OBSBasic::ReplayBufferClicked);
  7433. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  7434. &OBSBasic::VCamButtonClicked);
  7435. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  7436. }
  7437. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  7438. {
  7439. // Refresh projector list
  7440. previewProjector->clear();
  7441. studioProgramProjector->clear();
  7442. AddProjectorMenuMonitors(previewProjector, this,
  7443. SLOT(OpenPreviewProjector()));
  7444. AddProjectorMenuMonitors(studioProgramProjector, this,
  7445. SLOT(OpenStudioProgramProjector()));
  7446. #ifdef __APPLE__
  7447. UNUSED_PARAMETER(reason);
  7448. #else
  7449. if (reason == QSystemTrayIcon::Trigger) {
  7450. EnablePreviewDisplay(previewEnabled && !isVisible());
  7451. ToggleShowHide();
  7452. }
  7453. #endif
  7454. }
  7455. void OBSBasic::SysTrayNotify(const QString &text,
  7456. QSystemTrayIcon::MessageIcon n)
  7457. {
  7458. if (trayIcon && trayIcon->isVisible() &&
  7459. QSystemTrayIcon::supportsMessages()) {
  7460. QSystemTrayIcon::MessageIcon icon =
  7461. QSystemTrayIcon::MessageIcon(n);
  7462. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  7463. }
  7464. }
  7465. void OBSBasic::SystemTray(bool firstStarted)
  7466. {
  7467. if (!QSystemTrayIcon::isSystemTrayAvailable())
  7468. return;
  7469. if (!trayIcon && !firstStarted)
  7470. return;
  7471. bool sysTrayWhenStarted = config_get_bool(
  7472. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  7473. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7474. "SysTrayEnabled");
  7475. if (firstStarted)
  7476. SystemTrayInit();
  7477. if (!sysTrayEnabled) {
  7478. trayIcon->hide();
  7479. } else {
  7480. trayIcon->show();
  7481. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  7482. EnablePreviewDisplay(false);
  7483. #ifdef __APPLE__
  7484. EnableOSXDockIcon(false);
  7485. #endif
  7486. opt_minimize_tray = false;
  7487. }
  7488. }
  7489. if (isVisible())
  7490. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7491. else
  7492. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7493. }
  7494. bool OBSBasic::sysTrayMinimizeToTray()
  7495. {
  7496. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  7497. "SysTrayMinimizeToTray");
  7498. }
  7499. void OBSBasic::on_actionMainUndo_triggered()
  7500. {
  7501. undo_s.undo();
  7502. }
  7503. void OBSBasic::on_actionMainRedo_triggered()
  7504. {
  7505. undo_s.redo();
  7506. }
  7507. void OBSBasic::on_actionCopySource_triggered()
  7508. {
  7509. clipboard.clear();
  7510. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  7511. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  7512. if (!item)
  7513. continue;
  7514. OBSSource source = obs_sceneitem_get_source(item);
  7515. SourceCopyInfo copyInfo;
  7516. copyInfo.weak_source = OBSGetWeakRef(source);
  7517. obs_sceneitem_get_info(item, &copyInfo.transform);
  7518. obs_sceneitem_get_crop(item, &copyInfo.crop);
  7519. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  7520. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  7521. copyInfo.visible = obs_sceneitem_visible(item);
  7522. clipboard.push_back(copyInfo);
  7523. }
  7524. UpdateEditMenu();
  7525. }
  7526. void OBSBasic::on_actionPasteRef_triggered()
  7527. {
  7528. OBSSource scene_source = GetCurrentSceneSource();
  7529. OBSData undo_data = BackupScene(scene_source);
  7530. OBSScene scene = GetCurrentScene();
  7531. undo_s.push_disabled();
  7532. for (size_t i = clipboard.size(); i > 0; i--) {
  7533. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7534. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  7535. if (!source)
  7536. continue;
  7537. const char *name = obs_source_get_name(source);
  7538. /* do not allow duplicate refs of the same group in the same
  7539. * scene */
  7540. if (!!obs_scene_get_group(scene, name)) {
  7541. continue;
  7542. }
  7543. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  7544. }
  7545. undo_s.pop_disabled();
  7546. QString action_name = QTStr("Undo.PasteSourceRef");
  7547. const char *scene_name = obs_source_get_name(scene_source);
  7548. OBSData redo_data = BackupScene(scene_source);
  7549. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7550. redo_data);
  7551. }
  7552. void OBSBasic::on_actionPasteDup_triggered()
  7553. {
  7554. OBSSource scene_source = GetCurrentSceneSource();
  7555. OBSData undo_data = BackupScene(scene_source);
  7556. undo_s.push_disabled();
  7557. for (size_t i = clipboard.size(); i > 0; i--) {
  7558. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7559. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  7560. }
  7561. undo_s.pop_disabled();
  7562. QString action_name = QTStr("Undo.PasteSource");
  7563. const char *scene_name = obs_source_get_name(scene_source);
  7564. OBSData redo_data = BackupScene(scene_source);
  7565. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7566. redo_data);
  7567. }
  7568. void OBSBasic::AudioMixerCopyFilters()
  7569. {
  7570. QAction *action = reinterpret_cast<QAction *>(sender());
  7571. VolControl *vol = action->property("volControl").value<VolControl *>();
  7572. obs_source_t *source = vol->GetSource();
  7573. copyFiltersSource = obs_source_get_weak_source(source);
  7574. }
  7575. void OBSBasic::AudioMixerPasteFilters()
  7576. {
  7577. QAction *action = reinterpret_cast<QAction *>(sender());
  7578. VolControl *vol = action->property("volControl").value<VolControl *>();
  7579. obs_source_t *dstSource = vol->GetSource();
  7580. OBSSourceAutoRelease source =
  7581. obs_weak_source_get_source(copyFiltersSource);
  7582. if (source == dstSource)
  7583. return;
  7584. obs_source_copy_filters(dstSource, source);
  7585. }
  7586. void OBSBasic::SceneCopyFilters()
  7587. {
  7588. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  7589. }
  7590. void OBSBasic::ScenePasteFilters()
  7591. {
  7592. OBSSourceAutoRelease source =
  7593. obs_weak_source_get_source(copyFiltersSource);
  7594. OBSSource dstSource = GetCurrentSceneSource();
  7595. if (source == dstSource)
  7596. return;
  7597. obs_source_copy_filters(dstSource, source);
  7598. }
  7599. void OBSBasic::on_actionCopyFilters_triggered()
  7600. {
  7601. OBSSceneItem item = GetCurrentSceneItem();
  7602. if (!item)
  7603. return;
  7604. OBSSource source = obs_sceneitem_get_source(item);
  7605. copyFiltersSource = obs_source_get_weak_source(source);
  7606. ui->actionPasteFilters->setEnabled(true);
  7607. }
  7608. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  7609. obs_source_t *source,
  7610. obs_data_array_t *undo_array,
  7611. obs_data_array_t *redo_array)
  7612. {
  7613. auto undo_redo = [this](const std::string &json) {
  7614. OBSDataAutoRelease data =
  7615. obs_data_create_from_json(json.c_str());
  7616. OBSDataArrayAutoRelease array =
  7617. obs_data_get_array(data, "array");
  7618. const char *name = obs_data_get_string(data, "name");
  7619. OBSSourceAutoRelease source = obs_get_source_by_name(name);
  7620. obs_source_restore_filters(source, array);
  7621. if (filters)
  7622. filters->UpdateSource(source);
  7623. };
  7624. const char *name = obs_source_get_name(source);
  7625. OBSDataAutoRelease undo_data = obs_data_create();
  7626. OBSDataAutoRelease redo_data = obs_data_create();
  7627. obs_data_set_array(undo_data, "array", undo_array);
  7628. obs_data_set_array(redo_data, "array", redo_array);
  7629. obs_data_set_string(undo_data, "name", name);
  7630. obs_data_set_string(redo_data, "name", name);
  7631. undo_s.add_action(text, undo_redo, undo_redo,
  7632. obs_data_get_json(undo_data),
  7633. obs_data_get_json(redo_data));
  7634. }
  7635. void OBSBasic::on_actionPasteFilters_triggered()
  7636. {
  7637. OBSSourceAutoRelease source =
  7638. obs_weak_source_get_source(copyFiltersSource);
  7639. OBSSceneItem sceneItem = GetCurrentSceneItem();
  7640. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  7641. if (source == dstSource)
  7642. return;
  7643. OBSDataArrayAutoRelease undo_array =
  7644. obs_source_backup_filters(dstSource);
  7645. obs_source_copy_filters(dstSource, source);
  7646. OBSDataArrayAutoRelease redo_array =
  7647. obs_source_backup_filters(dstSource);
  7648. const char *srcName = obs_source_get_name(source);
  7649. const char *dstName = obs_source_get_name(dstSource);
  7650. QString text =
  7651. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  7652. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  7653. redo_array);
  7654. }
  7655. static void ConfirmColor(SourceTree *sources, const QColor &color,
  7656. QModelIndexList selectedItems)
  7657. {
  7658. for (int x = 0; x < selectedItems.count(); x++) {
  7659. SourceTreeItem *treeItem =
  7660. sources->GetItemWidget(selectedItems[x].row());
  7661. treeItem->setStyleSheet("background: " +
  7662. color.name(QColor::HexArgb));
  7663. treeItem->style()->unpolish(treeItem);
  7664. treeItem->style()->polish(treeItem);
  7665. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  7666. OBSDataAutoRelease privData =
  7667. obs_sceneitem_get_private_settings(sceneItem);
  7668. obs_data_set_int(privData, "color-preset", 1);
  7669. obs_data_set_string(privData, "color",
  7670. QT_TO_UTF8(color.name(QColor::HexArgb)));
  7671. }
  7672. }
  7673. void OBSBasic::ColorChange()
  7674. {
  7675. QModelIndexList selectedItems =
  7676. ui->sources->selectionModel()->selectedIndexes();
  7677. QAction *action = qobject_cast<QAction *>(sender());
  7678. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  7679. if (selectedItems.count() == 0)
  7680. return;
  7681. if (colorButton) {
  7682. int preset = colorButton->property("bgColor").value<int>();
  7683. for (int x = 0; x < selectedItems.count(); x++) {
  7684. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  7685. selectedItems[x].row());
  7686. treeItem->setStyleSheet("");
  7687. treeItem->setProperty("bgColor", preset);
  7688. treeItem->style()->unpolish(treeItem);
  7689. treeItem->style()->polish(treeItem);
  7690. OBSSceneItem sceneItem =
  7691. ui->sources->Get(selectedItems[x].row());
  7692. OBSDataAutoRelease privData =
  7693. obs_sceneitem_get_private_settings(sceneItem);
  7694. obs_data_set_int(privData, "color-preset", preset + 1);
  7695. obs_data_set_string(privData, "color", "");
  7696. }
  7697. for (int i = 1; i < 9; i++) {
  7698. stringstream button;
  7699. button << "preset" << i;
  7700. QPushButton *cButton =
  7701. colorButton->parentWidget()
  7702. ->findChild<QPushButton *>(
  7703. button.str().c_str());
  7704. cButton->setStyleSheet("border: 1px solid black");
  7705. }
  7706. colorButton->setStyleSheet("border: 2px solid black");
  7707. } else if (action) {
  7708. int preset = action->property("bgColor").value<int>();
  7709. if (preset == 1) {
  7710. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  7711. SourceTreeItem *curTreeItem =
  7712. GetItemWidgetFromSceneItem(curSceneItem);
  7713. OBSDataAutoRelease curPrivData =
  7714. obs_sceneitem_get_private_settings(
  7715. curSceneItem);
  7716. int oldPreset =
  7717. obs_data_get_int(curPrivData, "color-preset");
  7718. const QString oldSheet = curTreeItem->styleSheet();
  7719. auto liveChangeColor = [=](const QColor &color) {
  7720. if (color.isValid()) {
  7721. curTreeItem->setStyleSheet(
  7722. "background: " +
  7723. color.name(QColor::HexArgb));
  7724. }
  7725. };
  7726. auto changedColor = [=](const QColor &color) {
  7727. if (color.isValid()) {
  7728. ConfirmColor(ui->sources, color,
  7729. selectedItems);
  7730. }
  7731. };
  7732. auto rejected = [=]() {
  7733. if (oldPreset == 1) {
  7734. curTreeItem->setStyleSheet(oldSheet);
  7735. curTreeItem->setProperty("bgColor", 0);
  7736. } else if (oldPreset == 0) {
  7737. curTreeItem->setStyleSheet(
  7738. "background: none");
  7739. curTreeItem->setProperty("bgColor", 0);
  7740. } else {
  7741. curTreeItem->setStyleSheet("");
  7742. curTreeItem->setProperty("bgColor",
  7743. oldPreset - 1);
  7744. }
  7745. curTreeItem->style()->unpolish(curTreeItem);
  7746. curTreeItem->style()->polish(curTreeItem);
  7747. };
  7748. QColorDialog::ColorDialogOptions options =
  7749. QColorDialog::ShowAlphaChannel;
  7750. const char *oldColor =
  7751. obs_data_get_string(curPrivData, "color");
  7752. const char *customColor = *oldColor != 0 ? oldColor
  7753. : "#55FF0000";
  7754. #ifndef _WIN32
  7755. options |= QColorDialog::DontUseNativeDialog;
  7756. #endif
  7757. QColorDialog *colorDialog = new QColorDialog(this);
  7758. colorDialog->setOptions(options);
  7759. colorDialog->setCurrentColor(QColor(customColor));
  7760. connect(colorDialog, &QColorDialog::currentColorChanged,
  7761. liveChangeColor);
  7762. connect(colorDialog, &QColorDialog::colorSelected,
  7763. changedColor);
  7764. connect(colorDialog, &QColorDialog::rejected, rejected);
  7765. colorDialog->open();
  7766. } else {
  7767. for (int x = 0; x < selectedItems.count(); x++) {
  7768. SourceTreeItem *treeItem =
  7769. ui->sources->GetItemWidget(
  7770. selectedItems[x].row());
  7771. treeItem->setStyleSheet("background: none");
  7772. treeItem->setProperty("bgColor", preset);
  7773. treeItem->style()->unpolish(treeItem);
  7774. treeItem->style()->polish(treeItem);
  7775. OBSSceneItem sceneItem = ui->sources->Get(
  7776. selectedItems[x].row());
  7777. OBSDataAutoRelease privData =
  7778. obs_sceneitem_get_private_settings(
  7779. sceneItem);
  7780. obs_data_set_int(privData, "color-preset",
  7781. preset);
  7782. obs_data_set_string(privData, "color", "");
  7783. }
  7784. }
  7785. }
  7786. }
  7787. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  7788. {
  7789. int i = 0;
  7790. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  7791. OBSSceneItem item = ui->sources->Get(i);
  7792. int64_t id = obs_sceneitem_get_id(sceneItem);
  7793. while (treeItem && obs_sceneitem_get_id(item) != id) {
  7794. i++;
  7795. treeItem = ui->sources->GetItemWidget(i);
  7796. item = ui->sources->Get(i);
  7797. }
  7798. if (treeItem)
  7799. return treeItem;
  7800. return nullptr;
  7801. }
  7802. void OBSBasic::on_autoConfigure_triggered()
  7803. {
  7804. AutoConfig test(this);
  7805. test.setModal(true);
  7806. test.show();
  7807. test.exec();
  7808. }
  7809. void OBSBasic::on_stats_triggered()
  7810. {
  7811. if (!stats.isNull()) {
  7812. stats->show();
  7813. stats->raise();
  7814. return;
  7815. }
  7816. OBSBasicStats *statsDlg;
  7817. statsDlg = new OBSBasicStats(nullptr);
  7818. statsDlg->show();
  7819. stats = statsDlg;
  7820. }
  7821. void OBSBasic::on_actionShowAbout_triggered()
  7822. {
  7823. if (about)
  7824. about->close();
  7825. about = new OBSAbout(this);
  7826. about->show();
  7827. about->setAttribute(Qt::WA_DeleteOnClose, true);
  7828. }
  7829. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  7830. {
  7831. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  7832. action->setProperty("uuid", dock->property("uuid").toString());
  7833. action->setCheckable(true);
  7834. assignDockToggle(dock, action);
  7835. extraDocks.push_back(dock);
  7836. bool lock = ui->lockDocks->isChecked();
  7837. QDockWidget::DockWidgetFeatures features =
  7838. lock ? QDockWidget::NoDockWidgetFeatures
  7839. : (QDockWidget::DockWidgetClosable |
  7840. QDockWidget::DockWidgetMovable |
  7841. QDockWidget::DockWidgetFloatable);
  7842. dock->setFeatures(features);
  7843. /* prune deleted docks */
  7844. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7845. if (!extraDocks[i]) {
  7846. extraDocks.removeAt(i);
  7847. }
  7848. }
  7849. return action;
  7850. }
  7851. OBSBasic *OBSBasic::Get()
  7852. {
  7853. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  7854. }
  7855. bool OBSBasic::StreamingActive()
  7856. {
  7857. if (!outputHandler)
  7858. return false;
  7859. return outputHandler->StreamingActive();
  7860. }
  7861. bool OBSBasic::RecordingActive()
  7862. {
  7863. if (!outputHandler)
  7864. return false;
  7865. return outputHandler->RecordingActive();
  7866. }
  7867. bool OBSBasic::ReplayBufferActive()
  7868. {
  7869. if (!outputHandler)
  7870. return false;
  7871. return outputHandler->ReplayBufferActive();
  7872. }
  7873. bool OBSBasic::VirtualCamActive()
  7874. {
  7875. if (!outputHandler)
  7876. return false;
  7877. return outputHandler->VirtualCamActive();
  7878. }
  7879. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  7880. : QStyledItemDelegate(parent)
  7881. {
  7882. }
  7883. void SceneRenameDelegate::setEditorData(QWidget *editor,
  7884. const QModelIndex &index) const
  7885. {
  7886. QStyledItemDelegate::setEditorData(editor, index);
  7887. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7888. if (lineEdit)
  7889. lineEdit->selectAll();
  7890. }
  7891. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  7892. {
  7893. if (event->type() == QEvent::KeyPress) {
  7894. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  7895. if (keyEvent->key() == Qt::Key_Escape) {
  7896. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7897. if (lineEdit)
  7898. lineEdit->undo();
  7899. }
  7900. }
  7901. return QStyledItemDelegate::eventFilter(editor, event);
  7902. }
  7903. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  7904. {
  7905. if (!error.isEmpty())
  7906. return;
  7907. patronJson = QT_TO_UTF8(text);
  7908. }
  7909. void OBSBasic::PauseRecording()
  7910. {
  7911. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7912. os_atomic_load_bool(&recording_paused))
  7913. return;
  7914. obs_output_t *output = outputHandler->fileOutput;
  7915. if (obs_output_pause(output, true)) {
  7916. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  7917. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  7918. pause->blockSignals(true);
  7919. pause->setChecked(true);
  7920. pause->blockSignals(false);
  7921. ui->statusbar->RecordingPaused();
  7922. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  7923. if (trayIcon && trayIcon->isVisible()) {
  7924. #ifdef __APPLE__
  7925. QIcon trayIconFile =
  7926. QIcon(":/res/images/obs_paused_macos.svg");
  7927. trayIconFile.setIsMask(true);
  7928. #else
  7929. QIcon trayIconFile =
  7930. QIcon(":/res/images/obs_paused.png");
  7931. #endif
  7932. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  7933. trayIconFile));
  7934. }
  7935. os_atomic_set_bool(&recording_paused, true);
  7936. if (replay)
  7937. replay->setEnabled(false);
  7938. if (api)
  7939. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  7940. if (os_atomic_load_bool(&replaybuf_active))
  7941. ShowReplayBufferPauseWarning();
  7942. }
  7943. }
  7944. void OBSBasic::UnpauseRecording()
  7945. {
  7946. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7947. !os_atomic_load_bool(&recording_paused))
  7948. return;
  7949. obs_output_t *output = outputHandler->fileOutput;
  7950. if (obs_output_pause(output, false)) {
  7951. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  7952. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  7953. pause->blockSignals(true);
  7954. pause->setChecked(false);
  7955. pause->blockSignals(false);
  7956. ui->statusbar->RecordingUnpaused();
  7957. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  7958. if (trayIcon && trayIcon->isVisible()) {
  7959. #ifdef __APPLE__
  7960. QIcon trayIconFile =
  7961. QIcon(":/res/images/tray_active_macos.svg");
  7962. trayIconFile.setIsMask(true);
  7963. #else
  7964. QIcon trayIconFile =
  7965. QIcon(":/res/images/tray_active.png");
  7966. #endif
  7967. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  7968. trayIconFile));
  7969. }
  7970. os_atomic_set_bool(&recording_paused, false);
  7971. if (replay)
  7972. replay->setEnabled(true);
  7973. if (api)
  7974. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  7975. }
  7976. }
  7977. void OBSBasic::PauseToggled()
  7978. {
  7979. if (!pause || !outputHandler || !outputHandler->fileOutput)
  7980. return;
  7981. obs_output_t *output = outputHandler->fileOutput;
  7982. bool enable = !obs_output_paused(output);
  7983. if (enable)
  7984. PauseRecording();
  7985. else
  7986. UnpauseRecording();
  7987. }
  7988. void OBSBasic::UpdatePause(bool activate)
  7989. {
  7990. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  7991. pause.reset();
  7992. return;
  7993. }
  7994. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  7995. bool adv = astrcmpi(mode, "Advanced") == 0;
  7996. bool shared;
  7997. if (adv) {
  7998. const char *recType =
  7999. config_get_string(basicConfig, "AdvOut", "RecType");
  8000. if (astrcmpi(recType, "FFmpeg") == 0) {
  8001. shared = config_get_bool(basicConfig, "AdvOut",
  8002. "FFOutputToFile");
  8003. } else {
  8004. const char *recordEncoder = config_get_string(
  8005. basicConfig, "AdvOut", "RecEncoder");
  8006. shared = astrcmpi(recordEncoder, "none") == 0;
  8007. }
  8008. } else {
  8009. const char *quality = config_get_string(
  8010. basicConfig, "SimpleOutput", "RecQuality");
  8011. shared = strcmp(quality, "Stream") == 0;
  8012. }
  8013. if (!shared) {
  8014. pause.reset(new QPushButton());
  8015. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8016. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8017. pause->setCheckable(true);
  8018. pause->setChecked(false);
  8019. pause->setProperty("themeID",
  8020. QVariant(QStringLiteral("pauseIconSmall")));
  8021. QSizePolicy sp;
  8022. sp.setHeightForWidth(true);
  8023. pause->setSizePolicy(sp);
  8024. connect(pause.data(), &QAbstractButton::clicked, this,
  8025. &OBSBasic::PauseToggled);
  8026. ui->recordingLayout->addWidget(pause.data());
  8027. } else {
  8028. pause.reset();
  8029. }
  8030. }
  8031. void OBSBasic::UpdateReplayBuffer(bool activate)
  8032. {
  8033. if (!activate || !outputHandler ||
  8034. !outputHandler->ReplayBufferActive()) {
  8035. replay.reset();
  8036. return;
  8037. }
  8038. replay.reset(new QPushButton());
  8039. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  8040. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  8041. replay->setChecked(false);
  8042. replay->setProperty("themeID",
  8043. QVariant(QStringLiteral("replayIconSmall")));
  8044. QSizePolicy sp;
  8045. sp.setHeightForWidth(true);
  8046. replay->setSizePolicy(sp);
  8047. connect(replay.data(), &QAbstractButton::clicked, this,
  8048. &OBSBasic::ReplayBufferSave);
  8049. replayLayout->addWidget(replay.data());
  8050. setTabOrder(replayLayout->itemAt(0)->widget(),
  8051. replayLayout->itemAt(1)->widget());
  8052. setTabOrder(replayLayout->itemAt(1)->widget(),
  8053. ui->buttonsVLayout->itemAt(3)->widget());
  8054. }
  8055. #define MBYTE (1024ULL * 1024ULL)
  8056. #define MBYTES_LEFT_STOP_REC 50ULL
  8057. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8058. const char *OBSBasic::GetCurrentOutputPath()
  8059. {
  8060. const char *path = nullptr;
  8061. const char *mode = config_get_string(Config(), "Output", "Mode");
  8062. if (strcmp(mode, "Advanced") == 0) {
  8063. const char *advanced_mode =
  8064. config_get_string(Config(), "AdvOut", "RecType");
  8065. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8066. path = config_get_string(Config(), "AdvOut",
  8067. "FFFilePath");
  8068. } else {
  8069. path = config_get_string(Config(), "AdvOut",
  8070. "RecFilePath");
  8071. }
  8072. } else {
  8073. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8074. }
  8075. return path;
  8076. }
  8077. void OBSBasic::OutputPathInvalidMessage()
  8078. {
  8079. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8080. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8081. QTStr("Output.BadPath.Text"));
  8082. }
  8083. bool OBSBasic::OutputPathValid()
  8084. {
  8085. const char *mode = config_get_string(Config(), "Output", "Mode");
  8086. if (strcmp(mode, "Advanced") == 0) {
  8087. const char *advanced_mode =
  8088. config_get_string(Config(), "AdvOut", "RecType");
  8089. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8090. bool is_local = config_get_bool(Config(), "AdvOut",
  8091. "FFOutputToFile");
  8092. if (!is_local)
  8093. return true;
  8094. }
  8095. }
  8096. const char *path = GetCurrentOutputPath();
  8097. return path && *path && QDir(path).exists();
  8098. }
  8099. void OBSBasic::DiskSpaceMessage()
  8100. {
  8101. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8102. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8103. QTStr("Output.RecordNoSpace.Msg"));
  8104. }
  8105. bool OBSBasic::LowDiskSpace()
  8106. {
  8107. const char *path;
  8108. path = GetCurrentOutputPath();
  8109. if (!path)
  8110. return false;
  8111. uint64_t num_bytes = os_get_free_disk_space(path);
  8112. if (num_bytes < (MAX_BYTES_LEFT))
  8113. return true;
  8114. else
  8115. return false;
  8116. }
  8117. void OBSBasic::CheckDiskSpaceRemaining()
  8118. {
  8119. if (LowDiskSpace()) {
  8120. StopRecording();
  8121. StopReplayBuffer();
  8122. DiskSpaceMessage();
  8123. }
  8124. }
  8125. void OBSBasic::ScenesReordered()
  8126. {
  8127. OBSProjector::UpdateMultiviewProjectors();
  8128. }
  8129. void OBSBasic::ResetStatsHotkey()
  8130. {
  8131. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8132. foreach(OBSBasicStats * s, list) s->Reset();
  8133. }
  8134. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  8135. {
  8136. QWidget *widget = childAt(pos);
  8137. const char *className = nullptr;
  8138. QString objName;
  8139. if (widget != nullptr) {
  8140. className = widget->metaObject()->className();
  8141. objName = widget->objectName();
  8142. }
  8143. QPoint globalPos = mapToGlobal(pos);
  8144. if (className && strstr(className, "Dock") != nullptr &&
  8145. !objName.isEmpty()) {
  8146. if (objName.compare("scenesDock") == 0) {
  8147. ui->scenes->customContextMenuRequested(globalPos);
  8148. } else if (objName.compare("sourcesDock") == 0) {
  8149. ui->sources->customContextMenuRequested(globalPos);
  8150. } else if (objName.compare("mixerDock") == 0) {
  8151. StackedMixerAreaContextMenuRequested();
  8152. }
  8153. } else if (!className) {
  8154. ui->menuDocks->exec(globalPos);
  8155. }
  8156. }
  8157. void OBSBasic::UpdateProjectorHideCursor()
  8158. {
  8159. for (size_t i = 0; i < projectors.size(); i++)
  8160. projectors[i]->SetHideCursor();
  8161. }
  8162. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8163. {
  8164. for (size_t i = 0; i < projectors.size(); i++)
  8165. SetAlwaysOnTop(projectors[i], top);
  8166. }
  8167. void OBSBasic::ResetProjectors()
  8168. {
  8169. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8170. ClearProjectors();
  8171. LoadSavedProjectors(savedProjectorList);
  8172. OpenSavedProjectors();
  8173. }
  8174. void OBSBasic::on_sourcePropertiesButton_clicked()
  8175. {
  8176. on_actionSourceProperties_triggered();
  8177. }
  8178. void OBSBasic::on_sourceFiltersButton_clicked()
  8179. {
  8180. OpenFilters();
  8181. }
  8182. void OBSBasic::on_sourceInteractButton_clicked()
  8183. {
  8184. on_actionInteract_triggered();
  8185. }
  8186. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8187. {
  8188. ui->statusbar->clearMessage();
  8189. ui->statusbar->showMessage(message, 10000);
  8190. }
  8191. void OBSBasic::UpdatePreviewSafeAreas()
  8192. {
  8193. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8194. "ShowSafeAreas");
  8195. }
  8196. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8197. {
  8198. if (!SetDisplayAffinitySupported())
  8199. return;
  8200. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8201. "BasicWindow",
  8202. "HideOBSWindowsFromCapture");
  8203. // Don't hide projectors, those are designed to be visible / captured
  8204. if (window->property("isOBSProjectorWindow") == true)
  8205. return;
  8206. #ifdef _WIN32
  8207. HWND hwnd = (HWND)window->winId();
  8208. DWORD curAffinity;
  8209. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  8210. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  8211. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  8212. else if (!hideFromCapture && curAffinity != WDA_NONE)
  8213. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  8214. }
  8215. #else
  8216. // TODO: Implement for other platforms if possible. Don't forget to
  8217. // implement SetDisplayAffinitySupported too!
  8218. UNUSED_PARAMETER(hideFromCapture);
  8219. #endif
  8220. }