window-basic-main.cpp 265 KB

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