window-basic-main.cpp 249 KB

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