window-basic-main.cpp 270 KB

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