window-basic-main.cpp 223 KB

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