window-basic-main.cpp 225 KB

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