window-basic-main.cpp 210 KB

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