window-basic-main.cpp 212 KB

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