window-basic-main.cpp 224 KB

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