1
0

window-basic-main.cpp 275 KB

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