window-basic-main.cpp 245 KB

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