window-basic-main.cpp 279 KB

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