window-basic-main.cpp 268 KB

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