window-basic-main.cpp 225 KB

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