window-basic-main.cpp 262 KB

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