window-basic-main.cpp 223 KB

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