window-basic-main.cpp 257 KB

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