window-basic-main.cpp 211 KB

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