window-basic-main.cpp 248 KB

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