window-basic-main.cpp 271 KB

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