window-basic-main.cpp 210 KB

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