window-basic-main.cpp 224 KB

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