1
0

window-basic-main.cpp 214 KB

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