window-basic-main.cpp 214 KB

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