1
0

window-basic-main.cpp 273 KB

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