window-basic-main.cpp 214 KB

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