window-basic-main.cpp 245 KB

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