window-basic-main.cpp 219 KB

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