window-basic-main.cpp 273 KB

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