window-basic-main.cpp 219 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301
  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. bool closed = true;
  2149. if (interaction)
  2150. closed = interaction->close();
  2151. if (!closed)
  2152. return;
  2153. interaction = new OBSBasicInteraction(this, source);
  2154. interaction->Init();
  2155. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2156. }
  2157. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2158. {
  2159. bool closed = true;
  2160. if (properties)
  2161. closed = properties->close();
  2162. if (!closed)
  2163. return;
  2164. properties = new OBSBasicProperties(this, source);
  2165. properties->Init();
  2166. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2167. }
  2168. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2169. {
  2170. bool closed = true;
  2171. if (filters)
  2172. closed = filters->close();
  2173. if (!closed)
  2174. return;
  2175. filters = new OBSBasicFilters(this, source);
  2176. filters->Init();
  2177. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2178. }
  2179. /* Qt callbacks for invokeMethod */
  2180. void OBSBasic::AddScene(OBSSource source)
  2181. {
  2182. const char *name = obs_source_get_name(source);
  2183. obs_scene_t *scene = obs_scene_from_source(source);
  2184. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2185. SetOBSRef(item, OBSScene(scene));
  2186. ui->scenes->addItem(item);
  2187. obs_hotkey_register_source(
  2188. source, "OBSBasic.SelectScene",
  2189. Str("Basic.Hotkeys.SelectScene"),
  2190. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2191. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2192. App()->GetMainWindow());
  2193. auto potential_source =
  2194. static_cast<obs_source_t *>(data);
  2195. auto source = obs_source_get_ref(potential_source);
  2196. if (source && pressed)
  2197. main->SetCurrentScene(source);
  2198. obs_source_release(source);
  2199. },
  2200. static_cast<obs_source_t *>(source));
  2201. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2202. SignalContainer<OBSScene> container;
  2203. container.ref = scene;
  2204. container.handlers.assign({
  2205. std::make_shared<OBSSignal>(handler, "item_add",
  2206. OBSBasic::SceneItemAdded, this),
  2207. std::make_shared<OBSSignal>(handler, "reorder",
  2208. OBSBasic::SceneReordered, this),
  2209. std::make_shared<OBSSignal>(handler, "refresh",
  2210. OBSBasic::SceneRefreshed, this),
  2211. });
  2212. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2213. QVariant::fromValue(container));
  2214. /* if the scene already has items (a duplicated scene) add them */
  2215. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2216. AddSceneItem(item);
  2217. };
  2218. using addSceneItem_t = decltype(addSceneItem);
  2219. obs_scene_enum_items(
  2220. scene,
  2221. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2222. addSceneItem_t *func;
  2223. func = reinterpret_cast<addSceneItem_t *>(param);
  2224. (*func)(item);
  2225. return true;
  2226. },
  2227. &addSceneItem);
  2228. SaveProject();
  2229. if (!disableSaving) {
  2230. obs_source_t *source = obs_scene_get_source(scene);
  2231. blog(LOG_INFO, "User added scene '%s'",
  2232. obs_source_get_name(source));
  2233. OBSProjector::UpdateMultiviewProjectors();
  2234. }
  2235. if (api)
  2236. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2237. }
  2238. void OBSBasic::RemoveScene(OBSSource source)
  2239. {
  2240. obs_scene_t *scene = obs_scene_from_source(source);
  2241. QListWidgetItem *sel = nullptr;
  2242. int count = ui->scenes->count();
  2243. for (int i = 0; i < count; i++) {
  2244. auto item = ui->scenes->item(i);
  2245. auto cur_scene = GetOBSRef<OBSScene>(item);
  2246. if (cur_scene != scene)
  2247. continue;
  2248. sel = item;
  2249. break;
  2250. }
  2251. if (sel != nullptr) {
  2252. if (sel == ui->scenes->currentItem())
  2253. ui->sources->Clear();
  2254. delete sel;
  2255. }
  2256. SaveProject();
  2257. if (!disableSaving) {
  2258. blog(LOG_INFO, "User Removed scene '%s'",
  2259. obs_source_get_name(source));
  2260. OBSProjector::UpdateMultiviewProjectors();
  2261. }
  2262. if (api)
  2263. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2264. }
  2265. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2266. {
  2267. obs_sceneitem_t *selectedItem =
  2268. reinterpret_cast<obs_sceneitem_t *>(param);
  2269. if (obs_sceneitem_is_group(item))
  2270. obs_sceneitem_group_enum_items(item, select_one, param);
  2271. obs_sceneitem_select(item, (selectedItem == item));
  2272. UNUSED_PARAMETER(scene);
  2273. return true;
  2274. }
  2275. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2276. {
  2277. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2278. if (GetCurrentScene() == scene)
  2279. ui->sources->Add(item);
  2280. SaveProject();
  2281. if (!disableSaving) {
  2282. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2283. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2284. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2285. obs_source_get_name(itemSource),
  2286. obs_source_get_id(itemSource),
  2287. obs_source_get_name(sceneSource));
  2288. obs_scene_enum_items(scene, select_one,
  2289. (obs_sceneitem_t *)item);
  2290. }
  2291. }
  2292. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2293. {
  2294. if (source) {
  2295. obs_scene_t *scene = obs_scene_from_source(source);
  2296. const char *name = obs_source_get_name(source);
  2297. if (!scene)
  2298. return;
  2299. QList<QListWidgetItem *> items =
  2300. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2301. if (items.count()) {
  2302. sceneChanging = true;
  2303. ui->scenes->setCurrentItem(items.first());
  2304. sceneChanging = false;
  2305. OBSScene curScene =
  2306. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2307. if (api && scene != curScene)
  2308. api->on_event(
  2309. OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2310. }
  2311. }
  2312. }
  2313. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2314. const QString &prevName)
  2315. {
  2316. QList<QListWidgetItem *> items =
  2317. listWidget->findItems(prevName, Qt::MatchExactly);
  2318. for (int i = 0; i < items.count(); i++)
  2319. items[i]->setText(newName);
  2320. }
  2321. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2322. QString prevName)
  2323. {
  2324. RenameListValues(ui->scenes, newName, prevName);
  2325. for (size_t i = 0; i < volumes.size(); i++) {
  2326. if (volumes[i]->GetName().compare(prevName) == 0)
  2327. volumes[i]->SetName(newName);
  2328. }
  2329. for (size_t i = 0; i < projectors.size(); i++) {
  2330. if (projectors[i]->GetSource() == source)
  2331. projectors[i]->RenameProjector(prevName, newName);
  2332. }
  2333. SaveProject();
  2334. obs_scene_t *scene = obs_scene_from_source(source);
  2335. if (scene)
  2336. OBSProjector::UpdateMultiviewProjectors();
  2337. UpdateContextBar();
  2338. }
  2339. void OBSBasic::UpdateContextBar()
  2340. {
  2341. OBSSceneItem item = GetCurrentSceneItem();
  2342. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2343. if (la) {
  2344. delete la->widget();
  2345. ui->emptySpace->layout()->removeItem(la);
  2346. }
  2347. if (item) {
  2348. obs_source_t *source = obs_sceneitem_get_source(item);
  2349. const char *id = obs_source_get_unversioned_id(source);
  2350. uint32_t flags = obs_source_get_output_flags(source);
  2351. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2352. MediaControls *mediaControls =
  2353. new MediaControls(ui->emptySpace);
  2354. mediaControls->SetSource(source);
  2355. ui->emptySpace->layout()->addWidget(mediaControls);
  2356. }
  2357. if (strcmp(id, "browser_source") == 0) {
  2358. BrowserToolbar *c =
  2359. new BrowserToolbar(ui->emptySpace, source);
  2360. ui->emptySpace->layout()->addWidget(c);
  2361. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2362. strcmp(id, "wasapi_output_capture") == 0 ||
  2363. strcmp(id, "coreaudio_input_capture") == 0 ||
  2364. strcmp(id, "coreaudio_output_capture") == 0 ||
  2365. strcmp(id, "pulse_input_capture") == 0 ||
  2366. strcmp(id, "pulse_output_capture") == 0 ||
  2367. strcmp(id, "alsa_input_capture") == 0) {
  2368. AudioCaptureToolbar *c =
  2369. new AudioCaptureToolbar(ui->emptySpace, source);
  2370. c->Init();
  2371. ui->emptySpace->layout()->addWidget(c);
  2372. } else if (strcmp(id, "window_capture") == 0 ||
  2373. strcmp(id, "xcomposite_input") == 0) {
  2374. WindowCaptureToolbar *c = new WindowCaptureToolbar(
  2375. ui->emptySpace, source);
  2376. c->Init();
  2377. ui->emptySpace->layout()->addWidget(c);
  2378. } else if (strcmp(id, "monitor_capture") == 0 ||
  2379. strcmp(id, "display_capture") == 0 ||
  2380. strcmp(id, "xshm_input") == 0) {
  2381. DisplayCaptureToolbar *c = new DisplayCaptureToolbar(
  2382. ui->emptySpace, source);
  2383. c->Init();
  2384. ui->emptySpace->layout()->addWidget(c);
  2385. } else if (strcmp(id, "dshow_input") == 0 ||
  2386. strcmp(id, "av_capture_input") == 0 ||
  2387. strcmp(id, "v4l2_input") == 0) {
  2388. DeviceCaptureToolbar *c = new DeviceCaptureToolbar(
  2389. ui->emptySpace, source);
  2390. c->Init();
  2391. ui->emptySpace->layout()->addWidget(c);
  2392. } else if (strcmp(id, "game_capture") == 0) {
  2393. GameCaptureToolbar *c =
  2394. new GameCaptureToolbar(ui->emptySpace, source);
  2395. ui->emptySpace->layout()->addWidget(c);
  2396. } else if (strcmp(id, "image_source") == 0) {
  2397. ImageSourceToolbar *c =
  2398. new ImageSourceToolbar(ui->emptySpace, source);
  2399. ui->emptySpace->layout()->addWidget(c);
  2400. } else if (strcmp(id, "color_source") == 0) {
  2401. ColorSourceToolbar *c =
  2402. new ColorSourceToolbar(ui->emptySpace, source);
  2403. ui->emptySpace->layout()->addWidget(c);
  2404. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2405. strcmp(id, "text_gdiplus") == 0) {
  2406. TextSourceToolbar *c =
  2407. new TextSourceToolbar(ui->emptySpace, source);
  2408. ui->emptySpace->layout()->addWidget(c);
  2409. }
  2410. const char *name = obs_source_get_name(source);
  2411. ui->contextSourceLabel->setText(name);
  2412. ui->sourceFiltersButton->setEnabled(true);
  2413. ui->sourcePropertiesButton->setEnabled(true);
  2414. } else {
  2415. ui->contextSourceLabel->setText(
  2416. QTStr("ContextBar.NoSelectedSource"));
  2417. ui->sourceFiltersButton->setEnabled(false);
  2418. ui->sourcePropertiesButton->setEnabled(false);
  2419. }
  2420. }
  2421. static inline bool SourceMixerHidden(obs_source_t *source)
  2422. {
  2423. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2424. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2425. obs_data_release(priv_settings);
  2426. return hidden;
  2427. }
  2428. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2429. {
  2430. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2431. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2432. obs_data_release(priv_settings);
  2433. }
  2434. void OBSBasic::GetAudioSourceFilters()
  2435. {
  2436. QAction *action = reinterpret_cast<QAction *>(sender());
  2437. VolControl *vol = action->property("volControl").value<VolControl *>();
  2438. obs_source_t *source = vol->GetSource();
  2439. CreateFiltersWindow(source);
  2440. }
  2441. void OBSBasic::GetAudioSourceProperties()
  2442. {
  2443. QAction *action = reinterpret_cast<QAction *>(sender());
  2444. VolControl *vol = action->property("volControl").value<VolControl *>();
  2445. obs_source_t *source = vol->GetSource();
  2446. CreatePropertiesWindow(source);
  2447. }
  2448. void OBSBasic::HideAudioControl()
  2449. {
  2450. QAction *action = reinterpret_cast<QAction *>(sender());
  2451. VolControl *vol = action->property("volControl").value<VolControl *>();
  2452. obs_source_t *source = vol->GetSource();
  2453. if (!SourceMixerHidden(source)) {
  2454. SetSourceMixerHidden(source, true);
  2455. DeactivateAudioSource(source);
  2456. }
  2457. }
  2458. void OBSBasic::UnhideAllAudioControls()
  2459. {
  2460. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2461. {
  2462. if (!obs_source_active(source))
  2463. return true;
  2464. if (!SourceMixerHidden(source))
  2465. return true;
  2466. SetSourceMixerHidden(source, false);
  2467. ActivateAudioSource(source);
  2468. return true;
  2469. };
  2470. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2471. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2472. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2473. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2474. }
  2475. void OBSBasic::ToggleHideMixer()
  2476. {
  2477. OBSSceneItem item = GetCurrentSceneItem();
  2478. OBSSource source = obs_sceneitem_get_source(item);
  2479. if (!SourceMixerHidden(source)) {
  2480. SetSourceMixerHidden(source, true);
  2481. DeactivateAudioSource(source);
  2482. } else {
  2483. SetSourceMixerHidden(source, false);
  2484. ActivateAudioSource(source);
  2485. }
  2486. }
  2487. void OBSBasic::MixerRenameSource()
  2488. {
  2489. QAction *action = reinterpret_cast<QAction *>(sender());
  2490. VolControl *vol = action->property("volControl").value<VolControl *>();
  2491. OBSSource source = vol->GetSource();
  2492. const char *prevName = obs_source_get_name(source);
  2493. for (;;) {
  2494. string name;
  2495. bool accepted = NameDialog::AskForName(
  2496. this, QTStr("Basic.Main.MixerRename.Title"),
  2497. QTStr("Basic.Main.MixerRename.Text"), name,
  2498. QT_UTF8(prevName));
  2499. if (!accepted)
  2500. return;
  2501. if (name.empty()) {
  2502. OBSMessageBox::warning(this,
  2503. QTStr("NoNameEntered.Title"),
  2504. QTStr("NoNameEntered.Text"));
  2505. continue;
  2506. }
  2507. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2508. obs_source_release(sourceTest);
  2509. if (sourceTest) {
  2510. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2511. QTStr("NameExists.Text"));
  2512. continue;
  2513. }
  2514. obs_source_set_name(source, name.c_str());
  2515. break;
  2516. }
  2517. }
  2518. static inline bool SourceVolumeLocked(obs_source_t *source)
  2519. {
  2520. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2521. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2522. obs_data_release(priv_settings);
  2523. return lock;
  2524. }
  2525. void OBSBasic::LockVolumeControl(bool lock)
  2526. {
  2527. QAction *action = reinterpret_cast<QAction *>(sender());
  2528. VolControl *vol = action->property("volControl").value<VolControl *>();
  2529. obs_source_t *source = vol->GetSource();
  2530. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2531. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2532. obs_data_release(priv_settings);
  2533. vol->EnableSlider(!lock);
  2534. }
  2535. void OBSBasic::VolControlContextMenu()
  2536. {
  2537. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2538. /* ------------------- */
  2539. QAction lockAction(QTStr("LockVolume"), this);
  2540. lockAction.setCheckable(true);
  2541. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2542. QAction hideAction(QTStr("Hide"), this);
  2543. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2544. QAction mixerRenameAction(QTStr("Rename"), this);
  2545. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2546. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2547. QAction filtersAction(QTStr("Filters"), this);
  2548. QAction propertiesAction(QTStr("Properties"), this);
  2549. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2550. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2551. toggleControlLayoutAction.setCheckable(true);
  2552. toggleControlLayoutAction.setChecked(config_get_bool(
  2553. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2554. /* ------------------- */
  2555. connect(&hideAction, &QAction::triggered, this,
  2556. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2557. connect(&unhideAllAction, &QAction::triggered, this,
  2558. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2559. connect(&lockAction, &QAction::toggled, this,
  2560. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2561. connect(&mixerRenameAction, &QAction::triggered, this,
  2562. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2563. connect(&copyFiltersAction, &QAction::triggered, this,
  2564. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2565. connect(&pasteFiltersAction, &QAction::triggered, this,
  2566. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2567. connect(&filtersAction, &QAction::triggered, this,
  2568. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2569. connect(&propertiesAction, &QAction::triggered, this,
  2570. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2571. connect(&advPropAction, &QAction::triggered, this,
  2572. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2573. Qt::DirectConnection);
  2574. /* ------------------- */
  2575. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2576. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2577. /* ------------------- */
  2578. hideAction.setProperty("volControl",
  2579. QVariant::fromValue<VolControl *>(vol));
  2580. lockAction.setProperty("volControl",
  2581. QVariant::fromValue<VolControl *>(vol));
  2582. mixerRenameAction.setProperty("volControl",
  2583. QVariant::fromValue<VolControl *>(vol));
  2584. copyFiltersAction.setProperty("volControl",
  2585. QVariant::fromValue<VolControl *>(vol));
  2586. pasteFiltersAction.setProperty("volControl",
  2587. QVariant::fromValue<VolControl *>(vol));
  2588. filtersAction.setProperty("volControl",
  2589. QVariant::fromValue<VolControl *>(vol));
  2590. propertiesAction.setProperty("volControl",
  2591. QVariant::fromValue<VolControl *>(vol));
  2592. /* ------------------- */
  2593. if (copyFiltersString == nullptr)
  2594. pasteFiltersAction.setEnabled(false);
  2595. else
  2596. pasteFiltersAction.setEnabled(true);
  2597. QMenu popup;
  2598. popup.addAction(&lockAction);
  2599. popup.addSeparator();
  2600. popup.addAction(&unhideAllAction);
  2601. popup.addAction(&hideAction);
  2602. popup.addAction(&mixerRenameAction);
  2603. popup.addSeparator();
  2604. popup.addAction(&copyFiltersAction);
  2605. popup.addAction(&pasteFiltersAction);
  2606. popup.addSeparator();
  2607. popup.addAction(&toggleControlLayoutAction);
  2608. popup.addSeparator();
  2609. popup.addAction(&filtersAction);
  2610. popup.addAction(&propertiesAction);
  2611. popup.addAction(&advPropAction);
  2612. popup.exec(QCursor::pos());
  2613. }
  2614. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2615. {
  2616. StackedMixerAreaContextMenuRequested();
  2617. }
  2618. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2619. {
  2620. StackedMixerAreaContextMenuRequested();
  2621. }
  2622. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2623. {
  2624. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2625. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2626. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2627. toggleControlLayoutAction.setCheckable(true);
  2628. toggleControlLayoutAction.setChecked(config_get_bool(
  2629. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2630. /* ------------------- */
  2631. connect(&unhideAllAction, &QAction::triggered, this,
  2632. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2633. connect(&advPropAction, &QAction::triggered, this,
  2634. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2635. Qt::DirectConnection);
  2636. /* ------------------- */
  2637. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2638. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2639. /* ------------------- */
  2640. QMenu popup;
  2641. popup.addAction(&unhideAllAction);
  2642. popup.addSeparator();
  2643. popup.addAction(&toggleControlLayoutAction);
  2644. popup.addSeparator();
  2645. popup.addAction(&advPropAction);
  2646. popup.exec(QCursor::pos());
  2647. }
  2648. void OBSBasic::ToggleMixerLayout(bool vertical)
  2649. {
  2650. if (vertical) {
  2651. ui->stackedMixerArea->setMinimumSize(180, 220);
  2652. ui->stackedMixerArea->setCurrentIndex(1);
  2653. } else {
  2654. ui->stackedMixerArea->setMinimumSize(220, 0);
  2655. ui->stackedMixerArea->setCurrentIndex(0);
  2656. }
  2657. }
  2658. void OBSBasic::ToggleVolControlLayout()
  2659. {
  2660. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2661. "VerticalVolControl");
  2662. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2663. vertical);
  2664. ToggleMixerLayout(vertical);
  2665. // We need to store it so we can delete current and then add
  2666. // at the right order
  2667. vector<OBSSource> sources;
  2668. for (size_t i = 0; i != volumes.size(); i++)
  2669. sources.emplace_back(volumes[i]->GetSource());
  2670. ClearVolumeControls();
  2671. for (const auto &source : sources)
  2672. ActivateAudioSource(source);
  2673. }
  2674. void OBSBasic::ActivateAudioSource(OBSSource source)
  2675. {
  2676. if (SourceMixerHidden(source))
  2677. return;
  2678. if (!obs_source_audio_active(source))
  2679. return;
  2680. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2681. "VerticalVolControl");
  2682. VolControl *vol = new VolControl(source, true, vertical);
  2683. vol->EnableSlider(!SourceVolumeLocked(source));
  2684. double meterDecayRate =
  2685. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2686. vol->SetMeterDecayRate(meterDecayRate);
  2687. uint32_t peakMeterTypeIdx =
  2688. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2689. enum obs_peak_meter_type peakMeterType;
  2690. switch (peakMeterTypeIdx) {
  2691. case 0:
  2692. peakMeterType = SAMPLE_PEAK_METER;
  2693. break;
  2694. case 1:
  2695. peakMeterType = TRUE_PEAK_METER;
  2696. break;
  2697. default:
  2698. peakMeterType = SAMPLE_PEAK_METER;
  2699. break;
  2700. }
  2701. vol->setPeakMeterType(peakMeterType);
  2702. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2703. connect(vol, &QWidget::customContextMenuRequested, this,
  2704. &OBSBasic::VolControlContextMenu);
  2705. connect(vol, &VolControl::ConfigClicked, this,
  2706. &OBSBasic::VolControlContextMenu);
  2707. InsertQObjectByName(volumes, vol);
  2708. for (auto volume : volumes) {
  2709. if (vertical)
  2710. ui->vVolControlLayout->addWidget(volume);
  2711. else
  2712. ui->hVolControlLayout->addWidget(volume);
  2713. }
  2714. }
  2715. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2716. {
  2717. for (size_t i = 0; i < volumes.size(); i++) {
  2718. if (volumes[i]->GetSource() == source) {
  2719. delete volumes[i];
  2720. volumes.erase(volumes.begin() + i);
  2721. break;
  2722. }
  2723. }
  2724. }
  2725. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2726. {
  2727. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2728. !obs_source_is_group(source)) {
  2729. int count = ui->scenes->count();
  2730. if (count == 1) {
  2731. OBSMessageBox::information(this,
  2732. QTStr("FinalScene.Title"),
  2733. QTStr("FinalScene.Text"));
  2734. return false;
  2735. }
  2736. }
  2737. const char *name = obs_source_get_name(source);
  2738. QString text = QTStr("ConfirmRemove.Text");
  2739. text.replace("$1", QT_UTF8(name));
  2740. QMessageBox remove_source(this);
  2741. remove_source.setText(text);
  2742. QPushButton *Yes =
  2743. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2744. remove_source.setDefaultButton(Yes);
  2745. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2746. remove_source.setIcon(QMessageBox::Question);
  2747. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2748. remove_source.exec();
  2749. return Yes == remove_source.clickedButton();
  2750. }
  2751. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2752. #ifdef UPDATE_SPARKLE
  2753. void init_sparkle_updater(bool update_to_undeployed);
  2754. void trigger_sparkle_update();
  2755. #endif
  2756. void OBSBasic::TimedCheckForUpdates()
  2757. {
  2758. if (App()->IsUpdaterDisabled())
  2759. return;
  2760. if (!config_get_bool(App()->GlobalConfig(), "General",
  2761. "EnableAutoUpdates"))
  2762. return;
  2763. #ifdef UPDATE_SPARKLE
  2764. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2765. "UpdateToUndeployed"));
  2766. #elif _WIN32
  2767. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2768. "LastUpdateCheck");
  2769. uint32_t lastVersion =
  2770. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2771. if (lastVersion < LIBOBS_API_VER) {
  2772. lastUpdate = 0;
  2773. config_set_int(App()->GlobalConfig(), "General",
  2774. "LastUpdateCheck", 0);
  2775. }
  2776. long long t = (long long)time(nullptr);
  2777. long long secs = t - lastUpdate;
  2778. if (secs > UPDATE_CHECK_INTERVAL)
  2779. CheckForUpdates(false);
  2780. #endif
  2781. }
  2782. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2783. {
  2784. #ifdef UPDATE_SPARKLE
  2785. trigger_sparkle_update();
  2786. #elif _WIN32
  2787. ui->actionCheckForUpdates->setEnabled(false);
  2788. if (updateCheckThread && updateCheckThread->isRunning())
  2789. return;
  2790. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2791. updateCheckThread->start();
  2792. #endif
  2793. UNUSED_PARAMETER(manualUpdate);
  2794. }
  2795. void OBSBasic::updateCheckFinished()
  2796. {
  2797. ui->actionCheckForUpdates->setEnabled(true);
  2798. }
  2799. void OBSBasic::DuplicateSelectedScene()
  2800. {
  2801. OBSScene curScene = GetCurrentScene();
  2802. if (!curScene)
  2803. return;
  2804. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2805. QString format{obs_source_get_name(curSceneSource)};
  2806. format += " %1";
  2807. int i = 2;
  2808. QString placeHolderText = format.arg(i);
  2809. obs_source_t *source = nullptr;
  2810. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2811. obs_source_release(source);
  2812. placeHolderText = format.arg(++i);
  2813. }
  2814. for (;;) {
  2815. string name;
  2816. bool accepted = NameDialog::AskForName(
  2817. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2818. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2819. placeHolderText);
  2820. if (!accepted)
  2821. return;
  2822. if (name.empty()) {
  2823. OBSMessageBox::warning(this,
  2824. QTStr("NoNameEntered.Title"),
  2825. QTStr("NoNameEntered.Text"));
  2826. continue;
  2827. }
  2828. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2829. if (source) {
  2830. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2831. QTStr("NameExists.Text"));
  2832. obs_source_release(source);
  2833. continue;
  2834. }
  2835. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2836. OBS_SCENE_DUP_REFS);
  2837. source = obs_scene_get_source(scene);
  2838. SetCurrentScene(source, true);
  2839. obs_scene_release(scene);
  2840. break;
  2841. }
  2842. }
  2843. void OBSBasic::RemoveSelectedScene()
  2844. {
  2845. OBSScene scene = GetCurrentScene();
  2846. if (scene) {
  2847. obs_source_t *source = obs_scene_get_source(scene);
  2848. if (QueryRemoveSource(source)) {
  2849. obs_source_remove(source);
  2850. if (api)
  2851. api->on_event(
  2852. OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2853. }
  2854. }
  2855. }
  2856. void OBSBasic::RemoveSelectedSceneItem()
  2857. {
  2858. OBSSceneItem item = GetCurrentSceneItem();
  2859. if (item) {
  2860. obs_source_t *source = obs_sceneitem_get_source(item);
  2861. if (QueryRemoveSource(source))
  2862. obs_sceneitem_remove(item);
  2863. }
  2864. }
  2865. void OBSBasic::ReorderSources(OBSScene scene)
  2866. {
  2867. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2868. return;
  2869. ui->sources->ReorderItems();
  2870. SaveProject();
  2871. }
  2872. void OBSBasic::RefreshSources(OBSScene scene)
  2873. {
  2874. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2875. return;
  2876. ui->sources->RefreshItems();
  2877. SaveProject();
  2878. }
  2879. /* OBS Callbacks */
  2880. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2881. {
  2882. OBSBasic *window = static_cast<OBSBasic *>(data);
  2883. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2884. QMetaObject::invokeMethod(window, "ReorderSources",
  2885. Q_ARG(OBSScene, OBSScene(scene)));
  2886. }
  2887. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  2888. {
  2889. OBSBasic *window = static_cast<OBSBasic *>(data);
  2890. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2891. QMetaObject::invokeMethod(window, "RefreshSources",
  2892. Q_ARG(OBSScene, OBSScene(scene)));
  2893. }
  2894. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2895. {
  2896. OBSBasic *window = static_cast<OBSBasic *>(data);
  2897. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2898. QMetaObject::invokeMethod(window, "AddSceneItem",
  2899. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2900. }
  2901. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2902. {
  2903. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2904. if (obs_scene_from_source(source) != NULL)
  2905. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2906. "AddScene", WaitConnection(),
  2907. Q_ARG(OBSSource, OBSSource(source)));
  2908. }
  2909. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2910. {
  2911. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2912. if (obs_scene_from_source(source) != NULL)
  2913. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2914. "RemoveScene",
  2915. Q_ARG(OBSSource, OBSSource(source)));
  2916. }
  2917. void OBSBasic::SourceActivated(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. "ActivateAudioSource",
  2924. Q_ARG(OBSSource, OBSSource(source)));
  2925. }
  2926. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2927. {
  2928. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2929. uint32_t flags = obs_source_get_output_flags(source);
  2930. if (flags & OBS_SOURCE_AUDIO)
  2931. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2932. "DeactivateAudioSource",
  2933. Q_ARG(OBSSource, OBSSource(source)));
  2934. }
  2935. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  2936. {
  2937. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2938. if (obs_source_active(source))
  2939. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2940. "ActivateAudioSource",
  2941. Q_ARG(OBSSource, OBSSource(source)));
  2942. }
  2943. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  2944. {
  2945. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2946. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2947. "DeactivateAudioSource",
  2948. Q_ARG(OBSSource, OBSSource(source)));
  2949. }
  2950. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2951. {
  2952. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2953. const char *newName = calldata_string(params, "new_name");
  2954. const char *prevName = calldata_string(params, "prev_name");
  2955. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2956. "RenameSources", Q_ARG(OBSSource, source),
  2957. Q_ARG(QString, QT_UTF8(newName)),
  2958. Q_ARG(QString, QT_UTF8(prevName)));
  2959. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2960. }
  2961. void OBSBasic::DrawBackdrop(float cx, float cy)
  2962. {
  2963. if (!box)
  2964. return;
  2965. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  2966. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2967. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2968. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2969. vec4 colorVal;
  2970. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2971. gs_effect_set_vec4(color, &colorVal);
  2972. gs_technique_begin(tech);
  2973. gs_technique_begin_pass(tech, 0);
  2974. gs_matrix_push();
  2975. gs_matrix_identity();
  2976. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2977. gs_load_vertexbuffer(box);
  2978. gs_draw(GS_TRISTRIP, 0, 0);
  2979. gs_matrix_pop();
  2980. gs_technique_end_pass(tech);
  2981. gs_technique_end(tech);
  2982. gs_load_vertexbuffer(nullptr);
  2983. GS_DEBUG_MARKER_END();
  2984. }
  2985. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2986. {
  2987. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  2988. OBSBasic *window = static_cast<OBSBasic *>(data);
  2989. obs_video_info ovi;
  2990. obs_get_video_info(&ovi);
  2991. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2992. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2993. gs_viewport_push();
  2994. gs_projection_push();
  2995. obs_display_t *display = window->ui->preview->GetDisplay();
  2996. uint32_t width, height;
  2997. obs_display_size(display, &width, &height);
  2998. float right = float(width) - window->previewX;
  2999. float bottom = float(height) - window->previewY;
  3000. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3001. 100.0f);
  3002. window->ui->preview->DrawOverflow();
  3003. /* --------------------------------------- */
  3004. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3005. -100.0f, 100.0f);
  3006. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3007. window->previewCY);
  3008. if (window->IsPreviewProgramMode()) {
  3009. window->DrawBackdrop(float(ovi.base_width),
  3010. float(ovi.base_height));
  3011. OBSScene scene = window->GetCurrentScene();
  3012. obs_source_t *source = obs_scene_get_source(scene);
  3013. if (source)
  3014. obs_source_video_render(source);
  3015. } else {
  3016. obs_render_main_texture_src_color_only();
  3017. }
  3018. gs_load_vertexbuffer(nullptr);
  3019. /* --------------------------------------- */
  3020. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3021. 100.0f);
  3022. gs_reset_viewport();
  3023. window->ui->preview->DrawSceneEditing();
  3024. /* --------------------------------------- */
  3025. gs_projection_pop();
  3026. gs_viewport_pop();
  3027. GS_DEBUG_MARKER_END();
  3028. UNUSED_PARAMETER(cx);
  3029. UNUSED_PARAMETER(cy);
  3030. }
  3031. /* Main class functions */
  3032. obs_service_t *OBSBasic::GetService()
  3033. {
  3034. if (!service) {
  3035. service =
  3036. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3037. obs_service_release(service);
  3038. }
  3039. return service;
  3040. }
  3041. void OBSBasic::SetService(obs_service_t *newService)
  3042. {
  3043. if (newService)
  3044. service = newService;
  3045. }
  3046. int OBSBasic::GetTransitionDuration()
  3047. {
  3048. return ui->transitionDuration->value();
  3049. }
  3050. bool OBSBasic::StreamingActive() const
  3051. {
  3052. if (!outputHandler)
  3053. return false;
  3054. return outputHandler->StreamingActive();
  3055. }
  3056. bool OBSBasic::Active() const
  3057. {
  3058. if (!outputHandler)
  3059. return false;
  3060. return outputHandler->Active();
  3061. }
  3062. #ifdef _WIN32
  3063. #define IS_WIN32 1
  3064. #else
  3065. #define IS_WIN32 0
  3066. #endif
  3067. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3068. {
  3069. return obs_reset_video(ovi);
  3070. }
  3071. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3072. {
  3073. const char *scaleTypeStr =
  3074. config_get_string(basicConfig, "Video", "ScaleType");
  3075. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3076. return OBS_SCALE_BILINEAR;
  3077. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3078. return OBS_SCALE_LANCZOS;
  3079. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3080. return OBS_SCALE_AREA;
  3081. else
  3082. return OBS_SCALE_BICUBIC;
  3083. }
  3084. static inline enum video_format GetVideoFormatFromName(const char *name)
  3085. {
  3086. if (astrcmpi(name, "I420") == 0)
  3087. return VIDEO_FORMAT_I420;
  3088. else if (astrcmpi(name, "NV12") == 0)
  3089. return VIDEO_FORMAT_NV12;
  3090. else if (astrcmpi(name, "I444") == 0)
  3091. return VIDEO_FORMAT_I444;
  3092. #if 0 //currently unsupported
  3093. else if (astrcmpi(name, "YVYU") == 0)
  3094. return VIDEO_FORMAT_YVYU;
  3095. else if (astrcmpi(name, "YUY2") == 0)
  3096. return VIDEO_FORMAT_YUY2;
  3097. else if (astrcmpi(name, "UYVY") == 0)
  3098. return VIDEO_FORMAT_UYVY;
  3099. #endif
  3100. else
  3101. return VIDEO_FORMAT_RGBA;
  3102. }
  3103. void OBSBasic::ResetUI()
  3104. {
  3105. bool studioPortraitLayout = config_get_bool(
  3106. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3107. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3108. "StudioModeLabels");
  3109. if (studioPortraitLayout)
  3110. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  3111. else
  3112. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3113. if (previewProgramMode)
  3114. ui->previewLabel->setHidden(!labels);
  3115. if (programLabel)
  3116. programLabel->setHidden(!labels);
  3117. }
  3118. int OBSBasic::ResetVideo()
  3119. {
  3120. if (outputHandler && outputHandler->Active())
  3121. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3122. ProfileScope("OBSBasic::ResetVideo");
  3123. struct obs_video_info ovi;
  3124. int ret;
  3125. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3126. const char *colorFormat =
  3127. config_get_string(basicConfig, "Video", "ColorFormat");
  3128. const char *colorSpace =
  3129. config_get_string(basicConfig, "Video", "ColorSpace");
  3130. const char *colorRange =
  3131. config_get_string(basicConfig, "Video", "ColorRange");
  3132. ovi.graphics_module = App()->GetRenderModule();
  3133. ovi.base_width =
  3134. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3135. ovi.base_height =
  3136. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3137. ovi.output_width =
  3138. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3139. ovi.output_height =
  3140. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3141. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3142. ovi.colorspace = astrcmpi(colorSpace, "601") == 0
  3143. ? VIDEO_CS_601
  3144. : (astrcmpi(colorSpace, "709") == 0
  3145. ? VIDEO_CS_709
  3146. : VIDEO_CS_SRGB);
  3147. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3148. : VIDEO_RANGE_PARTIAL;
  3149. ovi.adapter =
  3150. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3151. ovi.gpu_conversion = true;
  3152. ovi.scale_type = GetScaleType(basicConfig);
  3153. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3154. ovi.base_width = 1920;
  3155. ovi.base_height = 1080;
  3156. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3157. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3158. }
  3159. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3160. ovi.output_width = ovi.base_width;
  3161. ovi.output_height = ovi.base_height;
  3162. config_set_uint(basicConfig, "Video", "OutputCX",
  3163. ovi.base_width);
  3164. config_set_uint(basicConfig, "Video", "OutputCY",
  3165. ovi.base_height);
  3166. }
  3167. ret = AttemptToResetVideo(&ovi);
  3168. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3169. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3170. blog(LOG_WARNING, "Tried to reset when "
  3171. "already active");
  3172. return ret;
  3173. }
  3174. /* Try OpenGL if DirectX fails on windows */
  3175. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3176. blog(LOG_WARNING,
  3177. "Failed to initialize obs video (%d) "
  3178. "with graphics_module='%s', retrying "
  3179. "with graphics_module='%s'",
  3180. ret, ovi.graphics_module, DL_OPENGL);
  3181. ovi.graphics_module = DL_OPENGL;
  3182. ret = AttemptToResetVideo(&ovi);
  3183. }
  3184. } else if (ret == OBS_VIDEO_SUCCESS) {
  3185. ResizePreview(ovi.base_width, ovi.base_height);
  3186. if (program)
  3187. ResizeProgram(ovi.base_width, ovi.base_height);
  3188. }
  3189. if (ret == OBS_VIDEO_SUCCESS) {
  3190. OBSBasicStats::InitializeValues();
  3191. OBSProjector::UpdateMultiviewProjectors();
  3192. }
  3193. return ret;
  3194. }
  3195. bool OBSBasic::ResetAudio()
  3196. {
  3197. ProfileScope("OBSBasic::ResetAudio");
  3198. struct obs_audio_info ai;
  3199. ai.samples_per_sec =
  3200. config_get_uint(basicConfig, "Audio", "SampleRate");
  3201. const char *channelSetupStr =
  3202. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3203. if (strcmp(channelSetupStr, "Mono") == 0)
  3204. ai.speakers = SPEAKERS_MONO;
  3205. else if (strcmp(channelSetupStr, "2.1") == 0)
  3206. ai.speakers = SPEAKERS_2POINT1;
  3207. else if (strcmp(channelSetupStr, "4.0") == 0)
  3208. ai.speakers = SPEAKERS_4POINT0;
  3209. else if (strcmp(channelSetupStr, "4.1") == 0)
  3210. ai.speakers = SPEAKERS_4POINT1;
  3211. else if (strcmp(channelSetupStr, "5.1") == 0)
  3212. ai.speakers = SPEAKERS_5POINT1;
  3213. else if (strcmp(channelSetupStr, "7.1") == 0)
  3214. ai.speakers = SPEAKERS_7POINT1;
  3215. else
  3216. ai.speakers = SPEAKERS_STEREO;
  3217. return obs_reset_audio(&ai);
  3218. }
  3219. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3220. const char *deviceDesc, int channel)
  3221. {
  3222. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3223. obs_source_t *source;
  3224. obs_data_t *settings;
  3225. source = obs_get_output_source(channel);
  3226. if (source) {
  3227. if (disable) {
  3228. obs_set_output_source(channel, nullptr);
  3229. } else {
  3230. settings = obs_source_get_settings(source);
  3231. const char *oldId =
  3232. obs_data_get_string(settings, "device_id");
  3233. if (strcmp(oldId, deviceId) != 0) {
  3234. obs_data_set_string(settings, "device_id",
  3235. deviceId);
  3236. obs_source_update(source, settings);
  3237. }
  3238. obs_data_release(settings);
  3239. }
  3240. obs_source_release(source);
  3241. } else if (!disable) {
  3242. settings = obs_data_create();
  3243. obs_data_set_string(settings, "device_id", deviceId);
  3244. source = obs_source_create(sourceId, deviceDesc, settings,
  3245. nullptr);
  3246. obs_data_release(settings);
  3247. obs_set_output_source(channel, source);
  3248. obs_source_release(source);
  3249. }
  3250. }
  3251. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3252. {
  3253. QSize targetSize;
  3254. bool isFixedScaling;
  3255. obs_video_info ovi;
  3256. /* resize preview panel to fix to the top section of the window */
  3257. targetSize = GetPixelSize(ui->preview);
  3258. isFixedScaling = ui->preview->IsFixedScaling();
  3259. obs_get_video_info(&ovi);
  3260. if (isFixedScaling) {
  3261. previewScale = ui->preview->GetScalingAmount();
  3262. GetCenterPosFromFixedScale(
  3263. int(cx), int(cy),
  3264. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3265. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3266. previewY, previewScale);
  3267. previewX += ui->preview->GetScrollX();
  3268. previewY += ui->preview->GetScrollY();
  3269. } else {
  3270. GetScaleAndCenterPos(int(cx), int(cy),
  3271. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3272. targetSize.height() -
  3273. PREVIEW_EDGE_SIZE * 2,
  3274. previewX, previewY, previewScale);
  3275. }
  3276. previewX += float(PREVIEW_EDGE_SIZE);
  3277. previewY += float(PREVIEW_EDGE_SIZE);
  3278. }
  3279. void OBSBasic::CloseDialogs()
  3280. {
  3281. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3282. if (!childDialogs.isEmpty()) {
  3283. for (int i = 0; i < childDialogs.size(); ++i) {
  3284. childDialogs.at(i)->close();
  3285. }
  3286. }
  3287. if (!stats.isNull())
  3288. stats->close(); //call close to save Stats geometry
  3289. if (!remux.isNull())
  3290. remux->close();
  3291. }
  3292. void OBSBasic::EnumDialogs()
  3293. {
  3294. visDialogs.clear();
  3295. modalDialogs.clear();
  3296. visMsgBoxes.clear();
  3297. /* fill list of Visible dialogs and Modal dialogs */
  3298. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3299. for (QDialog *dialog : dialogs) {
  3300. if (dialog->isVisible())
  3301. visDialogs.append(dialog);
  3302. if (dialog->isModal())
  3303. modalDialogs.append(dialog);
  3304. }
  3305. /* fill list of Visible message boxes */
  3306. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3307. for (QMessageBox *msgbox : msgBoxes) {
  3308. if (msgbox->isVisible())
  3309. visMsgBoxes.append(msgbox);
  3310. }
  3311. }
  3312. void OBSBasic::ClearProjectors()
  3313. {
  3314. for (size_t i = 0; i < projectors.size(); i++) {
  3315. if (projectors[i])
  3316. delete projectors[i];
  3317. }
  3318. projectors.clear();
  3319. }
  3320. void OBSBasic::ClearSceneData()
  3321. {
  3322. disableSaving++;
  3323. CloseDialogs();
  3324. ClearVolumeControls();
  3325. ClearListItems(ui->scenes);
  3326. ui->sources->Clear();
  3327. ClearQuickTransitions();
  3328. ui->transitions->clear();
  3329. ClearProjectors();
  3330. obs_set_output_source(0, nullptr);
  3331. obs_set_output_source(1, nullptr);
  3332. obs_set_output_source(2, nullptr);
  3333. obs_set_output_source(3, nullptr);
  3334. obs_set_output_source(4, nullptr);
  3335. obs_set_output_source(5, nullptr);
  3336. lastScene = nullptr;
  3337. swapScene = nullptr;
  3338. programScene = nullptr;
  3339. auto cb = [](void *unused, obs_source_t *source) {
  3340. obs_source_remove(source);
  3341. UNUSED_PARAMETER(unused);
  3342. return true;
  3343. };
  3344. obs_enum_scenes(cb, nullptr);
  3345. obs_enum_sources(cb, nullptr);
  3346. if (api)
  3347. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3348. disableSaving--;
  3349. blog(LOG_INFO, "All scene data cleared");
  3350. blog(LOG_INFO, "------------------------------------------------");
  3351. }
  3352. void OBSBasic::closeEvent(QCloseEvent *event)
  3353. {
  3354. /* Do not close window if inside of a temporary event loop because we
  3355. * could be inside of an Auth::LoadUI call. Keep trying once per
  3356. * second until we've exit any known sub-loops. */
  3357. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3358. QTimer::singleShot(1000, this, SLOT(close()));
  3359. event->ignore();
  3360. return;
  3361. }
  3362. if (isVisible())
  3363. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3364. "geometry",
  3365. saveGeometry().toBase64().constData());
  3366. if (outputHandler && outputHandler->Active()) {
  3367. SetShowing(true);
  3368. QMessageBox::StandardButton button = OBSMessageBox::question(
  3369. this, QTStr("ConfirmExit.Title"),
  3370. QTStr("ConfirmExit.Text"));
  3371. if (button == QMessageBox::No) {
  3372. event->ignore();
  3373. restart = false;
  3374. return;
  3375. }
  3376. }
  3377. QWidget::closeEvent(event);
  3378. if (!event->isAccepted())
  3379. return;
  3380. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3381. closing = true;
  3382. if (introCheckThread)
  3383. introCheckThread->wait();
  3384. if (whatsNewInitThread)
  3385. whatsNewInitThread->wait();
  3386. if (updateCheckThread)
  3387. updateCheckThread->wait();
  3388. if (logUploadThread)
  3389. logUploadThread->wait();
  3390. signalHandlers.clear();
  3391. Auth::Save();
  3392. SaveProjectNow();
  3393. auth.reset();
  3394. delete extraBrowsers;
  3395. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3396. saveState().toBase64().constData());
  3397. #ifdef BROWSER_AVAILABLE
  3398. SaveExtraBrowserDocks();
  3399. ClearExtraBrowserDocks();
  3400. #endif
  3401. if (api)
  3402. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3403. disableSaving++;
  3404. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3405. * sources, etc) so that all references are released before shutdown */
  3406. ClearSceneData();
  3407. App()->quit();
  3408. }
  3409. void OBSBasic::changeEvent(QEvent *event)
  3410. {
  3411. if (event->type() == QEvent::WindowStateChange) {
  3412. QWindowStateChangeEvent *stateEvent =
  3413. (QWindowStateChangeEvent *)event;
  3414. if (isMinimized()) {
  3415. if (trayIcon && trayIcon->isVisible() &&
  3416. sysTrayMinimizeToTray()) {
  3417. ToggleShowHide();
  3418. }
  3419. if (previewEnabled)
  3420. EnablePreviewDisplay(false);
  3421. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3422. isVisible()) {
  3423. if (previewEnabled)
  3424. EnablePreviewDisplay(true);
  3425. }
  3426. }
  3427. }
  3428. void OBSBasic::on_actionShow_Recordings_triggered()
  3429. {
  3430. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3431. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3432. const char *adv_path =
  3433. strcmp(type, "Standard")
  3434. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3435. : config_get_string(basicConfig, "AdvOut",
  3436. "RecFilePath");
  3437. const char *path = strcmp(mode, "Advanced")
  3438. ? config_get_string(basicConfig,
  3439. "SimpleOutput",
  3440. "FilePath")
  3441. : adv_path;
  3442. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3443. }
  3444. void OBSBasic::on_actionRemux_triggered()
  3445. {
  3446. if (!remux.isNull()) {
  3447. remux->show();
  3448. remux->raise();
  3449. return;
  3450. }
  3451. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3452. const char *path = strcmp(mode, "Advanced")
  3453. ? config_get_string(basicConfig,
  3454. "SimpleOutput",
  3455. "FilePath")
  3456. : config_get_string(basicConfig, "AdvOut",
  3457. "RecFilePath");
  3458. OBSRemux *remuxDlg;
  3459. remuxDlg = new OBSRemux(path, this);
  3460. remuxDlg->show();
  3461. remux = remuxDlg;
  3462. }
  3463. void OBSBasic::on_action_Settings_triggered()
  3464. {
  3465. static bool settings_already_executing = false;
  3466. /* Do not load settings window if inside of a temporary event loop
  3467. * because we could be inside of an Auth::LoadUI call. Keep trying
  3468. * once per second until we've exit any known sub-loops. */
  3469. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3470. QTimer::singleShot(1000, this,
  3471. SLOT(on_action_Settings_triggered()));
  3472. return;
  3473. }
  3474. if (settings_already_executing) {
  3475. return;
  3476. }
  3477. settings_already_executing = true;
  3478. {
  3479. OBSBasicSettings settings(this);
  3480. settings.exec();
  3481. }
  3482. SystemTray(false);
  3483. settings_already_executing = false;
  3484. if (restart) {
  3485. QMessageBox::StandardButton button = OBSMessageBox::question(
  3486. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3487. if (button == QMessageBox::Yes)
  3488. close();
  3489. else
  3490. restart = false;
  3491. }
  3492. }
  3493. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3494. {
  3495. if (advAudioWindow != nullptr) {
  3496. advAudioWindow->raise();
  3497. return;
  3498. }
  3499. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3500. "BasicWindow", "ShowSourceIcons");
  3501. advAudioWindow = new OBSBasicAdvAudio(this);
  3502. advAudioWindow->show();
  3503. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3504. advAudioWindow->SetIconsVisible(iconsVisible);
  3505. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3506. SLOT(on_advAudioProps_destroyed()));
  3507. }
  3508. void OBSBasic::on_advAudioProps_clicked()
  3509. {
  3510. on_actionAdvAudioProperties_triggered();
  3511. }
  3512. void OBSBasic::on_advAudioProps_destroyed()
  3513. {
  3514. advAudioWindow = nullptr;
  3515. }
  3516. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3517. QListWidgetItem *prev)
  3518. {
  3519. obs_source_t *source = NULL;
  3520. if (sceneChanging)
  3521. return;
  3522. if (current) {
  3523. obs_scene_t *scene;
  3524. scene = GetOBSRef<OBSScene>(current);
  3525. source = obs_scene_get_source(scene);
  3526. }
  3527. SetCurrentScene(source);
  3528. if (api)
  3529. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3530. UpdateContextBar();
  3531. UNUSED_PARAMETER(prev);
  3532. }
  3533. void OBSBasic::EditSceneName()
  3534. {
  3535. QListWidgetItem *item = ui->scenes->currentItem();
  3536. Qt::ItemFlags flags = item->flags();
  3537. item->setFlags(flags | Qt::ItemIsEditable);
  3538. ui->scenes->editItem(item);
  3539. item->setFlags(flags);
  3540. }
  3541. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3542. const char *slot)
  3543. {
  3544. QAction *action;
  3545. QList<QScreen *> screens = QGuiApplication::screens();
  3546. for (int i = 0; i < screens.size(); i++) {
  3547. QScreen *screen = screens[i];
  3548. QRect screenGeometry = screen->geometry();
  3549. QString name = "";
  3550. #ifdef _WIN32
  3551. QTextStream fullname(&name);
  3552. fullname << GetMonitorName(screen->name());
  3553. fullname << " (";
  3554. fullname << (i + 1);
  3555. fullname << ")";
  3556. #elif defined(__APPLE__)
  3557. name = screen->name();
  3558. #elif QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
  3559. name = screen->model().simplified();
  3560. if (name.length() > 1 && name.endsWith("-"))
  3561. name.chop(1);
  3562. #endif
  3563. name = name.simplified();
  3564. if (name.length() == 0) {
  3565. name = QString("%1 %2")
  3566. .arg(QTStr("Display"))
  3567. .arg(QString::number(i + 1));
  3568. }
  3569. QString str =
  3570. QString("%1: %2x%3 @ %4,%5")
  3571. .arg(name,
  3572. QString::number(screenGeometry.width()),
  3573. QString::number(screenGeometry.height()),
  3574. QString::number(screenGeometry.x()),
  3575. QString::number(screenGeometry.y()));
  3576. action = parent->addAction(str, target, slot);
  3577. action->setProperty("monitor", i);
  3578. }
  3579. }
  3580. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3581. {
  3582. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3583. QMenu popup(this);
  3584. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3585. popup.addAction(QTStr("Add"), this,
  3586. SLOT(on_actionAddScene_triggered()));
  3587. if (item) {
  3588. QAction *pasteFilters =
  3589. new QAction(QTStr("Paste.Filters"), this);
  3590. pasteFilters->setEnabled(copyFiltersString);
  3591. connect(pasteFilters, SIGNAL(triggered()), this,
  3592. SLOT(ScenePasteFilters()));
  3593. popup.addSeparator();
  3594. popup.addAction(QTStr("Duplicate"), this,
  3595. SLOT(DuplicateSelectedScene()));
  3596. popup.addAction(QTStr("Copy.Filters"), this,
  3597. SLOT(SceneCopyFilters()));
  3598. popup.addAction(pasteFilters);
  3599. popup.addSeparator();
  3600. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3601. popup.addAction(QTStr("Remove"), this,
  3602. SLOT(RemoveSelectedScene()));
  3603. popup.addSeparator();
  3604. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3605. SLOT(on_actionSceneUp_triggered()));
  3606. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3607. this, SLOT(on_actionSceneDown_triggered()));
  3608. order.addSeparator();
  3609. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3610. this, SLOT(MoveSceneToTop()));
  3611. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3612. this, SLOT(MoveSceneToBottom()));
  3613. popup.addMenu(&order);
  3614. popup.addSeparator();
  3615. delete sceneProjectorMenu;
  3616. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3617. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3618. SLOT(OpenSceneProjector()));
  3619. popup.addMenu(sceneProjectorMenu);
  3620. QAction *sceneWindow = popup.addAction(
  3621. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3622. popup.addAction(sceneWindow);
  3623. popup.addAction(QTStr("Screenshot.Scene"), this,
  3624. SLOT(ScreenshotScene()));
  3625. popup.addSeparator();
  3626. popup.addAction(QTStr("Filters"), this,
  3627. SLOT(OpenSceneFilters()));
  3628. popup.addSeparator();
  3629. delete perSceneTransitionMenu;
  3630. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3631. popup.addMenu(perSceneTransitionMenu);
  3632. /* ---------------------- */
  3633. QAction *multiviewAction =
  3634. popup.addAction(QTStr("ShowInMultiview"));
  3635. OBSSource source = GetCurrentSceneSource();
  3636. OBSData data = obs_source_get_private_settings(source);
  3637. obs_data_release(data);
  3638. obs_data_set_default_bool(data, "show_in_multiview", true);
  3639. bool show = obs_data_get_bool(data, "show_in_multiview");
  3640. multiviewAction->setCheckable(true);
  3641. multiviewAction->setChecked(show);
  3642. auto showInMultiview = [](OBSData data) {
  3643. bool show =
  3644. obs_data_get_bool(data, "show_in_multiview");
  3645. obs_data_set_bool(data, "show_in_multiview", !show);
  3646. OBSProjector::UpdateMultiviewProjectors();
  3647. };
  3648. connect(multiviewAction, &QAction::triggered,
  3649. std::bind(showInMultiview, data));
  3650. }
  3651. popup.addSeparator();
  3652. bool grid = ui->scenes->GetGridMode();
  3653. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  3654. : QTStr("Basic.Main.GridMode"),
  3655. this);
  3656. connect(gridAction, SIGNAL(triggered()), this,
  3657. SLOT(on_actionGridMode_triggered()));
  3658. popup.addAction(gridAction);
  3659. popup.exec(QCursor::pos());
  3660. }
  3661. void OBSBasic::on_actionGridMode_triggered()
  3662. {
  3663. bool gridMode = !ui->scenes->GetGridMode();
  3664. ui->scenes->SetGridMode(gridMode);
  3665. }
  3666. void OBSBasic::on_actionAddScene_triggered()
  3667. {
  3668. string name;
  3669. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3670. int i = 2;
  3671. QString placeHolderText = format.arg(i);
  3672. obs_source_t *source = nullptr;
  3673. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3674. obs_source_release(source);
  3675. placeHolderText = format.arg(++i);
  3676. }
  3677. bool accepted = NameDialog::AskForName(
  3678. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3679. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  3680. if (accepted) {
  3681. if (name.empty()) {
  3682. OBSMessageBox::warning(this,
  3683. QTStr("NoNameEntered.Title"),
  3684. QTStr("NoNameEntered.Text"));
  3685. on_actionAddScene_triggered();
  3686. return;
  3687. }
  3688. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3689. if (source) {
  3690. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3691. QTStr("NameExists.Text"));
  3692. obs_source_release(source);
  3693. on_actionAddScene_triggered();
  3694. return;
  3695. }
  3696. obs_scene_t *scene = obs_scene_create(name.c_str());
  3697. source = obs_scene_get_source(scene);
  3698. SetCurrentScene(source);
  3699. obs_scene_release(scene);
  3700. }
  3701. }
  3702. void OBSBasic::on_actionRemoveScene_triggered()
  3703. {
  3704. OBSScene scene = GetCurrentScene();
  3705. obs_source_t *source = obs_scene_get_source(scene);
  3706. if (source && QueryRemoveSource(source))
  3707. obs_source_remove(source);
  3708. }
  3709. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3710. {
  3711. int idx = ui->scenes->currentRow();
  3712. if (idx == -1 || idx == invalidIdx)
  3713. return;
  3714. sceneChanging = true;
  3715. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3716. if (!relative)
  3717. idx = 0;
  3718. ui->scenes->insertItem(idx + offset, item);
  3719. ui->scenes->setCurrentRow(idx + offset);
  3720. item->setSelected(true);
  3721. sceneChanging = false;
  3722. OBSProjector::UpdateMultiviewProjectors();
  3723. }
  3724. void OBSBasic::on_actionSceneUp_triggered()
  3725. {
  3726. ChangeSceneIndex(true, -1, 0);
  3727. }
  3728. void OBSBasic::on_actionSceneDown_triggered()
  3729. {
  3730. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3731. }
  3732. void OBSBasic::MoveSceneToTop()
  3733. {
  3734. ChangeSceneIndex(false, 0, 0);
  3735. }
  3736. void OBSBasic::MoveSceneToBottom()
  3737. {
  3738. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3739. ui->scenes->count() - 1);
  3740. }
  3741. void OBSBasic::EditSceneItemName()
  3742. {
  3743. int idx = GetTopSelectedSourceItem();
  3744. ui->sources->Edit(idx);
  3745. }
  3746. void OBSBasic::SetDeinterlacingMode()
  3747. {
  3748. QAction *action = reinterpret_cast<QAction *>(sender());
  3749. obs_deinterlace_mode mode =
  3750. (obs_deinterlace_mode)action->property("mode").toInt();
  3751. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3752. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3753. obs_source_set_deinterlace_mode(source, mode);
  3754. }
  3755. void OBSBasic::SetDeinterlacingOrder()
  3756. {
  3757. QAction *action = reinterpret_cast<QAction *>(sender());
  3758. obs_deinterlace_field_order order =
  3759. (obs_deinterlace_field_order)action->property("order").toInt();
  3760. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3761. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3762. obs_source_set_deinterlace_field_order(source, order);
  3763. }
  3764. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3765. {
  3766. obs_deinterlace_mode deinterlaceMode =
  3767. obs_source_get_deinterlace_mode(source);
  3768. obs_deinterlace_field_order deinterlaceOrder =
  3769. obs_source_get_deinterlace_field_order(source);
  3770. QAction *action;
  3771. #define ADD_MODE(name, mode) \
  3772. action = menu->addAction(QTStr("" name), this, \
  3773. SLOT(SetDeinterlacingMode())); \
  3774. action->setProperty("mode", (int)mode); \
  3775. action->setCheckable(true); \
  3776. action->setChecked(deinterlaceMode == mode);
  3777. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3778. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3779. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3780. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3781. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3782. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3783. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3784. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3785. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3786. #undef ADD_MODE
  3787. menu->addSeparator();
  3788. #define ADD_ORDER(name, order) \
  3789. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3790. SLOT(SetDeinterlacingOrder())); \
  3791. action->setProperty("order", (int)order); \
  3792. action->setCheckable(true); \
  3793. action->setChecked(deinterlaceOrder == order);
  3794. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3795. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3796. #undef ADD_ORDER
  3797. return menu;
  3798. }
  3799. void OBSBasic::SetScaleFilter()
  3800. {
  3801. QAction *action = reinterpret_cast<QAction *>(sender());
  3802. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3803. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3804. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3805. }
  3806. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3807. {
  3808. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3809. QAction *action;
  3810. #define ADD_MODE(name, mode) \
  3811. action = \
  3812. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  3813. action->setProperty("mode", (int)mode); \
  3814. action->setCheckable(true); \
  3815. action->setChecked(scaleFilter == mode);
  3816. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3817. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3818. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3819. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3820. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3821. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3822. #undef ADD_MODE
  3823. return menu;
  3824. }
  3825. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  3826. QWidgetAction *widgetAction,
  3827. ColorSelect *select,
  3828. obs_sceneitem_t *item)
  3829. {
  3830. QAction *action;
  3831. menu->setStyleSheet(QString(
  3832. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  3833. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  3834. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  3835. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  3836. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  3837. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  3838. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  3839. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3840. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3841. obs_data_release(privData);
  3842. obs_data_set_default_int(privData, "color-preset", 0);
  3843. int preset = obs_data_get_int(privData, "color-preset");
  3844. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  3845. action->setCheckable(true);
  3846. action->setProperty("bgColor", 0);
  3847. action->setChecked(preset == 0);
  3848. action = menu->addAction(QTStr("CustomColor"), this,
  3849. +SLOT(ColorChange()));
  3850. action->setCheckable(true);
  3851. action->setProperty("bgColor", 1);
  3852. action->setChecked(preset == 1);
  3853. menu->addSeparator();
  3854. widgetAction->setDefaultWidget(select);
  3855. for (int i = 1; i < 9; i++) {
  3856. stringstream button;
  3857. button << "preset" << i;
  3858. QPushButton *colorButton =
  3859. select->findChild<QPushButton *>(button.str().c_str());
  3860. if (preset == i + 1)
  3861. colorButton->setStyleSheet("border: 2px solid black");
  3862. colorButton->setProperty("bgColor", i);
  3863. select->connect(colorButton, SIGNAL(released()), this,
  3864. SLOT(ColorChange()));
  3865. }
  3866. menu->addAction(widgetAction);
  3867. return menu;
  3868. }
  3869. ColorSelect::ColorSelect(QWidget *parent)
  3870. : QWidget(parent), ui(new Ui::ColorSelect)
  3871. {
  3872. ui->setupUi(this);
  3873. }
  3874. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3875. {
  3876. QMenu popup(this);
  3877. delete previewProjectorSource;
  3878. delete sourceProjector;
  3879. delete scaleFilteringMenu;
  3880. delete colorMenu;
  3881. delete colorWidgetAction;
  3882. delete colorSelect;
  3883. delete deinterlaceMenu;
  3884. if (preview) {
  3885. QAction *action = popup.addAction(
  3886. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  3887. SLOT(TogglePreview()));
  3888. action->setCheckable(true);
  3889. action->setChecked(
  3890. obs_display_enabled(ui->preview->GetDisplay()));
  3891. if (IsPreviewProgramMode())
  3892. action->setEnabled(false);
  3893. popup.addAction(ui->actionLockPreview);
  3894. popup.addMenu(ui->scalingMenu);
  3895. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3896. AddProjectorMenuMonitors(previewProjectorSource, this,
  3897. SLOT(OpenPreviewProjector()));
  3898. popup.addMenu(previewProjectorSource);
  3899. QAction *previewWindow =
  3900. popup.addAction(QTStr("PreviewWindow"), this,
  3901. SLOT(OpenPreviewWindow()));
  3902. popup.addAction(previewWindow);
  3903. popup.addAction(QTStr("Screenshot.Preview"), this,
  3904. SLOT(ScreenshotScene()));
  3905. popup.addSeparator();
  3906. }
  3907. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3908. if (addSourceMenu)
  3909. popup.addMenu(addSourceMenu);
  3910. ui->actionCopyFilters->setEnabled(false);
  3911. ui->actionCopySource->setEnabled(false);
  3912. if (ui->sources->MultipleBaseSelected()) {
  3913. popup.addSeparator();
  3914. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  3915. SLOT(GroupSelectedItems()));
  3916. } else if (ui->sources->GroupsSelected()) {
  3917. popup.addSeparator();
  3918. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  3919. SLOT(UngroupSelectedGroups()));
  3920. }
  3921. popup.addSeparator();
  3922. popup.addAction(ui->actionCopySource);
  3923. popup.addAction(ui->actionPasteRef);
  3924. popup.addAction(ui->actionPasteDup);
  3925. popup.addSeparator();
  3926. popup.addSeparator();
  3927. popup.addAction(ui->actionCopyFilters);
  3928. popup.addAction(ui->actionPasteFilters);
  3929. popup.addSeparator();
  3930. if (idx != -1) {
  3931. if (addSourceMenu)
  3932. popup.addSeparator();
  3933. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3934. bool lock = obs_sceneitem_locked(sceneItem);
  3935. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3936. uint32_t flags = obs_source_get_output_flags(source);
  3937. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3938. OBS_SOURCE_ASYNC_VIDEO;
  3939. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  3940. QAction *action;
  3941. colorMenu = new QMenu(QTStr("ChangeBG"));
  3942. colorWidgetAction = new QWidgetAction(colorMenu);
  3943. colorSelect = new ColorSelect(colorMenu);
  3944. popup.addMenu(AddBackgroundColorMenu(
  3945. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  3946. popup.addAction(QTStr("Rename"), this,
  3947. SLOT(EditSceneItemName()));
  3948. popup.addAction(QTStr("Remove"), this,
  3949. SLOT(on_actionRemoveSource_triggered()));
  3950. popup.addSeparator();
  3951. popup.addMenu(ui->orderMenu);
  3952. popup.addMenu(ui->transformMenu);
  3953. ui->actionResetTransform->setEnabled(!lock);
  3954. ui->actionRotate90CW->setEnabled(!lock);
  3955. ui->actionRotate90CCW->setEnabled(!lock);
  3956. ui->actionRotate180->setEnabled(!lock);
  3957. ui->actionFlipHorizontal->setEnabled(!lock);
  3958. ui->actionFlipVertical->setEnabled(!lock);
  3959. ui->actionFitToScreen->setEnabled(!lock);
  3960. ui->actionStretchToScreen->setEnabled(!lock);
  3961. ui->actionCenterToScreen->setEnabled(!lock);
  3962. ui->actionVerticalCenter->setEnabled(!lock);
  3963. ui->actionHorizontalCenter->setEnabled(!lock);
  3964. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3965. AddProjectorMenuMonitors(sourceProjector, this,
  3966. SLOT(OpenSourceProjector()));
  3967. QAction *sourceWindow = popup.addAction(
  3968. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  3969. popup.addAction(sourceWindow);
  3970. popup.addSeparator();
  3971. if (hasAudio) {
  3972. QAction *actionHideMixer =
  3973. popup.addAction(QTStr("HideMixer"), this,
  3974. SLOT(ToggleHideMixer()));
  3975. actionHideMixer->setCheckable(true);
  3976. actionHideMixer->setChecked(SourceMixerHidden(source));
  3977. }
  3978. if (isAsyncVideo) {
  3979. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3980. popup.addMenu(
  3981. AddDeinterlacingMenu(deinterlaceMenu, source));
  3982. popup.addSeparator();
  3983. }
  3984. QAction *resizeOutput =
  3985. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  3986. SLOT(ResizeOutputSizeOfSource()));
  3987. int width = obs_source_get_width(source);
  3988. int height = obs_source_get_height(source);
  3989. resizeOutput->setEnabled(!obs_video_active());
  3990. if (width < 8 || height < 8)
  3991. resizeOutput->setEnabled(false);
  3992. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3993. popup.addMenu(
  3994. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3995. popup.addSeparator();
  3996. popup.addMenu(sourceProjector);
  3997. popup.addAction(sourceWindow);
  3998. popup.addAction(QTStr("Screenshot.Source"), this,
  3999. SLOT(ScreenshotSelectedSource()));
  4000. popup.addSeparator();
  4001. action = popup.addAction(QTStr("Interact"), this,
  4002. SLOT(on_actionInteract_triggered()));
  4003. action->setEnabled(obs_source_get_output_flags(source) &
  4004. OBS_SOURCE_INTERACTION);
  4005. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4006. popup.addAction(QTStr("Properties"), this,
  4007. SLOT(on_actionSourceProperties_triggered()));
  4008. ui->actionCopyFilters->setEnabled(true);
  4009. ui->actionCopySource->setEnabled(true);
  4010. } else {
  4011. ui->actionPasteFilters->setEnabled(false);
  4012. }
  4013. popup.exec(QCursor::pos());
  4014. }
  4015. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4016. {
  4017. if (ui->scenes->count()) {
  4018. QModelIndex idx = ui->sources->indexAt(pos);
  4019. CreateSourcePopupMenu(idx.row(), false);
  4020. }
  4021. }
  4022. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4023. {
  4024. if (!witem)
  4025. return;
  4026. if (IsPreviewProgramMode()) {
  4027. bool doubleClickSwitch =
  4028. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4029. "TransitionOnDoubleClick");
  4030. if (doubleClickSwitch)
  4031. TransitionClicked();
  4032. }
  4033. }
  4034. void OBSBasic::AddSource(const char *id)
  4035. {
  4036. if (id && *id) {
  4037. OBSBasicSourceSelect sourceSelect(this, id);
  4038. sourceSelect.exec();
  4039. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  4040. CreatePropertiesWindow(sourceSelect.newSource);
  4041. }
  4042. }
  4043. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4044. {
  4045. const char *unversioned_type;
  4046. const char *type;
  4047. bool foundValues = false;
  4048. bool foundDeprecated = false;
  4049. size_t idx = 0;
  4050. QMenu *popup = new QMenu(QTStr("Add"), this);
  4051. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4052. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4053. QList<QAction *> actions = menu->actions();
  4054. for (QAction *menuAction : actions) {
  4055. if (menuAction->text().compare(name) >= 0)
  4056. return menuAction;
  4057. }
  4058. return (QAction *)nullptr;
  4059. };
  4060. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4061. const char *name) {
  4062. QString qname = QT_UTF8(name);
  4063. QAction *popupItem = new QAction(qname, this);
  4064. popupItem->setData(QT_UTF8(type));
  4065. connect(popupItem, SIGNAL(triggered(bool)), this,
  4066. SLOT(AddSourceFromAction()));
  4067. QIcon icon;
  4068. if (strcmp(type, "scene") == 0)
  4069. icon = GetSceneIcon();
  4070. else
  4071. icon = GetSourceIcon(type);
  4072. popupItem->setIcon(icon);
  4073. QAction *after = getActionAfter(popup, qname);
  4074. popup->insertAction(after, popupItem);
  4075. };
  4076. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4077. const char *name = obs_source_get_display_name(type);
  4078. uint32_t caps = obs_get_source_output_flags(type);
  4079. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4080. continue;
  4081. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4082. addSource(popup, unversioned_type, name);
  4083. } else {
  4084. addSource(deprecated, unversioned_type, name);
  4085. foundDeprecated = true;
  4086. }
  4087. foundValues = true;
  4088. }
  4089. addSource(popup, "scene", Str("Basic.Scene"));
  4090. popup->addSeparator();
  4091. QAction *addGroup = new QAction(QTStr("Group"), this);
  4092. addGroup->setData(QT_UTF8("group"));
  4093. addGroup->setIcon(GetGroupIcon());
  4094. connect(addGroup, SIGNAL(triggered(bool)), this,
  4095. SLOT(AddSourceFromAction()));
  4096. popup->addAction(addGroup);
  4097. if (!foundDeprecated) {
  4098. delete deprecated;
  4099. deprecated = nullptr;
  4100. }
  4101. if (!foundValues) {
  4102. delete popup;
  4103. popup = nullptr;
  4104. } else if (foundDeprecated) {
  4105. popup->addSeparator();
  4106. popup->addMenu(deprecated);
  4107. }
  4108. return popup;
  4109. }
  4110. void OBSBasic::AddSourceFromAction()
  4111. {
  4112. QAction *action = qobject_cast<QAction *>(sender());
  4113. if (!action)
  4114. return;
  4115. AddSource(QT_TO_UTF8(action->data().toString()));
  4116. }
  4117. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4118. {
  4119. if (!GetCurrentScene()) {
  4120. // Tell the user he needs a scene first (help beginners).
  4121. OBSMessageBox::information(
  4122. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4123. QTStr("Basic.Main.AddSourceHelp.Text"));
  4124. return;
  4125. }
  4126. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4127. if (popup)
  4128. popup->exec(pos);
  4129. }
  4130. void OBSBasic::on_actionAddSource_triggered()
  4131. {
  4132. AddSourcePopupMenu(QCursor::pos());
  4133. }
  4134. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4135. {
  4136. vector<OBSSceneItem> &items =
  4137. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4138. if (obs_sceneitem_selected(item)) {
  4139. items.emplace_back(item);
  4140. } else if (obs_sceneitem_is_group(item)) {
  4141. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4142. }
  4143. return true;
  4144. };
  4145. void OBSBasic::on_actionRemoveSource_triggered()
  4146. {
  4147. vector<OBSSceneItem> items;
  4148. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  4149. if (!items.size())
  4150. return;
  4151. auto removeMultiple = [this](size_t count) {
  4152. QString text = QTStr("ConfirmRemove.TextMultiple")
  4153. .arg(QString::number(count));
  4154. QMessageBox remove_items(this);
  4155. remove_items.setText(text);
  4156. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4157. QMessageBox::YesRole);
  4158. remove_items.setDefaultButton(Yes);
  4159. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4160. remove_items.setIcon(QMessageBox::Question);
  4161. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4162. remove_items.exec();
  4163. return Yes == remove_items.clickedButton();
  4164. };
  4165. if (items.size() == 1) {
  4166. OBSSceneItem &item = items[0];
  4167. obs_source_t *source = obs_sceneitem_get_source(item);
  4168. if (source && QueryRemoveSource(source))
  4169. obs_sceneitem_remove(item);
  4170. } else {
  4171. if (removeMultiple(items.size())) {
  4172. for (auto &item : items)
  4173. obs_sceneitem_remove(item);
  4174. }
  4175. }
  4176. }
  4177. void OBSBasic::on_actionInteract_triggered()
  4178. {
  4179. OBSSceneItem item = GetCurrentSceneItem();
  4180. OBSSource source = obs_sceneitem_get_source(item);
  4181. if (source)
  4182. CreateInteractionWindow(source);
  4183. }
  4184. void OBSBasic::on_actionSourceProperties_triggered()
  4185. {
  4186. OBSSceneItem item = GetCurrentSceneItem();
  4187. OBSSource source = obs_sceneitem_get_source(item);
  4188. if (source)
  4189. CreatePropertiesWindow(source);
  4190. }
  4191. void OBSBasic::on_actionSourceUp_triggered()
  4192. {
  4193. OBSSceneItem item = GetCurrentSceneItem();
  4194. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  4195. }
  4196. void OBSBasic::on_actionSourceDown_triggered()
  4197. {
  4198. OBSSceneItem item = GetCurrentSceneItem();
  4199. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  4200. }
  4201. void OBSBasic::on_actionMoveUp_triggered()
  4202. {
  4203. OBSSceneItem item = GetCurrentSceneItem();
  4204. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  4205. }
  4206. void OBSBasic::on_actionMoveDown_triggered()
  4207. {
  4208. OBSSceneItem item = GetCurrentSceneItem();
  4209. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  4210. }
  4211. void OBSBasic::on_actionMoveToTop_triggered()
  4212. {
  4213. OBSSceneItem item = GetCurrentSceneItem();
  4214. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  4215. }
  4216. void OBSBasic::on_actionMoveToBottom_triggered()
  4217. {
  4218. OBSSceneItem item = GetCurrentSceneItem();
  4219. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  4220. }
  4221. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4222. {
  4223. char logDir[512];
  4224. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4225. return nullptr;
  4226. string path = logDir;
  4227. path += "/";
  4228. path += log;
  4229. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4230. if (!file)
  4231. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4232. return file;
  4233. }
  4234. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4235. {
  4236. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4237. if (!fileString)
  4238. return;
  4239. if (!*fileString)
  4240. return;
  4241. ui->menuLogFiles->setEnabled(false);
  4242. ui->menuCrashLogs->setEnabled(false);
  4243. stringstream ss;
  4244. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4245. << CurrentDateTimeString() << "\n\n"
  4246. << fileString;
  4247. if (logUploadThread) {
  4248. logUploadThread->wait();
  4249. }
  4250. RemoteTextThread *thread =
  4251. new RemoteTextThread("https://obsproject.com/logs/upload",
  4252. "text/plain", ss.str().c_str());
  4253. logUploadThread.reset(thread);
  4254. if (crash) {
  4255. connect(thread, &RemoteTextThread::Result, this,
  4256. &OBSBasic::crashUploadFinished);
  4257. } else {
  4258. connect(thread, &RemoteTextThread::Result, this,
  4259. &OBSBasic::logUploadFinished);
  4260. }
  4261. logUploadThread->start();
  4262. }
  4263. void OBSBasic::on_actionShowLogs_triggered()
  4264. {
  4265. char logDir[512];
  4266. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4267. return;
  4268. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4269. QDesktopServices::openUrl(url);
  4270. }
  4271. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4272. {
  4273. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  4274. }
  4275. void OBSBasic::on_actionUploadLastLog_triggered()
  4276. {
  4277. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  4278. }
  4279. void OBSBasic::on_actionViewCurrentLog_triggered()
  4280. {
  4281. logView->setVisible(!logView->isVisible());
  4282. }
  4283. void OBSBasic::on_actionShowCrashLogs_triggered()
  4284. {
  4285. char logDir[512];
  4286. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4287. return;
  4288. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4289. QDesktopServices::openUrl(url);
  4290. }
  4291. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4292. {
  4293. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  4294. }
  4295. void OBSBasic::on_actionCheckForUpdates_triggered()
  4296. {
  4297. CheckForUpdates(true);
  4298. }
  4299. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4300. {
  4301. ui->menuLogFiles->setEnabled(true);
  4302. ui->menuCrashLogs->setEnabled(true);
  4303. if (text.isEmpty()) {
  4304. OBSMessageBox::critical(
  4305. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4306. error);
  4307. return;
  4308. }
  4309. openLogDialog(text, false);
  4310. }
  4311. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  4312. {
  4313. ui->menuLogFiles->setEnabled(true);
  4314. ui->menuCrashLogs->setEnabled(true);
  4315. if (text.isEmpty()) {
  4316. OBSMessageBox::critical(
  4317. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4318. error);
  4319. return;
  4320. }
  4321. openLogDialog(text, true);
  4322. }
  4323. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  4324. {
  4325. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4326. string resURL = obs_data_get_string(returnData, "url");
  4327. QString logURL = resURL.c_str();
  4328. obs_data_release(returnData);
  4329. OBSLogReply logDialog(this, logURL, crash);
  4330. logDialog.exec();
  4331. }
  4332. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4333. obs_source_t *source, const string &name)
  4334. {
  4335. const char *prevName = obs_source_get_name(source);
  4336. if (name == prevName)
  4337. return;
  4338. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4339. QListWidgetItem *listItem = listWidget->currentItem();
  4340. if (foundSource || name.empty()) {
  4341. listItem->setText(QT_UTF8(prevName));
  4342. if (foundSource) {
  4343. OBSMessageBox::warning(parent,
  4344. QTStr("NameExists.Title"),
  4345. QTStr("NameExists.Text"));
  4346. } else if (name.empty()) {
  4347. OBSMessageBox::warning(parent,
  4348. QTStr("NoNameEntered.Title"),
  4349. QTStr("NoNameEntered.Text"));
  4350. }
  4351. obs_source_release(foundSource);
  4352. } else {
  4353. listItem->setText(QT_UTF8(name.c_str()));
  4354. obs_source_set_name(source, name.c_str());
  4355. }
  4356. }
  4357. void OBSBasic::SceneNameEdited(QWidget *editor,
  4358. QAbstractItemDelegate::EndEditHint endHint)
  4359. {
  4360. OBSScene scene = GetCurrentScene();
  4361. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4362. string text = QT_TO_UTF8(edit->text().trimmed());
  4363. if (!scene)
  4364. return;
  4365. obs_source_t *source = obs_scene_get_source(scene);
  4366. RenameListItem(this, ui->scenes, source, text);
  4367. if (api)
  4368. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4369. UNUSED_PARAMETER(endHint);
  4370. }
  4371. void OBSBasic::OpenFilters()
  4372. {
  4373. OBSSceneItem item = GetCurrentSceneItem();
  4374. OBSSource source = obs_sceneitem_get_source(item);
  4375. CreateFiltersWindow(source);
  4376. }
  4377. void OBSBasic::OpenSceneFilters()
  4378. {
  4379. OBSScene scene = GetCurrentScene();
  4380. OBSSource source = obs_scene_get_source(scene);
  4381. CreateFiltersWindow(source);
  4382. }
  4383. #define RECORDING_START \
  4384. "==== Recording Start ==============================================="
  4385. #define RECORDING_STOP \
  4386. "==== Recording Stop ================================================"
  4387. #define REPLAY_BUFFER_START \
  4388. "==== Replay Buffer Start ==========================================="
  4389. #define REPLAY_BUFFER_STOP \
  4390. "==== Replay Buffer Stop ============================================"
  4391. #define STREAMING_START \
  4392. "==== Streaming Start ==============================================="
  4393. #define STREAMING_STOP \
  4394. "==== Streaming Stop ================================================"
  4395. #define VIRTUAL_CAM_START \
  4396. "==== Virtual Camera Start =========================================="
  4397. #define VIRTUAL_CAM_STOP \
  4398. "==== Virtual Camera Stop ==========================================="
  4399. void OBSBasic::StartStreaming()
  4400. {
  4401. if (outputHandler->StreamingActive())
  4402. return;
  4403. if (disableOutputsRef)
  4404. return;
  4405. if (api)
  4406. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4407. SaveProject();
  4408. ui->streamButton->setEnabled(false);
  4409. ui->streamButton->setChecked(false);
  4410. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4411. if (sysTrayStream) {
  4412. sysTrayStream->setEnabled(false);
  4413. sysTrayStream->setText(ui->streamButton->text());
  4414. }
  4415. if (!outputHandler->StartStreaming(service)) {
  4416. QString message =
  4417. !outputHandler->lastError.empty()
  4418. ? QTStr(outputHandler->lastError.c_str())
  4419. : QTStr("Output.StartFailedGeneric");
  4420. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4421. ui->streamButton->setEnabled(true);
  4422. ui->streamButton->setChecked(false);
  4423. if (sysTrayStream) {
  4424. sysTrayStream->setText(ui->streamButton->text());
  4425. sysTrayStream->setEnabled(true);
  4426. }
  4427. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
  4428. message);
  4429. return;
  4430. }
  4431. bool recordWhenStreaming = config_get_bool(
  4432. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4433. if (recordWhenStreaming)
  4434. StartRecording();
  4435. bool replayBufferWhileStreaming = config_get_bool(
  4436. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4437. if (replayBufferWhileStreaming)
  4438. StartReplayBuffer();
  4439. }
  4440. #ifdef _WIN32
  4441. static inline void UpdateProcessPriority()
  4442. {
  4443. const char *priority = config_get_string(App()->GlobalConfig(),
  4444. "General", "ProcessPriority");
  4445. if (priority && strcmp(priority, "Normal") != 0)
  4446. SetProcessPriority(priority);
  4447. }
  4448. static inline void ClearProcessPriority()
  4449. {
  4450. const char *priority = config_get_string(App()->GlobalConfig(),
  4451. "General", "ProcessPriority");
  4452. if (priority && strcmp(priority, "Normal") != 0)
  4453. SetProcessPriority("Normal");
  4454. }
  4455. #else
  4456. #define UpdateProcessPriority() \
  4457. do { \
  4458. } while (false)
  4459. #define ClearProcessPriority() \
  4460. do { \
  4461. } while (false)
  4462. #endif
  4463. inline void OBSBasic::OnActivate()
  4464. {
  4465. if (ui->profileMenu->isEnabled()) {
  4466. ui->profileMenu->setEnabled(false);
  4467. ui->autoConfigure->setEnabled(false);
  4468. App()->IncrementSleepInhibition();
  4469. UpdateProcessPriority();
  4470. if (trayIcon)
  4471. trayIcon->setIcon(QIcon::fromTheme(
  4472. "obs-tray-active",
  4473. QIcon(":/res/images/tray_active.png")));
  4474. }
  4475. }
  4476. extern volatile bool recording_paused;
  4477. extern volatile bool replaybuf_active;
  4478. inline void OBSBasic::OnDeactivate()
  4479. {
  4480. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4481. ui->profileMenu->setEnabled(true);
  4482. ui->autoConfigure->setEnabled(true);
  4483. App()->DecrementSleepInhibition();
  4484. ClearProcessPriority();
  4485. if (trayIcon)
  4486. trayIcon->setIcon(QIcon::fromTheme(
  4487. "obs-tray", QIcon(":/res/images/obs.png")));
  4488. } else if (trayIcon) {
  4489. if (os_atomic_load_bool(&recording_paused))
  4490. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  4491. else
  4492. trayIcon->setIcon(
  4493. QIcon(":/res/images/tray_active.png"));
  4494. }
  4495. }
  4496. void OBSBasic::StopStreaming()
  4497. {
  4498. SaveProject();
  4499. if (outputHandler->StreamingActive())
  4500. outputHandler->StopStreaming(streamingStopping);
  4501. OnDeactivate();
  4502. bool recordWhenStreaming = config_get_bool(
  4503. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4504. bool keepRecordingWhenStreamStops =
  4505. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4506. "KeepRecordingWhenStreamStops");
  4507. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4508. StopRecording();
  4509. bool replayBufferWhileStreaming = config_get_bool(
  4510. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4511. bool keepReplayBufferStreamStops =
  4512. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4513. "KeepReplayBufferStreamStops");
  4514. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4515. StopReplayBuffer();
  4516. }
  4517. void OBSBasic::ForceStopStreaming()
  4518. {
  4519. SaveProject();
  4520. if (outputHandler->StreamingActive())
  4521. outputHandler->StopStreaming(true);
  4522. OnDeactivate();
  4523. bool recordWhenStreaming = config_get_bool(
  4524. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4525. bool keepRecordingWhenStreamStops =
  4526. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4527. "KeepRecordingWhenStreamStops");
  4528. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4529. StopRecording();
  4530. bool replayBufferWhileStreaming = config_get_bool(
  4531. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4532. bool keepReplayBufferStreamStops =
  4533. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4534. "KeepReplayBufferStreamStops");
  4535. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4536. StopReplayBuffer();
  4537. }
  4538. void OBSBasic::StreamDelayStarting(int sec)
  4539. {
  4540. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4541. ui->streamButton->setEnabled(true);
  4542. ui->streamButton->setChecked(true);
  4543. if (sysTrayStream) {
  4544. sysTrayStream->setText(ui->streamButton->text());
  4545. sysTrayStream->setEnabled(true);
  4546. }
  4547. if (!startStreamMenu.isNull())
  4548. startStreamMenu->deleteLater();
  4549. startStreamMenu = new QMenu();
  4550. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  4551. SLOT(StopStreaming()));
  4552. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4553. SLOT(ForceStopStreaming()));
  4554. ui->streamButton->setMenu(startStreamMenu);
  4555. ui->statusbar->StreamDelayStarting(sec);
  4556. OnActivate();
  4557. }
  4558. void OBSBasic::StreamDelayStopping(int sec)
  4559. {
  4560. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4561. ui->streamButton->setEnabled(true);
  4562. ui->streamButton->setChecked(false);
  4563. if (sysTrayStream) {
  4564. sysTrayStream->setText(ui->streamButton->text());
  4565. sysTrayStream->setEnabled(true);
  4566. }
  4567. if (!startStreamMenu.isNull())
  4568. startStreamMenu->deleteLater();
  4569. startStreamMenu = new QMenu();
  4570. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  4571. SLOT(StartStreaming()));
  4572. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4573. SLOT(ForceStopStreaming()));
  4574. ui->streamButton->setMenu(startStreamMenu);
  4575. ui->statusbar->StreamDelayStopping(sec);
  4576. if (api)
  4577. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4578. }
  4579. void OBSBasic::StreamingStart()
  4580. {
  4581. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4582. ui->streamButton->setEnabled(true);
  4583. ui->streamButton->setChecked(true);
  4584. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4585. if (sysTrayStream) {
  4586. sysTrayStream->setText(ui->streamButton->text());
  4587. sysTrayStream->setEnabled(true);
  4588. }
  4589. if (api)
  4590. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4591. OnActivate();
  4592. blog(LOG_INFO, STREAMING_START);
  4593. }
  4594. void OBSBasic::StreamStopping()
  4595. {
  4596. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4597. if (sysTrayStream)
  4598. sysTrayStream->setText(ui->streamButton->text());
  4599. streamingStopping = true;
  4600. if (api)
  4601. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4602. }
  4603. void OBSBasic::StreamingStop(int code, QString last_error)
  4604. {
  4605. const char *errorDescription = "";
  4606. DStr errorMessage;
  4607. bool use_last_error = false;
  4608. bool encode_error = false;
  4609. switch (code) {
  4610. case OBS_OUTPUT_BAD_PATH:
  4611. errorDescription = Str("Output.ConnectFail.BadPath");
  4612. break;
  4613. case OBS_OUTPUT_CONNECT_FAILED:
  4614. use_last_error = true;
  4615. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4616. break;
  4617. case OBS_OUTPUT_INVALID_STREAM:
  4618. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4619. break;
  4620. case OBS_OUTPUT_ENCODE_ERROR:
  4621. encode_error = true;
  4622. break;
  4623. default:
  4624. case OBS_OUTPUT_ERROR:
  4625. use_last_error = true;
  4626. errorDescription = Str("Output.ConnectFail.Error");
  4627. break;
  4628. case OBS_OUTPUT_DISCONNECTED:
  4629. /* doesn't happen if output is set to reconnect. note that
  4630. * reconnects are handled in the output, not in the UI */
  4631. use_last_error = true;
  4632. errorDescription = Str("Output.ConnectFail.Disconnected");
  4633. }
  4634. if (use_last_error && !last_error.isEmpty())
  4635. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4636. QT_TO_UTF8(last_error));
  4637. else
  4638. dstr_copy(errorMessage, errorDescription);
  4639. ui->statusbar->StreamStopped();
  4640. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4641. ui->streamButton->setEnabled(true);
  4642. ui->streamButton->setChecked(false);
  4643. if (sysTrayStream) {
  4644. sysTrayStream->setText(ui->streamButton->text());
  4645. sysTrayStream->setEnabled(true);
  4646. }
  4647. streamingStopping = false;
  4648. if (api)
  4649. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4650. OnDeactivate();
  4651. blog(LOG_INFO, STREAMING_STOP);
  4652. if (encode_error) {
  4653. OBSMessageBox::information(
  4654. this, QTStr("Output.StreamEncodeError.Title"),
  4655. QTStr("Output.StreamEncodeError.Msg"));
  4656. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4657. OBSMessageBox::information(this,
  4658. QTStr("Output.ConnectFail.Title"),
  4659. QT_UTF8(errorMessage));
  4660. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4661. SysTrayNotify(QT_UTF8(errorDescription),
  4662. QSystemTrayIcon::Warning);
  4663. }
  4664. if (!startStreamMenu.isNull()) {
  4665. ui->streamButton->setMenu(nullptr);
  4666. startStreamMenu->deleteLater();
  4667. startStreamMenu = nullptr;
  4668. }
  4669. }
  4670. void OBSBasic::AutoRemux()
  4671. {
  4672. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4673. bool advanced = astrcmpi(mode, "Advanced") == 0;
  4674. const char *path = !advanced ? config_get_string(basicConfig,
  4675. "SimpleOutput",
  4676. "FilePath")
  4677. : config_get_string(basicConfig, "AdvOut",
  4678. "RecFilePath");
  4679. /* do not save if using FFmpeg output in advanced output mode */
  4680. if (advanced) {
  4681. const char *type =
  4682. config_get_string(basicConfig, "AdvOut", "RecType");
  4683. if (astrcmpi(type, "FFmpeg") == 0) {
  4684. return;
  4685. }
  4686. }
  4687. QString input;
  4688. input += path;
  4689. input += "/";
  4690. input += remuxFilename.c_str();
  4691. QFileInfo fi(remuxFilename.c_str());
  4692. /* do not remux if lossless */
  4693. if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
  4694. return;
  4695. }
  4696. QString output;
  4697. output += path;
  4698. output += "/";
  4699. output += fi.completeBaseName();
  4700. output += ".mp4";
  4701. OBSRemux *remux = new OBSRemux(path, this, true);
  4702. remux->show();
  4703. remux->AutoRemux(input, output);
  4704. }
  4705. void OBSBasic::StartRecording()
  4706. {
  4707. if (outputHandler->RecordingActive())
  4708. return;
  4709. if (disableOutputsRef)
  4710. return;
  4711. if (!OutputPathValid()) {
  4712. OutputPathInvalidMessage();
  4713. ui->recordButton->setChecked(false);
  4714. return;
  4715. }
  4716. if (LowDiskSpace()) {
  4717. DiskSpaceMessage();
  4718. ui->recordButton->setChecked(false);
  4719. return;
  4720. }
  4721. if (api)
  4722. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4723. SaveProject();
  4724. if (!outputHandler->StartRecording())
  4725. ui->recordButton->setChecked(false);
  4726. }
  4727. void OBSBasic::RecordStopping()
  4728. {
  4729. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4730. if (sysTrayRecord)
  4731. sysTrayRecord->setText(ui->recordButton->text());
  4732. recordingStopping = true;
  4733. if (api)
  4734. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4735. }
  4736. void OBSBasic::StopRecording()
  4737. {
  4738. SaveProject();
  4739. if (outputHandler->RecordingActive())
  4740. outputHandler->StopRecording(recordingStopping);
  4741. OnDeactivate();
  4742. }
  4743. void OBSBasic::RecordingStart()
  4744. {
  4745. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4746. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4747. ui->recordButton->setChecked(true);
  4748. if (sysTrayRecord)
  4749. sysTrayRecord->setText(ui->recordButton->text());
  4750. recordingStopping = false;
  4751. if (api)
  4752. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4753. if (!diskFullTimer->isActive())
  4754. diskFullTimer->start(1000);
  4755. OnActivate();
  4756. UpdatePause();
  4757. blog(LOG_INFO, RECORDING_START);
  4758. }
  4759. void OBSBasic::RecordingStop(int code, QString last_error)
  4760. {
  4761. ui->statusbar->RecordingStopped();
  4762. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4763. ui->recordButton->setChecked(false);
  4764. if (sysTrayRecord)
  4765. sysTrayRecord->setText(ui->recordButton->text());
  4766. blog(LOG_INFO, RECORDING_STOP);
  4767. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4768. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4769. QTStr("Output.RecordFail.Unsupported"));
  4770. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  4771. OBSMessageBox::warning(
  4772. this, QTStr("Output.RecordError.Title"),
  4773. QTStr("Output.RecordError.EncodeErrorMsg"));
  4774. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4775. OBSMessageBox::warning(this,
  4776. QTStr("Output.RecordNoSpace.Title"),
  4777. QTStr("Output.RecordNoSpace.Msg"));
  4778. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4779. const char *errorDescription;
  4780. DStr errorMessage;
  4781. bool use_last_error = true;
  4782. errorDescription = Str("Output.RecordError.Msg");
  4783. if (use_last_error && !last_error.isEmpty())
  4784. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4785. QT_TO_UTF8(last_error));
  4786. else
  4787. dstr_copy(errorMessage, errorDescription);
  4788. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4789. QT_UTF8(errorMessage));
  4790. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4791. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4792. QSystemTrayIcon::Warning);
  4793. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4794. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4795. QSystemTrayIcon::Warning);
  4796. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4797. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4798. QSystemTrayIcon::Warning);
  4799. }
  4800. if (api)
  4801. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4802. if (diskFullTimer->isActive())
  4803. diskFullTimer->stop();
  4804. if (remuxAfterRecord)
  4805. AutoRemux();
  4806. OnDeactivate();
  4807. UpdatePause(false);
  4808. }
  4809. void OBSBasic::ShowReplayBufferPauseWarning()
  4810. {
  4811. auto msgBox = []() {
  4812. QMessageBox msgbox(App()->GetMainWindow());
  4813. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  4814. "PauseWarning.Title"));
  4815. msgbox.setText(QTStr("Output.ReplayBuffer."
  4816. "PauseWarning.Text"));
  4817. msgbox.setIcon(QMessageBox::Icon::Information);
  4818. msgbox.addButton(QMessageBox::Ok);
  4819. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  4820. msgbox.setCheckBox(cb);
  4821. msgbox.exec();
  4822. if (cb->isChecked()) {
  4823. config_set_bool(App()->GlobalConfig(), "General",
  4824. "WarnedAboutReplayBufferPausing", true);
  4825. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  4826. }
  4827. };
  4828. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  4829. "WarnedAboutReplayBufferPausing");
  4830. if (!warned) {
  4831. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  4832. Q_ARG(VoidFunc, msgBox));
  4833. }
  4834. }
  4835. void OBSBasic::StartReplayBuffer()
  4836. {
  4837. if (!outputHandler || !outputHandler->replayBuffer)
  4838. return;
  4839. if (outputHandler->ReplayBufferActive())
  4840. return;
  4841. if (disableOutputsRef)
  4842. return;
  4843. if (!UIValidation::NoSourcesConfirmation(this)) {
  4844. replayBufferButton->setChecked(false);
  4845. return;
  4846. }
  4847. if (LowDiskSpace()) {
  4848. DiskSpaceMessage();
  4849. replayBufferButton->setChecked(false);
  4850. return;
  4851. }
  4852. if (api)
  4853. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4854. SaveProject();
  4855. if (!outputHandler->StartReplayBuffer()) {
  4856. replayBufferButton->setChecked(false);
  4857. } else if (os_atomic_load_bool(&recording_paused)) {
  4858. ShowReplayBufferPauseWarning();
  4859. }
  4860. }
  4861. void OBSBasic::ReplayBufferStopping()
  4862. {
  4863. if (!outputHandler || !outputHandler->replayBuffer)
  4864. return;
  4865. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4866. if (sysTrayReplayBuffer)
  4867. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4868. replayBufferStopping = true;
  4869. if (api)
  4870. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4871. }
  4872. void OBSBasic::StopReplayBuffer()
  4873. {
  4874. if (!outputHandler || !outputHandler->replayBuffer)
  4875. return;
  4876. SaveProject();
  4877. if (outputHandler->ReplayBufferActive())
  4878. outputHandler->StopReplayBuffer(replayBufferStopping);
  4879. OnDeactivate();
  4880. }
  4881. void OBSBasic::ReplayBufferStart()
  4882. {
  4883. if (!outputHandler || !outputHandler->replayBuffer)
  4884. return;
  4885. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4886. replayBufferButton->setChecked(true);
  4887. if (sysTrayReplayBuffer)
  4888. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4889. replayBufferStopping = false;
  4890. if (api)
  4891. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4892. OnActivate();
  4893. UpdateReplayBuffer();
  4894. blog(LOG_INFO, REPLAY_BUFFER_START);
  4895. }
  4896. void OBSBasic::ReplayBufferSave()
  4897. {
  4898. if (!outputHandler || !outputHandler->replayBuffer)
  4899. return;
  4900. if (!outputHandler->ReplayBufferActive())
  4901. return;
  4902. calldata_t cd = {0};
  4903. proc_handler_t *ph =
  4904. obs_output_get_proc_handler(outputHandler->replayBuffer);
  4905. proc_handler_call(ph, "save", &cd);
  4906. calldata_free(&cd);
  4907. }
  4908. void OBSBasic::ReplayBufferStop(int code)
  4909. {
  4910. if (!outputHandler || !outputHandler->replayBuffer)
  4911. return;
  4912. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4913. replayBufferButton->setChecked(false);
  4914. if (sysTrayReplayBuffer)
  4915. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4916. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4917. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4918. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4919. QTStr("Output.RecordFail.Unsupported"));
  4920. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4921. OBSMessageBox::warning(this,
  4922. QTStr("Output.RecordNoSpace.Title"),
  4923. QTStr("Output.RecordNoSpace.Msg"));
  4924. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4925. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4926. QTStr("Output.RecordError.Msg"));
  4927. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4928. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4929. QSystemTrayIcon::Warning);
  4930. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4931. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4932. QSystemTrayIcon::Warning);
  4933. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4934. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4935. QSystemTrayIcon::Warning);
  4936. }
  4937. if (api)
  4938. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4939. OnDeactivate();
  4940. UpdateReplayBuffer(false);
  4941. }
  4942. void OBSBasic::StartVirtualCam()
  4943. {
  4944. if (!outputHandler || !outputHandler->virtualCam)
  4945. return;
  4946. if (outputHandler->VirtualCamActive())
  4947. return;
  4948. if (disableOutputsRef)
  4949. return;
  4950. SaveProject();
  4951. if (!outputHandler->StartVirtualCam()) {
  4952. vcamButton->setChecked(false);
  4953. }
  4954. }
  4955. void OBSBasic::StopVirtualCam()
  4956. {
  4957. if (!outputHandler || !outputHandler->virtualCam)
  4958. return;
  4959. SaveProject();
  4960. if (outputHandler->VirtualCamActive())
  4961. outputHandler->StopVirtualCam();
  4962. OnDeactivate();
  4963. }
  4964. void OBSBasic::OnVirtualCamStart()
  4965. {
  4966. if (!outputHandler || !outputHandler->virtualCam)
  4967. return;
  4968. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  4969. vcamButton->setChecked(true);
  4970. OnActivate();
  4971. blog(LOG_INFO, VIRTUAL_CAM_START);
  4972. }
  4973. void OBSBasic::OnVirtualCamStop(int)
  4974. {
  4975. if (!outputHandler || !outputHandler->virtualCam)
  4976. return;
  4977. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  4978. vcamButton->setChecked(false);
  4979. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  4980. OnDeactivate();
  4981. }
  4982. void OBSBasic::on_streamButton_clicked()
  4983. {
  4984. if (outputHandler->StreamingActive()) {
  4985. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4986. "WarnBeforeStoppingStream");
  4987. if (confirm && isVisible()) {
  4988. QMessageBox::StandardButton button =
  4989. OBSMessageBox::question(
  4990. this, QTStr("ConfirmStop.Title"),
  4991. QTStr("ConfirmStop.Text"),
  4992. QMessageBox::Yes | QMessageBox::No,
  4993. QMessageBox::No);
  4994. if (button == QMessageBox::No) {
  4995. ui->streamButton->setChecked(true);
  4996. return;
  4997. }
  4998. }
  4999. StopStreaming();
  5000. } else {
  5001. if (!UIValidation::NoSourcesConfirmation(this)) {
  5002. ui->streamButton->setChecked(false);
  5003. return;
  5004. }
  5005. auto action =
  5006. UIValidation::StreamSettingsConfirmation(this, service);
  5007. switch (action) {
  5008. case StreamSettingsAction::ContinueStream:
  5009. break;
  5010. case StreamSettingsAction::OpenSettings:
  5011. on_action_Settings_triggered();
  5012. ui->streamButton->setChecked(false);
  5013. return;
  5014. case StreamSettingsAction::Cancel:
  5015. ui->streamButton->setChecked(false);
  5016. return;
  5017. }
  5018. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5019. "WarnBeforeStartingStream");
  5020. obs_data_t *settings = obs_service_get_settings(service);
  5021. bool bwtest = obs_data_get_bool(settings, "bwtest");
  5022. obs_data_release(settings);
  5023. if (bwtest && isVisible()) {
  5024. QMessageBox::StandardButton button =
  5025. OBSMessageBox::question(
  5026. this, QTStr("ConfirmBWTest.Title"),
  5027. QTStr("ConfirmBWTest.Text"));
  5028. if (button == QMessageBox::No) {
  5029. ui->streamButton->setChecked(false);
  5030. return;
  5031. }
  5032. } else if (confirm && isVisible()) {
  5033. QMessageBox::StandardButton button =
  5034. OBSMessageBox::question(
  5035. this, QTStr("ConfirmStart.Title"),
  5036. QTStr("ConfirmStart.Text"),
  5037. QMessageBox::Yes | QMessageBox::No,
  5038. QMessageBox::No);
  5039. if (button == QMessageBox::No) {
  5040. ui->streamButton->setChecked(false);
  5041. return;
  5042. }
  5043. }
  5044. StartStreaming();
  5045. }
  5046. }
  5047. void OBSBasic::on_recordButton_clicked()
  5048. {
  5049. if (outputHandler->RecordingActive()) {
  5050. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5051. "WarnBeforeStoppingRecord");
  5052. if (confirm && isVisible()) {
  5053. QMessageBox::StandardButton button =
  5054. OBSMessageBox::question(
  5055. this, QTStr("ConfirmStopRecord.Title"),
  5056. QTStr("ConfirmStopRecord.Text"),
  5057. QMessageBox::Yes | QMessageBox::No,
  5058. QMessageBox::No);
  5059. if (button == QMessageBox::No) {
  5060. ui->recordButton->setChecked(true);
  5061. return;
  5062. }
  5063. }
  5064. StopRecording();
  5065. } else {
  5066. if (!UIValidation::NoSourcesConfirmation(this)) {
  5067. ui->recordButton->setChecked(false);
  5068. return;
  5069. }
  5070. StartRecording();
  5071. }
  5072. }
  5073. void OBSBasic::VCamButtonClicked()
  5074. {
  5075. if (outputHandler->VirtualCamActive()) {
  5076. StopVirtualCam();
  5077. } else {
  5078. if (!UIValidation::NoSourcesConfirmation(this)) {
  5079. vcamButton->setChecked(false);
  5080. return;
  5081. }
  5082. StartVirtualCam();
  5083. }
  5084. }
  5085. void OBSBasic::on_settingsButton_clicked()
  5086. {
  5087. on_action_Settings_triggered();
  5088. }
  5089. void OBSBasic::on_actionHelpPortal_triggered()
  5090. {
  5091. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  5092. QDesktopServices::openUrl(url);
  5093. }
  5094. void OBSBasic::on_actionWebsite_triggered()
  5095. {
  5096. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  5097. QDesktopServices::openUrl(url);
  5098. }
  5099. void OBSBasic::on_actionDiscord_triggered()
  5100. {
  5101. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  5102. QDesktopServices::openUrl(url);
  5103. }
  5104. void OBSBasic::on_actionShowSettingsFolder_triggered()
  5105. {
  5106. char path[512];
  5107. int ret = GetConfigPath(path, 512, "obs-studio");
  5108. if (ret <= 0)
  5109. return;
  5110. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5111. }
  5112. void OBSBasic::on_actionShowProfileFolder_triggered()
  5113. {
  5114. char path[512];
  5115. int ret = GetProfilePath(path, 512, "");
  5116. if (ret <= 0)
  5117. return;
  5118. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5119. }
  5120. int OBSBasic::GetTopSelectedSourceItem()
  5121. {
  5122. QModelIndexList selectedItems =
  5123. ui->sources->selectionModel()->selectedIndexes();
  5124. return selectedItems.count() ? selectedItems[0].row() : -1;
  5125. }
  5126. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  5127. {
  5128. return ui->sources->selectionModel()->selectedIndexes();
  5129. }
  5130. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  5131. {
  5132. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  5133. UNUSED_PARAMETER(pos);
  5134. }
  5135. void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
  5136. {
  5137. QMenu popup(this);
  5138. QPointer<QMenu> studioProgramProjector;
  5139. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5140. AddProjectorMenuMonitors(studioProgramProjector, this,
  5141. SLOT(OpenStudioProgramProjector()));
  5142. popup.addMenu(studioProgramProjector);
  5143. QAction *studioProgramWindow =
  5144. popup.addAction(QTStr("StudioProgramWindow"), this,
  5145. SLOT(OpenStudioProgramWindow()));
  5146. popup.addAction(studioProgramWindow);
  5147. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  5148. SLOT(ScreenshotProgram()));
  5149. popup.exec(QCursor::pos());
  5150. }
  5151. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  5152. {
  5153. QMenu popup(this);
  5154. delete previewProjectorMain;
  5155. QAction *action =
  5156. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  5157. this, SLOT(TogglePreview()));
  5158. action->setCheckable(true);
  5159. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  5160. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  5161. AddProjectorMenuMonitors(previewProjectorMain, this,
  5162. SLOT(OpenPreviewProjector()));
  5163. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  5164. SLOT(OpenPreviewWindow()));
  5165. popup.addMenu(previewProjectorMain);
  5166. popup.addAction(previewWindow);
  5167. popup.exec(QCursor::pos());
  5168. UNUSED_PARAMETER(pos);
  5169. }
  5170. void OBSBasic::on_actionAlwaysOnTop_triggered()
  5171. {
  5172. #ifndef _WIN32
  5173. /* Make sure all dialogs are safely and successfully closed before
  5174. * switching the always on top mode due to the fact that windows all
  5175. * have to be recreated, so queue the actual toggle to happen after
  5176. * all events related to closing the dialogs have finished */
  5177. CloseDialogs();
  5178. #endif
  5179. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  5180. Qt::QueuedConnection);
  5181. }
  5182. void OBSBasic::ToggleAlwaysOnTop()
  5183. {
  5184. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  5185. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  5186. SetAlwaysOnTop(this, !isAlwaysOnTop);
  5187. show();
  5188. }
  5189. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  5190. {
  5191. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  5192. if (strcmp(val, "10") == 0) {
  5193. num = 10;
  5194. den = 1;
  5195. } else if (strcmp(val, "20") == 0) {
  5196. num = 20;
  5197. den = 1;
  5198. } else if (strcmp(val, "24 NTSC") == 0) {
  5199. num = 24000;
  5200. den = 1001;
  5201. } else if (strcmp(val, "25 PAL") == 0) {
  5202. num = 25;
  5203. den = 1;
  5204. } else if (strcmp(val, "29.97") == 0) {
  5205. num = 30000;
  5206. den = 1001;
  5207. } else if (strcmp(val, "48") == 0) {
  5208. num = 48;
  5209. den = 1;
  5210. } else if (strcmp(val, "50 PAL") == 0) {
  5211. num = 50;
  5212. den = 1;
  5213. } else if (strcmp(val, "59.94") == 0) {
  5214. num = 60000;
  5215. den = 1001;
  5216. } else if (strcmp(val, "60") == 0) {
  5217. num = 60;
  5218. den = 1;
  5219. } else {
  5220. num = 30;
  5221. den = 1;
  5222. }
  5223. }
  5224. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  5225. {
  5226. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  5227. den = 1;
  5228. }
  5229. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  5230. {
  5231. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  5232. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  5233. }
  5234. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  5235. {
  5236. num = 1000000000;
  5237. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  5238. }
  5239. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  5240. {
  5241. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  5242. if (type == 1) //"Integer"
  5243. GetFPSInteger(num, den);
  5244. else if (type == 2) //"Fraction"
  5245. GetFPSFraction(num, den);
  5246. else if (false) //"Nanoseconds", currently not implemented
  5247. GetFPSNanoseconds(num, den);
  5248. else
  5249. GetFPSCommon(num, den);
  5250. }
  5251. config_t *OBSBasic::Config() const
  5252. {
  5253. return basicConfig;
  5254. }
  5255. void OBSBasic::on_actionEditTransform_triggered()
  5256. {
  5257. if (transformWindow)
  5258. transformWindow->close();
  5259. if (!GetCurrentSceneItem())
  5260. return;
  5261. transformWindow = new OBSBasicTransform(this);
  5262. transformWindow->show();
  5263. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  5264. }
  5265. static obs_transform_info copiedTransformInfo;
  5266. static obs_sceneitem_crop copiedCropInfo;
  5267. void OBSBasic::on_actionCopyTransform_triggered()
  5268. {
  5269. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  5270. if (!obs_sceneitem_selected(item))
  5271. return true;
  5272. obs_sceneitem_defer_update_begin(item);
  5273. obs_sceneitem_get_info(item, &copiedTransformInfo);
  5274. obs_sceneitem_get_crop(item, &copiedCropInfo);
  5275. obs_sceneitem_defer_update_end(item);
  5276. UNUSED_PARAMETER(scene);
  5277. UNUSED_PARAMETER(param);
  5278. return true;
  5279. };
  5280. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  5281. ui->actionPasteTransform->setEnabled(true);
  5282. }
  5283. void OBSBasic::on_actionPasteTransform_triggered()
  5284. {
  5285. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  5286. if (!obs_sceneitem_selected(item))
  5287. return true;
  5288. obs_sceneitem_defer_update_begin(item);
  5289. obs_sceneitem_set_info(item, &copiedTransformInfo);
  5290. obs_sceneitem_set_crop(item, &copiedCropInfo);
  5291. obs_sceneitem_defer_update_end(item);
  5292. UNUSED_PARAMETER(scene);
  5293. UNUSED_PARAMETER(param);
  5294. return true;
  5295. };
  5296. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  5297. }
  5298. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  5299. {
  5300. if (obs_sceneitem_is_group(item))
  5301. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  5302. if (!obs_sceneitem_selected(item))
  5303. return true;
  5304. if (obs_sceneitem_locked(item))
  5305. return true;
  5306. obs_sceneitem_defer_update_begin(item);
  5307. obs_transform_info info;
  5308. vec2_set(&info.pos, 0.0f, 0.0f);
  5309. vec2_set(&info.scale, 1.0f, 1.0f);
  5310. info.rot = 0.0f;
  5311. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  5312. info.bounds_type = OBS_BOUNDS_NONE;
  5313. info.bounds_alignment = OBS_ALIGN_CENTER;
  5314. vec2_set(&info.bounds, 0.0f, 0.0f);
  5315. obs_sceneitem_set_info(item, &info);
  5316. obs_sceneitem_crop crop = {};
  5317. obs_sceneitem_set_crop(item, &crop);
  5318. obs_sceneitem_defer_update_end(item);
  5319. UNUSED_PARAMETER(scene);
  5320. UNUSED_PARAMETER(param);
  5321. return true;
  5322. }
  5323. void OBSBasic::on_actionResetTransform_triggered()
  5324. {
  5325. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  5326. }
  5327. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  5328. {
  5329. matrix4 boxTransform;
  5330. obs_sceneitem_get_box_transform(item, &boxTransform);
  5331. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  5332. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  5333. auto GetMinPos = [&](float x, float y) {
  5334. vec3 pos;
  5335. vec3_set(&pos, x, y, 0.0f);
  5336. vec3_transform(&pos, &pos, &boxTransform);
  5337. vec3_min(&tl, &tl, &pos);
  5338. vec3_max(&br, &br, &pos);
  5339. };
  5340. GetMinPos(0.0f, 0.0f);
  5341. GetMinPos(1.0f, 0.0f);
  5342. GetMinPos(0.0f, 1.0f);
  5343. GetMinPos(1.0f, 1.0f);
  5344. }
  5345. static vec3 GetItemTL(obs_sceneitem_t *item)
  5346. {
  5347. vec3 tl, br;
  5348. GetItemBox(item, tl, br);
  5349. return tl;
  5350. }
  5351. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  5352. {
  5353. vec3 newTL;
  5354. vec2 pos;
  5355. obs_sceneitem_get_pos(item, &pos);
  5356. newTL = GetItemTL(item);
  5357. pos.x += tl.x - newTL.x;
  5358. pos.y += tl.y - newTL.y;
  5359. obs_sceneitem_set_pos(item, &pos);
  5360. }
  5361. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  5362. void *param)
  5363. {
  5364. if (obs_sceneitem_is_group(item))
  5365. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  5366. param);
  5367. if (!obs_sceneitem_selected(item))
  5368. return true;
  5369. if (obs_sceneitem_locked(item))
  5370. return true;
  5371. float rot = *reinterpret_cast<float *>(param);
  5372. vec3 tl = GetItemTL(item);
  5373. rot += obs_sceneitem_get_rot(item);
  5374. if (rot >= 360.0f)
  5375. rot -= 360.0f;
  5376. else if (rot <= -360.0f)
  5377. rot += 360.0f;
  5378. obs_sceneitem_set_rot(item, rot);
  5379. obs_sceneitem_force_update_transform(item);
  5380. SetItemTL(item, tl);
  5381. UNUSED_PARAMETER(scene);
  5382. return true;
  5383. };
  5384. void OBSBasic::on_actionRotate90CW_triggered()
  5385. {
  5386. float f90CW = 90.0f;
  5387. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  5388. }
  5389. void OBSBasic::on_actionRotate90CCW_triggered()
  5390. {
  5391. float f90CCW = -90.0f;
  5392. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  5393. }
  5394. void OBSBasic::on_actionRotate180_triggered()
  5395. {
  5396. float f180 = 180.0f;
  5397. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  5398. }
  5399. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  5400. void *param)
  5401. {
  5402. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  5403. if (obs_sceneitem_is_group(item))
  5404. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  5405. param);
  5406. if (!obs_sceneitem_selected(item))
  5407. return true;
  5408. if (obs_sceneitem_locked(item))
  5409. return true;
  5410. vec3 tl = GetItemTL(item);
  5411. vec2 scale;
  5412. obs_sceneitem_get_scale(item, &scale);
  5413. vec2_mul(&scale, &scale, &mul);
  5414. obs_sceneitem_set_scale(item, &scale);
  5415. obs_sceneitem_force_update_transform(item);
  5416. SetItemTL(item, tl);
  5417. UNUSED_PARAMETER(scene);
  5418. return true;
  5419. }
  5420. void OBSBasic::on_actionFlipHorizontal_triggered()
  5421. {
  5422. vec2 scale;
  5423. vec2_set(&scale, -1.0f, 1.0f);
  5424. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5425. &scale);
  5426. }
  5427. void OBSBasic::on_actionFlipVertical_triggered()
  5428. {
  5429. vec2 scale;
  5430. vec2_set(&scale, 1.0f, -1.0f);
  5431. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5432. &scale);
  5433. }
  5434. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  5435. void *param)
  5436. {
  5437. obs_bounds_type boundsType =
  5438. *reinterpret_cast<obs_bounds_type *>(param);
  5439. if (obs_sceneitem_is_group(item))
  5440. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  5441. param);
  5442. if (!obs_sceneitem_selected(item))
  5443. return true;
  5444. if (obs_sceneitem_locked(item))
  5445. return true;
  5446. obs_video_info ovi;
  5447. obs_get_video_info(&ovi);
  5448. obs_transform_info itemInfo;
  5449. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  5450. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  5451. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  5452. itemInfo.rot = 0.0f;
  5453. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  5454. float(ovi.base_height));
  5455. itemInfo.bounds_type = boundsType;
  5456. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  5457. obs_sceneitem_set_info(item, &itemInfo);
  5458. UNUSED_PARAMETER(scene);
  5459. return true;
  5460. }
  5461. void OBSBasic::on_actionFitToScreen_triggered()
  5462. {
  5463. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  5464. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5465. &boundsType);
  5466. }
  5467. void OBSBasic::on_actionStretchToScreen_triggered()
  5468. {
  5469. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  5470. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5471. &boundsType);
  5472. }
  5473. enum class CenterType {
  5474. Scene,
  5475. Vertical,
  5476. Horizontal,
  5477. };
  5478. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5479. {
  5480. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  5481. vec3 tl, br, itemCenter, screenCenter, offset;
  5482. obs_video_info ovi;
  5483. obs_transform_info oti;
  5484. if (obs_sceneitem_is_group(item))
  5485. obs_sceneitem_group_enum_items(item, center_to_scene,
  5486. &centerType);
  5487. if (!obs_sceneitem_selected(item))
  5488. return true;
  5489. if (obs_sceneitem_locked(item))
  5490. return true;
  5491. obs_get_video_info(&ovi);
  5492. obs_sceneitem_get_info(item, &oti);
  5493. if (centerType == CenterType::Scene)
  5494. vec3_set(&screenCenter, float(ovi.base_width),
  5495. float(ovi.base_height), 0.0f);
  5496. else if (centerType == CenterType::Vertical)
  5497. vec3_set(&screenCenter, float(oti.bounds.x),
  5498. float(ovi.base_height), 0.0f);
  5499. else if (centerType == CenterType::Horizontal)
  5500. vec3_set(&screenCenter, float(ovi.base_width),
  5501. float(oti.bounds.y), 0.0f);
  5502. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  5503. GetItemBox(item, tl, br);
  5504. vec3_sub(&itemCenter, &br, &tl);
  5505. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  5506. vec3_add(&itemCenter, &itemCenter, &tl);
  5507. vec3_sub(&offset, &screenCenter, &itemCenter);
  5508. vec3_add(&tl, &tl, &offset);
  5509. if (centerType == CenterType::Vertical)
  5510. tl.x = oti.pos.x;
  5511. else if (centerType == CenterType::Horizontal)
  5512. tl.y = oti.pos.y;
  5513. SetItemTL(item, tl);
  5514. return true;
  5515. };
  5516. void OBSBasic::on_actionCenterToScreen_triggered()
  5517. {
  5518. CenterType centerType = CenterType::Scene;
  5519. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5520. }
  5521. void OBSBasic::on_actionVerticalCenter_triggered()
  5522. {
  5523. CenterType centerType = CenterType::Vertical;
  5524. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5525. }
  5526. void OBSBasic::on_actionHorizontalCenter_triggered()
  5527. {
  5528. CenterType centerType = CenterType::Horizontal;
  5529. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5530. }
  5531. void OBSBasic::EnablePreviewDisplay(bool enable)
  5532. {
  5533. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  5534. ui->preview->setVisible(enable);
  5535. ui->previewDisabledWidget->setVisible(!enable);
  5536. }
  5537. void OBSBasic::TogglePreview()
  5538. {
  5539. previewEnabled = !previewEnabled;
  5540. EnablePreviewDisplay(previewEnabled);
  5541. }
  5542. void OBSBasic::EnablePreview()
  5543. {
  5544. if (previewProgramMode)
  5545. return;
  5546. previewEnabled = true;
  5547. EnablePreviewDisplay(true);
  5548. }
  5549. void OBSBasic::DisablePreview()
  5550. {
  5551. if (previewProgramMode)
  5552. return;
  5553. previewEnabled = false;
  5554. EnablePreviewDisplay(false);
  5555. }
  5556. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5557. {
  5558. if (obs_sceneitem_locked(item))
  5559. return true;
  5560. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  5561. struct vec2 pos;
  5562. if (!obs_sceneitem_selected(item)) {
  5563. if (obs_sceneitem_is_group(item)) {
  5564. struct vec3 offset3;
  5565. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5566. struct matrix4 matrix;
  5567. obs_sceneitem_get_draw_transform(item, &matrix);
  5568. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5569. matrix4_inv(&matrix, &matrix);
  5570. vec3_transform(&offset3, &offset3, &matrix);
  5571. struct vec2 new_offset;
  5572. vec2_set(&new_offset, offset3.x, offset3.y);
  5573. obs_sceneitem_group_enum_items(item, nudge_callback,
  5574. &new_offset);
  5575. }
  5576. return true;
  5577. }
  5578. obs_sceneitem_get_pos(item, &pos);
  5579. vec2_add(&pos, &pos, &offset);
  5580. obs_sceneitem_set_pos(item, &pos);
  5581. return true;
  5582. }
  5583. void OBSBasic::Nudge(int dist, MoveDir dir)
  5584. {
  5585. if (ui->preview->Locked())
  5586. return;
  5587. struct vec2 offset;
  5588. vec2_set(&offset, 0.0f, 0.0f);
  5589. switch (dir) {
  5590. case MoveDir::Up:
  5591. offset.y = (float)-dist;
  5592. break;
  5593. case MoveDir::Down:
  5594. offset.y = (float)dist;
  5595. break;
  5596. case MoveDir::Left:
  5597. offset.x = (float)-dist;
  5598. break;
  5599. case MoveDir::Right:
  5600. offset.x = (float)dist;
  5601. break;
  5602. }
  5603. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5604. }
  5605. void OBSBasic::NudgeUp()
  5606. {
  5607. Nudge(1, MoveDir::Up);
  5608. }
  5609. void OBSBasic::NudgeDown()
  5610. {
  5611. Nudge(1, MoveDir::Down);
  5612. }
  5613. void OBSBasic::NudgeLeft()
  5614. {
  5615. Nudge(1, MoveDir::Left);
  5616. }
  5617. void OBSBasic::NudgeRight()
  5618. {
  5619. Nudge(1, MoveDir::Right);
  5620. }
  5621. void OBSBasic::DeleteProjector(OBSProjector *projector)
  5622. {
  5623. for (size_t i = 0; i < projectors.size(); i++) {
  5624. if (projectors[i] == projector) {
  5625. projectors[i]->deleteLater();
  5626. projectors.erase(projectors.begin() + i);
  5627. break;
  5628. }
  5629. }
  5630. }
  5631. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5632. ProjectorType type)
  5633. {
  5634. /* seriously? 10 monitors? */
  5635. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5636. return nullptr;
  5637. if (monitor > -1) {
  5638. for (size_t i = 0; i < projectors.size(); i++) {
  5639. if (projectors[i]->GetMonitor() == monitor) {
  5640. DeleteProjector(projectors[i]);
  5641. break;
  5642. }
  5643. }
  5644. }
  5645. OBSProjector *projector =
  5646. new OBSProjector(nullptr, source, monitor, type);
  5647. if (projector)
  5648. projectors.emplace_back(projector);
  5649. return projector;
  5650. }
  5651. void OBSBasic::OpenStudioProgramProjector()
  5652. {
  5653. int monitor = sender()->property("monitor").toInt();
  5654. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  5655. }
  5656. void OBSBasic::OpenPreviewProjector()
  5657. {
  5658. int monitor = sender()->property("monitor").toInt();
  5659. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  5660. }
  5661. void OBSBasic::OpenSourceProjector()
  5662. {
  5663. int monitor = sender()->property("monitor").toInt();
  5664. OBSSceneItem item = GetCurrentSceneItem();
  5665. if (!item)
  5666. return;
  5667. OpenProjector(obs_sceneitem_get_source(item), monitor,
  5668. ProjectorType::Source);
  5669. }
  5670. void OBSBasic::OpenMultiviewProjector()
  5671. {
  5672. int monitor = sender()->property("monitor").toInt();
  5673. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  5674. }
  5675. void OBSBasic::OpenSceneProjector()
  5676. {
  5677. int monitor = sender()->property("monitor").toInt();
  5678. OBSScene scene = GetCurrentScene();
  5679. if (!scene)
  5680. return;
  5681. OpenProjector(obs_scene_get_source(scene), monitor,
  5682. ProjectorType::Scene);
  5683. }
  5684. void OBSBasic::OpenStudioProgramWindow()
  5685. {
  5686. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  5687. }
  5688. void OBSBasic::OpenPreviewWindow()
  5689. {
  5690. OpenProjector(nullptr, -1, ProjectorType::Preview);
  5691. }
  5692. void OBSBasic::OpenSourceWindow()
  5693. {
  5694. OBSSceneItem item = GetCurrentSceneItem();
  5695. if (!item)
  5696. return;
  5697. OBSSource source = obs_sceneitem_get_source(item);
  5698. OpenProjector(obs_sceneitem_get_source(item), -1,
  5699. ProjectorType::Source);
  5700. }
  5701. void OBSBasic::OpenMultiviewWindow()
  5702. {
  5703. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  5704. }
  5705. void OBSBasic::OpenSceneWindow()
  5706. {
  5707. OBSScene scene = GetCurrentScene();
  5708. if (!scene)
  5709. return;
  5710. OBSSource source = obs_scene_get_source(scene);
  5711. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  5712. }
  5713. void OBSBasic::OpenSavedProjectors()
  5714. {
  5715. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5716. OpenSavedProjector(info);
  5717. }
  5718. }
  5719. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  5720. {
  5721. if (info) {
  5722. OBSProjector *projector = nullptr;
  5723. switch (info->type) {
  5724. case ProjectorType::Source:
  5725. case ProjectorType::Scene: {
  5726. OBSSource source =
  5727. obs_get_source_by_name(info->name.c_str());
  5728. if (!source)
  5729. return;
  5730. projector = OpenProjector(source, info->monitor,
  5731. info->type);
  5732. obs_source_release(source);
  5733. break;
  5734. }
  5735. default: {
  5736. projector = OpenProjector(nullptr, info->monitor,
  5737. info->type);
  5738. break;
  5739. }
  5740. }
  5741. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5742. QByteArray byteArray = QByteArray::fromBase64(
  5743. QByteArray(info->geometry.c_str()));
  5744. projector->restoreGeometry(byteArray);
  5745. if (!WindowPositionValid(projector->normalGeometry())) {
  5746. QRect rect = App()->desktop()->geometry();
  5747. projector->setGeometry(QStyle::alignedRect(
  5748. Qt::LeftToRight, Qt::AlignCenter,
  5749. size(), rect));
  5750. }
  5751. if (info->alwaysOnTopOverridden)
  5752. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  5753. true);
  5754. }
  5755. }
  5756. }
  5757. void OBSBasic::on_actionFullscreenInterface_triggered()
  5758. {
  5759. if (!isFullScreen())
  5760. showFullScreen();
  5761. else
  5762. showNormal();
  5763. }
  5764. void OBSBasic::UpdateTitleBar()
  5765. {
  5766. stringstream name;
  5767. const char *profile =
  5768. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  5769. const char *sceneCollection = config_get_string(
  5770. App()->GlobalConfig(), "Basic", "SceneCollection");
  5771. name << "OBS ";
  5772. if (previewProgramMode)
  5773. name << "Studio ";
  5774. name << App()->GetVersionString();
  5775. if (App()->IsPortableMode())
  5776. name << " - Portable Mode";
  5777. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5778. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5779. setWindowTitle(QT_UTF8(name.str().c_str()));
  5780. }
  5781. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5782. {
  5783. char profiles_path[512];
  5784. const char *profile =
  5785. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  5786. int ret;
  5787. if (!profile)
  5788. return -1;
  5789. if (!path)
  5790. return -1;
  5791. if (!file)
  5792. file = "";
  5793. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5794. if (ret <= 0)
  5795. return ret;
  5796. if (!*file)
  5797. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5798. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5799. }
  5800. void OBSBasic::on_resetUI_triggered()
  5801. {
  5802. /* prune deleted extra docks */
  5803. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5804. if (!extraDocks[i]) {
  5805. extraDocks.removeAt(i);
  5806. }
  5807. }
  5808. if (extraDocks.size()) {
  5809. QMessageBox::StandardButton button = QMessageBox::question(
  5810. this, QTStr("ResetUIWarning.Title"),
  5811. QTStr("ResetUIWarning.Text"));
  5812. if (button == QMessageBox::No)
  5813. return;
  5814. }
  5815. /* undock/hide/center extra docks */
  5816. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5817. if (extraDocks[i]) {
  5818. extraDocks[i]->setVisible(true);
  5819. extraDocks[i]->setFloating(true);
  5820. extraDocks[i]->move(frameGeometry().topLeft() +
  5821. rect().center() -
  5822. extraDocks[i]->rect().center());
  5823. extraDocks[i]->setVisible(false);
  5824. }
  5825. }
  5826. restoreState(startingDockLayout);
  5827. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5828. int cx = width();
  5829. int cy = height();
  5830. int cx22_5 = cx * 225 / 1000;
  5831. int cx5 = cx * 5 / 100;
  5832. cy = cy * 225 / 1000;
  5833. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5834. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  5835. ui->mixerDock, ui->transitionsDock,
  5836. ui->controlsDock};
  5837. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  5838. ui->scenesDock->setVisible(true);
  5839. ui->sourcesDock->setVisible(true);
  5840. ui->mixerDock->setVisible(true);
  5841. ui->transitionsDock->setVisible(true);
  5842. ui->controlsDock->setVisible(true);
  5843. statsDock->setVisible(false);
  5844. statsDock->setFloating(true);
  5845. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5846. resizeDocks(docks, sizes, Qt::Horizontal);
  5847. #endif
  5848. activateWindow();
  5849. }
  5850. void OBSBasic::on_lockUI_toggled(bool lock)
  5851. {
  5852. QDockWidget::DockWidgetFeatures features =
  5853. lock ? QDockWidget::NoDockWidgetFeatures
  5854. : (QDockWidget::DockWidgetClosable |
  5855. QDockWidget::DockWidgetMovable |
  5856. QDockWidget::DockWidgetFloatable);
  5857. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5858. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5859. ui->scenesDock->setFeatures(mainFeatures);
  5860. ui->sourcesDock->setFeatures(mainFeatures);
  5861. ui->mixerDock->setFeatures(mainFeatures);
  5862. ui->transitionsDock->setFeatures(mainFeatures);
  5863. ui->controlsDock->setFeatures(mainFeatures);
  5864. statsDock->setFeatures(features);
  5865. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5866. if (!extraDocks[i]) {
  5867. extraDocks.removeAt(i);
  5868. } else {
  5869. extraDocks[i]->setFeatures(features);
  5870. }
  5871. }
  5872. }
  5873. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5874. {
  5875. ui->sourcesToolbar->setVisible(visible);
  5876. ui->scenesToolbar->setVisible(visible);
  5877. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5878. "ShowListboxToolbars", visible);
  5879. }
  5880. void OBSBasic::ShowContextBar()
  5881. {
  5882. on_toggleContextBar_toggled(true);
  5883. }
  5884. void OBSBasic::HideContextBar()
  5885. {
  5886. on_toggleContextBar_toggled(false);
  5887. }
  5888. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  5889. {
  5890. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5891. "ShowContextToolbars", visible);
  5892. this->ui->contextContainer->setVisible(visible);
  5893. }
  5894. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5895. {
  5896. ui->statusbar->setVisible(visible);
  5897. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  5898. visible);
  5899. }
  5900. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  5901. {
  5902. ui->sources->SetIconsVisible(visible);
  5903. if (advAudioWindow != nullptr)
  5904. advAudioWindow->SetIconsVisible(visible);
  5905. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  5906. visible);
  5907. }
  5908. void OBSBasic::on_actionLockPreview_triggered()
  5909. {
  5910. ui->preview->ToggleLocked();
  5911. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5912. }
  5913. void OBSBasic::on_scalingMenu_aboutToShow()
  5914. {
  5915. obs_video_info ovi;
  5916. obs_get_video_info(&ovi);
  5917. QAction *action = ui->actionScaleCanvas;
  5918. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5919. text = text.arg(QString::number(ovi.base_width),
  5920. QString::number(ovi.base_height));
  5921. action->setText(text);
  5922. action = ui->actionScaleOutput;
  5923. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5924. text = text.arg(QString::number(ovi.output_width),
  5925. QString::number(ovi.output_height));
  5926. action->setText(text);
  5927. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5928. ovi.output_height == ovi.base_height));
  5929. UpdatePreviewScalingMenu();
  5930. }
  5931. void OBSBasic::on_actionScaleWindow_triggered()
  5932. {
  5933. ui->preview->SetFixedScaling(false);
  5934. ui->preview->ResetScrollingOffset();
  5935. emit ui->preview->DisplayResized();
  5936. }
  5937. void OBSBasic::on_actionScaleCanvas_triggered()
  5938. {
  5939. ui->preview->SetFixedScaling(true);
  5940. ui->preview->SetScalingLevel(0);
  5941. emit ui->preview->DisplayResized();
  5942. }
  5943. void OBSBasic::on_actionScaleOutput_triggered()
  5944. {
  5945. obs_video_info ovi;
  5946. obs_get_video_info(&ovi);
  5947. ui->preview->SetFixedScaling(true);
  5948. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5949. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5950. int32_t approxScalingLevel =
  5951. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5952. ui->preview->SetScalingLevel(approxScalingLevel);
  5953. ui->preview->SetScalingAmount(scalingAmount);
  5954. emit ui->preview->DisplayResized();
  5955. }
  5956. void OBSBasic::SetShowing(bool showing)
  5957. {
  5958. if (!showing && isVisible()) {
  5959. config_set_string(App()->GlobalConfig(), "BasicWindow",
  5960. "geometry",
  5961. saveGeometry().toBase64().constData());
  5962. /* hide all visible child dialogs */
  5963. visDlgPositions.clear();
  5964. if (!visDialogs.isEmpty()) {
  5965. for (QDialog *dlg : visDialogs) {
  5966. visDlgPositions.append(dlg->pos());
  5967. dlg->hide();
  5968. }
  5969. }
  5970. if (showHide)
  5971. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5972. QTimer::singleShot(250, this, SLOT(hide()));
  5973. setVisible(false);
  5974. #ifdef __APPLE__
  5975. EnableOSXDockIcon(false);
  5976. #endif
  5977. } else if (showing && !isVisible()) {
  5978. if (showHide)
  5979. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5980. QTimer::singleShot(250, this, SLOT(show()));
  5981. setVisible(true);
  5982. #ifdef __APPLE__
  5983. EnableOSXDockIcon(true);
  5984. #endif
  5985. /* raise and activate window to ensure it is on top */
  5986. raise();
  5987. activateWindow();
  5988. /* show all child dialogs that was visible earlier */
  5989. if (!visDialogs.isEmpty()) {
  5990. for (int i = 0; i < visDialogs.size(); ++i) {
  5991. QDialog *dlg = visDialogs[i];
  5992. dlg->move(visDlgPositions[i]);
  5993. dlg->show();
  5994. }
  5995. }
  5996. /* Unminimize window if it was hidden to tray instead of task
  5997. * bar. */
  5998. if (sysTrayMinimizeToTray()) {
  5999. Qt::WindowStates state;
  6000. state = windowState() & ~Qt::WindowMinimized;
  6001. state |= Qt::WindowActive;
  6002. setWindowState(state);
  6003. }
  6004. }
  6005. }
  6006. void OBSBasic::ToggleShowHide()
  6007. {
  6008. bool showing = isVisible();
  6009. if (showing) {
  6010. /* check for modal dialogs */
  6011. EnumDialogs();
  6012. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  6013. return;
  6014. }
  6015. SetShowing(!showing);
  6016. }
  6017. void OBSBasic::SystemTrayInit()
  6018. {
  6019. trayIcon.reset(new QSystemTrayIcon(
  6020. QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
  6021. this));
  6022. trayIcon->setToolTip("OBS Studio");
  6023. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  6024. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  6025. trayIcon.data());
  6026. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  6027. trayIcon.data());
  6028. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  6029. trayIcon.data());
  6030. exit = new QAction(QTStr("Exit"), trayIcon.data());
  6031. trayMenu = new QMenu;
  6032. previewProjector = new QMenu(QTStr("PreviewProjector"));
  6033. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6034. AddProjectorMenuMonitors(previewProjector, this,
  6035. SLOT(OpenPreviewProjector()));
  6036. AddProjectorMenuMonitors(studioProgramProjector, this,
  6037. SLOT(OpenStudioProgramProjector()));
  6038. trayMenu->addAction(showHide);
  6039. trayMenu->addMenu(previewProjector);
  6040. trayMenu->addMenu(studioProgramProjector);
  6041. trayMenu->addAction(sysTrayStream);
  6042. trayMenu->addAction(sysTrayRecord);
  6043. trayMenu->addAction(sysTrayReplayBuffer);
  6044. trayMenu->addAction(exit);
  6045. trayIcon->setContextMenu(trayMenu);
  6046. trayIcon->show();
  6047. if (outputHandler && !outputHandler->replayBuffer)
  6048. sysTrayReplayBuffer->setEnabled(false);
  6049. connect(trayIcon.data(),
  6050. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  6051. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  6052. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  6053. connect(sysTrayStream, SIGNAL(triggered()), this,
  6054. SLOT(on_streamButton_clicked()));
  6055. connect(sysTrayRecord, SIGNAL(triggered()), this,
  6056. SLOT(on_recordButton_clicked()));
  6057. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  6058. &OBSBasic::ReplayBufferClicked);
  6059. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  6060. }
  6061. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  6062. {
  6063. // Refresh projector list
  6064. previewProjector->clear();
  6065. studioProgramProjector->clear();
  6066. AddProjectorMenuMonitors(previewProjector, this,
  6067. SLOT(OpenPreviewProjector()));
  6068. AddProjectorMenuMonitors(studioProgramProjector, this,
  6069. SLOT(OpenStudioProgramProjector()));
  6070. if (reason == QSystemTrayIcon::Trigger) {
  6071. EnablePreviewDisplay(previewEnabled && !isVisible());
  6072. ToggleShowHide();
  6073. }
  6074. }
  6075. void OBSBasic::SysTrayNotify(const QString &text,
  6076. QSystemTrayIcon::MessageIcon n)
  6077. {
  6078. if (trayIcon && QSystemTrayIcon::supportsMessages()) {
  6079. QSystemTrayIcon::MessageIcon icon =
  6080. QSystemTrayIcon::MessageIcon(n);
  6081. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  6082. }
  6083. }
  6084. void OBSBasic::SystemTray(bool firstStarted)
  6085. {
  6086. if (!QSystemTrayIcon::isSystemTrayAvailable())
  6087. return;
  6088. if (!trayIcon && !firstStarted)
  6089. return;
  6090. bool sysTrayWhenStarted = config_get_bool(
  6091. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  6092. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6093. "SysTrayEnabled");
  6094. if (firstStarted)
  6095. SystemTrayInit();
  6096. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  6097. trayIcon->hide();
  6098. } else if ((sysTrayWhenStarted && sysTrayEnabled) ||
  6099. opt_minimize_tray) {
  6100. trayIcon->show();
  6101. if (firstStarted) {
  6102. QTimer::singleShot(50, this, SLOT(hide()));
  6103. EnablePreviewDisplay(false);
  6104. setVisible(false);
  6105. #ifdef __APPLE__
  6106. EnableOSXDockIcon(false);
  6107. #endif
  6108. opt_minimize_tray = false;
  6109. }
  6110. } else if (sysTrayEnabled) {
  6111. trayIcon->show();
  6112. } else if (!sysTrayEnabled) {
  6113. trayIcon->hide();
  6114. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  6115. trayIcon->hide();
  6116. }
  6117. if (isVisible())
  6118. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  6119. else
  6120. showHide->setText(QTStr("Basic.SystemTray.Show"));
  6121. }
  6122. bool OBSBasic::sysTrayMinimizeToTray()
  6123. {
  6124. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  6125. "SysTrayMinimizeToTray");
  6126. }
  6127. void OBSBasic::on_actionCopySource_triggered()
  6128. {
  6129. copyStrings.clear();
  6130. bool allowPastingDuplicate = true;
  6131. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  6132. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  6133. if (!item)
  6134. continue;
  6135. on_actionCopyTransform_triggered();
  6136. OBSSource source = obs_sceneitem_get_source(item);
  6137. copyStrings.push_front(obs_source_get_name(source));
  6138. copyVisible = obs_sceneitem_visible(item);
  6139. uint32_t output_flags = obs_source_get_output_flags(source);
  6140. if (output_flags & OBS_SOURCE_DO_NOT_DUPLICATE)
  6141. allowPastingDuplicate = false;
  6142. }
  6143. ui->actionPasteRef->setEnabled(true);
  6144. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6145. }
  6146. void OBSBasic::on_actionPasteRef_triggered()
  6147. {
  6148. for (auto &copyString : copyStrings) {
  6149. /* do not allow duplicate refs of the same group in the same scene */
  6150. OBSScene scene = GetCurrentScene();
  6151. if (!!obs_scene_get_group(scene, copyString))
  6152. continue;
  6153. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  6154. false);
  6155. on_actionPasteTransform_triggered();
  6156. }
  6157. }
  6158. void OBSBasic::on_actionPasteDup_triggered()
  6159. {
  6160. for (auto &copyString : copyStrings) {
  6161. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  6162. true);
  6163. on_actionPasteTransform_triggered();
  6164. }
  6165. }
  6166. void OBSBasic::AudioMixerCopyFilters()
  6167. {
  6168. QAction *action = reinterpret_cast<QAction *>(sender());
  6169. VolControl *vol = action->property("volControl").value<VolControl *>();
  6170. obs_source_t *source = vol->GetSource();
  6171. copyFiltersString = obs_source_get_name(source);
  6172. }
  6173. void OBSBasic::AudioMixerPasteFilters()
  6174. {
  6175. QAction *action = reinterpret_cast<QAction *>(sender());
  6176. VolControl *vol = action->property("volControl").value<VolControl *>();
  6177. obs_source_t *dstSource = vol->GetSource();
  6178. OBSSource source = obs_get_source_by_name(copyFiltersString);
  6179. obs_source_release(source);
  6180. if (source == dstSource)
  6181. return;
  6182. obs_source_copy_filters(dstSource, source);
  6183. }
  6184. void OBSBasic::SceneCopyFilters()
  6185. {
  6186. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  6187. }
  6188. void OBSBasic::ScenePasteFilters()
  6189. {
  6190. OBSSource source = obs_get_source_by_name(copyFiltersString);
  6191. obs_source_release(source);
  6192. OBSSource dstSource = GetCurrentSceneSource();
  6193. if (source == dstSource)
  6194. return;
  6195. obs_source_copy_filters(dstSource, source);
  6196. }
  6197. void OBSBasic::on_actionCopyFilters_triggered()
  6198. {
  6199. OBSSceneItem item = GetCurrentSceneItem();
  6200. if (!item)
  6201. return;
  6202. OBSSource source = obs_sceneitem_get_source(item);
  6203. copyFiltersString = obs_source_get_name(source);
  6204. ui->actionPasteFilters->setEnabled(true);
  6205. }
  6206. void OBSBasic::on_actionPasteFilters_triggered()
  6207. {
  6208. OBSSource source = obs_get_source_by_name(copyFiltersString);
  6209. obs_source_release(source);
  6210. OBSSceneItem sceneItem = GetCurrentSceneItem();
  6211. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  6212. if (source == dstSource)
  6213. return;
  6214. obs_source_copy_filters(dstSource, source);
  6215. }
  6216. static void ConfirmColor(SourceTree *sources, const QColor &color,
  6217. QModelIndexList selectedItems)
  6218. {
  6219. for (int x = 0; x < selectedItems.count(); x++) {
  6220. SourceTreeItem *treeItem =
  6221. sources->GetItemWidget(selectedItems[x].row());
  6222. treeItem->setStyleSheet("background: " +
  6223. color.name(QColor::HexArgb));
  6224. treeItem->style()->unpolish(treeItem);
  6225. treeItem->style()->polish(treeItem);
  6226. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  6227. obs_data_t *privData =
  6228. obs_sceneitem_get_private_settings(sceneItem);
  6229. obs_data_set_int(privData, "color-preset", 1);
  6230. obs_data_set_string(privData, "color",
  6231. QT_TO_UTF8(color.name(QColor::HexArgb)));
  6232. obs_data_release(privData);
  6233. }
  6234. }
  6235. void OBSBasic::ColorChange()
  6236. {
  6237. QModelIndexList selectedItems =
  6238. ui->sources->selectionModel()->selectedIndexes();
  6239. QAction *action = qobject_cast<QAction *>(sender());
  6240. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  6241. if (selectedItems.count() == 0)
  6242. return;
  6243. if (colorButton) {
  6244. int preset = colorButton->property("bgColor").value<int>();
  6245. for (int x = 0; x < selectedItems.count(); x++) {
  6246. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  6247. selectedItems[x].row());
  6248. treeItem->setStyleSheet("");
  6249. treeItem->setProperty("bgColor", preset);
  6250. treeItem->style()->unpolish(treeItem);
  6251. treeItem->style()->polish(treeItem);
  6252. OBSSceneItem sceneItem =
  6253. ui->sources->Get(selectedItems[x].row());
  6254. obs_data_t *privData =
  6255. obs_sceneitem_get_private_settings(sceneItem);
  6256. obs_data_set_int(privData, "color-preset", preset + 1);
  6257. obs_data_set_string(privData, "color", "");
  6258. obs_data_release(privData);
  6259. }
  6260. for (int i = 1; i < 9; i++) {
  6261. stringstream button;
  6262. button << "preset" << i;
  6263. QPushButton *cButton =
  6264. colorButton->parentWidget()
  6265. ->findChild<QPushButton *>(
  6266. button.str().c_str());
  6267. cButton->setStyleSheet("border: 1px solid black");
  6268. }
  6269. colorButton->setStyleSheet("border: 2px solid black");
  6270. } else if (action) {
  6271. int preset = action->property("bgColor").value<int>();
  6272. if (preset == 1) {
  6273. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  6274. SourceTreeItem *curTreeItem =
  6275. GetItemWidgetFromSceneItem(curSceneItem);
  6276. obs_data_t *curPrivData =
  6277. obs_sceneitem_get_private_settings(
  6278. curSceneItem);
  6279. int oldPreset =
  6280. obs_data_get_int(curPrivData, "color-preset");
  6281. const QString oldSheet = curTreeItem->styleSheet();
  6282. auto liveChangeColor = [=](const QColor &color) {
  6283. if (color.isValid()) {
  6284. curTreeItem->setStyleSheet(
  6285. "background: " +
  6286. color.name(QColor::HexArgb));
  6287. }
  6288. };
  6289. auto changedColor = [=](const QColor &color) {
  6290. if (color.isValid()) {
  6291. ConfirmColor(ui->sources, color,
  6292. selectedItems);
  6293. }
  6294. };
  6295. auto rejected = [=]() {
  6296. if (oldPreset == 1) {
  6297. curTreeItem->setStyleSheet(oldSheet);
  6298. curTreeItem->setProperty("bgColor", 0);
  6299. } else if (oldPreset == 0) {
  6300. curTreeItem->setStyleSheet(
  6301. "background: none");
  6302. curTreeItem->setProperty("bgColor", 0);
  6303. } else {
  6304. curTreeItem->setStyleSheet("");
  6305. curTreeItem->setProperty("bgColor",
  6306. oldPreset - 1);
  6307. }
  6308. curTreeItem->style()->unpolish(curTreeItem);
  6309. curTreeItem->style()->polish(curTreeItem);
  6310. };
  6311. QColorDialog::ColorDialogOptions options =
  6312. QColorDialog::ShowAlphaChannel;
  6313. const char *oldColor =
  6314. obs_data_get_string(curPrivData, "color");
  6315. const char *customColor = *oldColor != 0 ? oldColor
  6316. : "#55FF0000";
  6317. #ifndef _WIN32
  6318. options |= QColorDialog::DontUseNativeDialog;
  6319. #endif
  6320. QColorDialog *colorDialog = new QColorDialog(this);
  6321. colorDialog->setOptions(options);
  6322. colorDialog->setCurrentColor(QColor(customColor));
  6323. connect(colorDialog, &QColorDialog::currentColorChanged,
  6324. liveChangeColor);
  6325. connect(colorDialog, &QColorDialog::colorSelected,
  6326. changedColor);
  6327. connect(colorDialog, &QColorDialog::rejected, rejected);
  6328. colorDialog->open();
  6329. obs_data_release(curPrivData);
  6330. } else {
  6331. for (int x = 0; x < selectedItems.count(); x++) {
  6332. SourceTreeItem *treeItem =
  6333. ui->sources->GetItemWidget(
  6334. selectedItems[x].row());
  6335. treeItem->setStyleSheet("background: none");
  6336. treeItem->setProperty("bgColor", preset);
  6337. treeItem->style()->unpolish(treeItem);
  6338. treeItem->style()->polish(treeItem);
  6339. OBSSceneItem sceneItem = ui->sources->Get(
  6340. selectedItems[x].row());
  6341. obs_data_t *privData =
  6342. obs_sceneitem_get_private_settings(
  6343. sceneItem);
  6344. obs_data_set_int(privData, "color-preset",
  6345. preset);
  6346. obs_data_set_string(privData, "color", "");
  6347. obs_data_release(privData);
  6348. }
  6349. }
  6350. }
  6351. }
  6352. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  6353. {
  6354. int i = 0;
  6355. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  6356. OBSSceneItem item = ui->sources->Get(i);
  6357. int64_t id = obs_sceneitem_get_id(sceneItem);
  6358. while (treeItem && obs_sceneitem_get_id(item) != id) {
  6359. i++;
  6360. treeItem = ui->sources->GetItemWidget(i);
  6361. item = ui->sources->Get(i);
  6362. }
  6363. if (treeItem)
  6364. return treeItem;
  6365. return nullptr;
  6366. }
  6367. void OBSBasic::on_autoConfigure_triggered()
  6368. {
  6369. AutoConfig test(this);
  6370. test.setModal(true);
  6371. test.show();
  6372. test.exec();
  6373. }
  6374. void OBSBasic::on_stats_triggered()
  6375. {
  6376. if (!stats.isNull()) {
  6377. stats->show();
  6378. stats->raise();
  6379. return;
  6380. }
  6381. OBSBasicStats *statsDlg;
  6382. statsDlg = new OBSBasicStats(nullptr);
  6383. statsDlg->show();
  6384. stats = statsDlg;
  6385. }
  6386. void OBSBasic::on_actionShowAbout_triggered()
  6387. {
  6388. if (about)
  6389. about->close();
  6390. about = new OBSAbout(this);
  6391. about->show();
  6392. about->setAttribute(Qt::WA_DeleteOnClose, true);
  6393. }
  6394. void OBSBasic::ResizeOutputSizeOfSource()
  6395. {
  6396. if (obs_video_active())
  6397. return;
  6398. QMessageBox resize_output(this);
  6399. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  6400. QTStr("ResizeOutputSizeOfSource.Continue"));
  6401. QAbstractButton *Yes =
  6402. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  6403. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  6404. resize_output.setIcon(QMessageBox::Warning);
  6405. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  6406. resize_output.exec();
  6407. if (resize_output.clickedButton() != Yes)
  6408. return;
  6409. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  6410. int width = obs_source_get_width(source);
  6411. int height = obs_source_get_height(source);
  6412. config_set_uint(basicConfig, "Video", "BaseCX", width);
  6413. config_set_uint(basicConfig, "Video", "BaseCY", height);
  6414. config_set_uint(basicConfig, "Video", "OutputCX", width);
  6415. config_set_uint(basicConfig, "Video", "OutputCY", height);
  6416. ResetVideo();
  6417. on_actionFitToScreen_triggered();
  6418. }
  6419. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  6420. {
  6421. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  6422. action->setCheckable(true);
  6423. assignDockToggle(dock, action);
  6424. extraDocks.push_back(dock);
  6425. bool lock = ui->lockUI->isChecked();
  6426. QDockWidget::DockWidgetFeatures features =
  6427. lock ? QDockWidget::NoDockWidgetFeatures
  6428. : (QDockWidget::DockWidgetClosable |
  6429. QDockWidget::DockWidgetMovable |
  6430. QDockWidget::DockWidgetFloatable);
  6431. dock->setFeatures(features);
  6432. /* prune deleted docks */
  6433. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6434. if (!extraDocks[i]) {
  6435. extraDocks.removeAt(i);
  6436. }
  6437. }
  6438. return action;
  6439. }
  6440. OBSBasic *OBSBasic::Get()
  6441. {
  6442. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  6443. }
  6444. bool OBSBasic::StreamingActive()
  6445. {
  6446. if (!outputHandler)
  6447. return false;
  6448. return outputHandler->StreamingActive();
  6449. }
  6450. bool OBSBasic::RecordingActive()
  6451. {
  6452. if (!outputHandler)
  6453. return false;
  6454. return outputHandler->RecordingActive();
  6455. }
  6456. bool OBSBasic::ReplayBufferActive()
  6457. {
  6458. if (!outputHandler)
  6459. return false;
  6460. return outputHandler->ReplayBufferActive();
  6461. }
  6462. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  6463. : QStyledItemDelegate(parent)
  6464. {
  6465. }
  6466. void SceneRenameDelegate::setEditorData(QWidget *editor,
  6467. const QModelIndex &index) const
  6468. {
  6469. QStyledItemDelegate::setEditorData(editor, index);
  6470. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6471. if (lineEdit)
  6472. lineEdit->selectAll();
  6473. }
  6474. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  6475. {
  6476. if (event->type() == QEvent::KeyPress) {
  6477. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  6478. if (keyEvent->key() == Qt::Key_Escape) {
  6479. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6480. if (lineEdit)
  6481. lineEdit->undo();
  6482. }
  6483. }
  6484. return QStyledItemDelegate::eventFilter(editor, event);
  6485. }
  6486. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  6487. {
  6488. if (!error.isEmpty())
  6489. return;
  6490. patronJson = QT_TO_UTF8(text);
  6491. }
  6492. void OBSBasic::PauseRecording()
  6493. {
  6494. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6495. return;
  6496. obs_output_t *output = outputHandler->fileOutput;
  6497. if (obs_output_pause(output, true)) {
  6498. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  6499. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  6500. pause->blockSignals(true);
  6501. pause->setChecked(true);
  6502. pause->blockSignals(false);
  6503. ui->statusbar->RecordingPaused();
  6504. if (trayIcon)
  6505. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  6506. os_atomic_set_bool(&recording_paused, true);
  6507. if (api)
  6508. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  6509. if (os_atomic_load_bool(&replaybuf_active))
  6510. ShowReplayBufferPauseWarning();
  6511. }
  6512. }
  6513. void OBSBasic::UnpauseRecording()
  6514. {
  6515. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6516. return;
  6517. obs_output_t *output = outputHandler->fileOutput;
  6518. if (obs_output_pause(output, false)) {
  6519. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6520. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6521. pause->blockSignals(true);
  6522. pause->setChecked(false);
  6523. pause->blockSignals(false);
  6524. ui->statusbar->RecordingUnpaused();
  6525. if (trayIcon)
  6526. trayIcon->setIcon(
  6527. QIcon(":/res/images/tray_active.png"));
  6528. os_atomic_set_bool(&recording_paused, false);
  6529. if (api)
  6530. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  6531. }
  6532. }
  6533. void OBSBasic::PauseToggled()
  6534. {
  6535. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6536. return;
  6537. obs_output_t *output = outputHandler->fileOutput;
  6538. bool enable = !obs_output_paused(output);
  6539. if (enable)
  6540. PauseRecording();
  6541. else
  6542. UnpauseRecording();
  6543. }
  6544. void OBSBasic::UpdatePause(bool activate)
  6545. {
  6546. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  6547. pause.reset();
  6548. return;
  6549. }
  6550. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  6551. bool adv = astrcmpi(mode, "Advanced") == 0;
  6552. bool shared;
  6553. if (adv) {
  6554. const char *recType =
  6555. config_get_string(basicConfig, "AdvOut", "RecType");
  6556. if (astrcmpi(recType, "FFmpeg") == 0) {
  6557. shared = config_get_bool(basicConfig, "AdvOut",
  6558. "FFOutputToFile");
  6559. } else {
  6560. const char *recordEncoder = config_get_string(
  6561. basicConfig, "AdvOut", "RecEncoder");
  6562. shared = astrcmpi(recordEncoder, "none") == 0;
  6563. }
  6564. } else {
  6565. const char *quality = config_get_string(
  6566. basicConfig, "SimpleOutput", "RecQuality");
  6567. shared = strcmp(quality, "Stream") == 0;
  6568. }
  6569. if (!shared) {
  6570. pause.reset(new QPushButton());
  6571. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6572. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6573. pause->setCheckable(true);
  6574. pause->setChecked(false);
  6575. pause->setProperty("themeID",
  6576. QVariant(QStringLiteral("pauseIconSmall")));
  6577. QSizePolicy sp;
  6578. sp.setHeightForWidth(true);
  6579. pause->setSizePolicy(sp);
  6580. connect(pause.data(), &QAbstractButton::clicked, this,
  6581. &OBSBasic::PauseToggled);
  6582. ui->recordingLayout->addWidget(pause.data());
  6583. } else {
  6584. pause.reset();
  6585. }
  6586. }
  6587. void OBSBasic::UpdateReplayBuffer(bool activate)
  6588. {
  6589. if (!activate || !outputHandler ||
  6590. !outputHandler->ReplayBufferActive()) {
  6591. replay.reset();
  6592. return;
  6593. }
  6594. replay.reset(new QPushButton());
  6595. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  6596. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  6597. replay->setCheckable(true);
  6598. replay->setChecked(false);
  6599. replay->setProperty("themeID",
  6600. QVariant(QStringLiteral("replayIconSmall")));
  6601. QSizePolicy sp;
  6602. sp.setHeightForWidth(true);
  6603. replay->setSizePolicy(sp);
  6604. connect(replay.data(), &QAbstractButton::clicked, this,
  6605. &OBSBasic::ReplayBufferSave);
  6606. replayLayout->addWidget(replay.data());
  6607. }
  6608. #define MBYTE (1024ULL * 1024ULL)
  6609. #define MBYTES_LEFT_STOP_REC 50ULL
  6610. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  6611. const char *OBSBasic::GetCurrentOutputPath()
  6612. {
  6613. const char *path = nullptr;
  6614. const char *mode = config_get_string(Config(), "Output", "Mode");
  6615. if (strcmp(mode, "Advanced") == 0) {
  6616. const char *advanced_mode =
  6617. config_get_string(Config(), "AdvOut", "RecType");
  6618. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6619. path = config_get_string(Config(), "AdvOut",
  6620. "FFFilePath");
  6621. } else {
  6622. path = config_get_string(Config(), "AdvOut",
  6623. "RecFilePath");
  6624. }
  6625. } else {
  6626. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  6627. }
  6628. return path;
  6629. }
  6630. void OBSBasic::OutputPathInvalidMessage()
  6631. {
  6632. blog(LOG_ERROR, "Recording stopped because of bad output path");
  6633. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  6634. QTStr("Output.BadPath.Text"));
  6635. }
  6636. bool OBSBasic::OutputPathValid()
  6637. {
  6638. const char *path = GetCurrentOutputPath();
  6639. return path && *path && QDir(path).exists();
  6640. }
  6641. void OBSBasic::DiskSpaceMessage()
  6642. {
  6643. blog(LOG_ERROR, "Recording stopped because of low disk space");
  6644. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  6645. QTStr("Output.RecordNoSpace.Msg"));
  6646. }
  6647. bool OBSBasic::LowDiskSpace()
  6648. {
  6649. const char *path;
  6650. path = GetCurrentOutputPath();
  6651. if (!path)
  6652. return false;
  6653. uint64_t num_bytes = os_get_free_disk_space(path);
  6654. if (num_bytes < (MAX_BYTES_LEFT))
  6655. return true;
  6656. else
  6657. return false;
  6658. }
  6659. void OBSBasic::CheckDiskSpaceRemaining()
  6660. {
  6661. if (LowDiskSpace()) {
  6662. StopRecording();
  6663. StopReplayBuffer();
  6664. DiskSpaceMessage();
  6665. }
  6666. }
  6667. void OBSBasic::ScenesReordered()
  6668. {
  6669. OBSProjector::UpdateMultiviewProjectors();
  6670. }
  6671. void OBSBasic::ResetStatsHotkey()
  6672. {
  6673. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  6674. foreach(OBSBasicStats * s, list) s->Reset();
  6675. }
  6676. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  6677. {
  6678. QWidget *widget = childAt(pos);
  6679. const char *className = nullptr;
  6680. if (widget != nullptr)
  6681. className = widget->metaObject()->className();
  6682. if (!className || strstr(className, "Dock") != nullptr)
  6683. ui->viewMenuDocks->exec(mapToGlobal(pos));
  6684. }
  6685. void OBSBasic::UpdateProjectorHideCursor()
  6686. {
  6687. for (size_t i = 0; i < projectors.size(); i++)
  6688. projectors[i]->SetHideCursor();
  6689. }
  6690. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  6691. {
  6692. for (size_t i = 0; i < projectors.size(); i++)
  6693. SetAlwaysOnTop(projectors[i], top);
  6694. }
  6695. void OBSBasic::ResetProjectors()
  6696. {
  6697. obs_data_array_t *savedProjectorList = SaveProjectors();
  6698. ClearProjectors();
  6699. LoadSavedProjectors(savedProjectorList);
  6700. OpenSavedProjectors();
  6701. obs_data_array_release(savedProjectorList);
  6702. }
  6703. void OBSBasic::on_sourcePropertiesButton_clicked()
  6704. {
  6705. on_actionSourceProperties_triggered();
  6706. }
  6707. void OBSBasic::on_sourceFiltersButton_clicked()
  6708. {
  6709. OpenFilters();
  6710. }