window-basic-main.cpp 245 KB

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