1
0

window-basic-main.cpp 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684
  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. #if defined(_WIN32) || defined(__APPLE__)
  1657. if (App()->IsUpdaterDisabled())
  1658. ui->actionCheckForUpdates->setEnabled(false);
  1659. #endif
  1660. OnFirstLoad();
  1661. activateWindow();
  1662. #ifdef __APPLE__
  1663. QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
  1664. Qt::QueuedConnection, Q_ARG(int, 10));
  1665. #endif
  1666. }
  1667. void OBSBasic::OnFirstLoad()
  1668. {
  1669. if (api)
  1670. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1671. #if defined(BROWSER_AVAILABLE) && defined(_WIN32)
  1672. /* Attempt to load init screen if available */
  1673. if (cef) {
  1674. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1675. connect(wnit, &WhatsNewInfoThread::Result, this,
  1676. &OBSBasic::ReceivedIntroJson);
  1677. introCheckThread.reset(wnit);
  1678. introCheckThread->start();
  1679. }
  1680. #endif
  1681. Auth::Load();
  1682. bool showLogViewerOnStartup = config_get_bool(
  1683. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1684. if (showLogViewerOnStartup)
  1685. on_actionViewCurrentLog_triggered();
  1686. }
  1687. void OBSBasic::DeferredSysTrayLoad(int requeueCount)
  1688. {
  1689. if (--requeueCount > 0) {
  1690. QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
  1691. Qt::QueuedConnection,
  1692. Q_ARG(int, requeueCount));
  1693. return;
  1694. }
  1695. /* Minimizng to tray on initial startup does not work on mac
  1696. * unless it is done in the deferred load */
  1697. SystemTray(true);
  1698. }
  1699. /* shows a "what's new" page on startup of new versions using CEF */
  1700. void OBSBasic::ReceivedIntroJson(const QString &text)
  1701. {
  1702. #ifdef BROWSER_AVAILABLE
  1703. #ifdef _WIN32
  1704. if (closing)
  1705. return;
  1706. std::string err;
  1707. Json json = Json::parse(QT_TO_UTF8(text), err);
  1708. if (!err.empty())
  1709. return;
  1710. std::string info_url;
  1711. int info_increment = -1;
  1712. /* check to see if there's an info page for this version */
  1713. const Json::array &items = json.array_items();
  1714. for (const Json &item : items) {
  1715. const std::string &version = item["version"].string_value();
  1716. const std::string &url = item["url"].string_value();
  1717. int increment = item["increment"].int_value();
  1718. int rc = item["RC"].int_value();
  1719. int major = 0;
  1720. int minor = 0;
  1721. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1722. #if OBS_RELEASE_CANDIDATE > 0
  1723. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1724. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1725. rc == OBS_RELEASE_CANDIDATE) {
  1726. #else
  1727. if (major == LIBOBS_API_MAJOR_VER &&
  1728. minor == LIBOBS_API_MINOR_VER && rc == 0) {
  1729. #endif
  1730. info_url = url;
  1731. info_increment = increment;
  1732. }
  1733. }
  1734. /* this version was not found, or no info for this version */
  1735. if (info_increment == -1) {
  1736. return;
  1737. }
  1738. #if OBS_RELEASE_CANDIDATE > 0
  1739. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1740. "LastRCVersion");
  1741. #else
  1742. uint32_t lastVersion =
  1743. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  1744. #endif
  1745. int current_version_increment = -1;
  1746. #if OBS_RELEASE_CANDIDATE > 0
  1747. if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
  1748. #else
  1749. if ((lastVersion & ~0xFFFF) < (LIBOBS_API_VER & ~0xFFFF)) {
  1750. #endif
  1751. config_set_int(App()->GlobalConfig(), "General",
  1752. "InfoIncrement", -1);
  1753. } else {
  1754. current_version_increment = config_get_int(
  1755. App()->GlobalConfig(), "General", "InfoIncrement");
  1756. }
  1757. if (info_increment <= current_version_increment) {
  1758. return;
  1759. }
  1760. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  1761. info_increment);
  1762. /* Don't show What's New dialog for new users */
  1763. #if !defined(OBS_RELEASE_CANDIDATE) || OBS_RELEASE_CANDIDATE == 0
  1764. if (!lastVersion) {
  1765. return;
  1766. }
  1767. #endif
  1768. cef->init_browser();
  1769. WhatsNewBrowserInitThread *wnbit =
  1770. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  1771. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  1772. &OBSBasic::ShowWhatsNew);
  1773. whatsNewInitThread.reset(wnbit);
  1774. whatsNewInitThread->start();
  1775. #else
  1776. UNUSED_PARAMETER(text);
  1777. #endif
  1778. #else
  1779. UNUSED_PARAMETER(text);
  1780. #endif
  1781. }
  1782. void OBSBasic::ShowWhatsNew(const QString &url)
  1783. {
  1784. #ifdef BROWSER_AVAILABLE
  1785. #ifdef _WIN32
  1786. if (closing)
  1787. return;
  1788. std::string info_url = QT_TO_UTF8(url);
  1789. QDialog *dlg = new QDialog(this);
  1790. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1791. dlg->setWindowTitle("What's New");
  1792. dlg->resize(700, 600);
  1793. Qt::WindowFlags flags = dlg->windowFlags();
  1794. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1795. dlg->setWindowFlags(flags & (~helpFlag));
  1796. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1797. if (!cefWidget) {
  1798. return;
  1799. }
  1800. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  1801. SLOT(setWindowTitle(const QString &)));
  1802. QPushButton *close = new QPushButton(QTStr("Close"));
  1803. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  1804. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1805. bottomLayout->addStretch();
  1806. bottomLayout->addWidget(close);
  1807. bottomLayout->addStretch();
  1808. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1809. topLayout->addWidget(cefWidget);
  1810. topLayout->addLayout(bottomLayout);
  1811. dlg->show();
  1812. #else
  1813. UNUSED_PARAMETER(url);
  1814. #endif
  1815. #else
  1816. UNUSED_PARAMETER(url);
  1817. #endif
  1818. }
  1819. void OBSBasic::UpdateMultiviewProjectorMenu()
  1820. {
  1821. multiviewProjectorMenu->clear();
  1822. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1823. SLOT(OpenMultiviewProjector()));
  1824. }
  1825. void OBSBasic::InitHotkeys()
  1826. {
  1827. ProfileScope("OBSBasic::InitHotkeys");
  1828. struct obs_hotkeys_translations t = {};
  1829. t.insert = Str("Hotkeys.Insert");
  1830. t.del = Str("Hotkeys.Delete");
  1831. t.home = Str("Hotkeys.Home");
  1832. t.end = Str("Hotkeys.End");
  1833. t.page_up = Str("Hotkeys.PageUp");
  1834. t.page_down = Str("Hotkeys.PageDown");
  1835. t.num_lock = Str("Hotkeys.NumLock");
  1836. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1837. t.caps_lock = Str("Hotkeys.CapsLock");
  1838. t.backspace = Str("Hotkeys.Backspace");
  1839. t.tab = Str("Hotkeys.Tab");
  1840. t.print = Str("Hotkeys.Print");
  1841. t.pause = Str("Hotkeys.Pause");
  1842. t.left = Str("Hotkeys.Left");
  1843. t.right = Str("Hotkeys.Right");
  1844. t.up = Str("Hotkeys.Up");
  1845. t.down = Str("Hotkeys.Down");
  1846. #ifdef _WIN32
  1847. t.meta = Str("Hotkeys.Windows");
  1848. #else
  1849. t.meta = Str("Hotkeys.Super");
  1850. #endif
  1851. t.menu = Str("Hotkeys.Menu");
  1852. t.space = Str("Hotkeys.Space");
  1853. t.numpad_num = Str("Hotkeys.NumpadNum");
  1854. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1855. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1856. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1857. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1858. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1859. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1860. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1861. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1862. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1863. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1864. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1865. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1866. t.mouse_num = Str("Hotkeys.MouseButton");
  1867. t.escape = Str("Hotkeys.Escape");
  1868. obs_hotkeys_set_translations(&t);
  1869. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1870. Str("Push-to-mute"),
  1871. Str("Push-to-talk"));
  1872. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  1873. Str("SceneItemHide"));
  1874. obs_hotkey_enable_callback_rerouting(true);
  1875. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1876. }
  1877. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1878. {
  1879. obs_hotkey_trigger_routed_callback(id, pressed);
  1880. }
  1881. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1882. {
  1883. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1884. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1885. Q_ARG(obs_hotkey_id, id),
  1886. Q_ARG(bool, pressed));
  1887. }
  1888. void OBSBasic::CreateHotkeys()
  1889. {
  1890. ProfileScope("OBSBasic::CreateHotkeys");
  1891. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  1892. const char *info =
  1893. config_get_string(basicConfig, "Hotkeys", name);
  1894. if (!info)
  1895. return {};
  1896. obs_data_t *data = obs_data_create_from_json(info);
  1897. if (!data)
  1898. return {};
  1899. OBSData res = data;
  1900. obs_data_release(data);
  1901. return res;
  1902. };
  1903. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  1904. obs_data_array_t *array =
  1905. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1906. obs_hotkey_load(id, array);
  1907. obs_data_array_release(array);
  1908. };
  1909. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1910. const char *name1) {
  1911. obs_data_array_t *array0 =
  1912. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1913. obs_data_array_t *array1 =
  1914. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1915. obs_hotkey_pair_load(id, array0, array1);
  1916. obs_data_array_release(array0);
  1917. obs_data_array_release(array1);
  1918. };
  1919. #define MAKE_CALLBACK(pred, method, log_action) \
  1920. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  1921. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  1922. if ((pred) && pressed) { \
  1923. blog(LOG_INFO, log_action " due to hotkey"); \
  1924. method(); \
  1925. return true; \
  1926. } \
  1927. return false; \
  1928. }
  1929. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1930. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  1931. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  1932. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1933. basic.ui->streamButton->isEnabled(),
  1934. basic.StartStreaming, "Starting stream"),
  1935. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1936. basic.ui->streamButton->isEnabled(),
  1937. basic.StopStreaming, "Stopping stream"),
  1938. this, this);
  1939. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  1940. "OBSBasic.StopStreaming");
  1941. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  1942. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1943. if (basic.outputHandler->StreamingActive() && pressed) {
  1944. basic.ForceStopStreaming();
  1945. }
  1946. };
  1947. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1948. "OBSBasic.ForceStopStreaming",
  1949. Str("Basic.Main.ForceStopStreaming"), cb, this);
  1950. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  1951. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1952. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  1953. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  1954. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1955. !basic.ui->recordButton->isChecked(),
  1956. basic.StartRecording, "Starting recording"),
  1957. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1958. basic.ui->recordButton->isChecked(),
  1959. basic.StopRecording, "Stopping recording"),
  1960. this, this);
  1961. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  1962. "OBSBasic.StopRecording");
  1963. pauseHotkeys = obs_hotkey_pair_register_frontend(
  1964. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  1965. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  1966. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  1967. basic.PauseRecording, "Pausing recording"),
  1968. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  1969. basic.UnpauseRecording, "Unpausing recording"),
  1970. this, this);
  1971. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  1972. "OBSBasic.UnpauseRecording");
  1973. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1974. "OBSBasic.StartReplayBuffer",
  1975. Str("Basic.Main.StartReplayBuffer"),
  1976. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  1977. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1978. basic.StartReplayBuffer,
  1979. "Starting replay buffer"),
  1980. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1981. basic.StopReplayBuffer, "Stopping replay buffer"),
  1982. this, this);
  1983. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  1984. "OBSBasic.StopReplayBuffer");
  1985. if (vcamEnabled) {
  1986. vcamHotkeys = obs_hotkey_pair_register_frontend(
  1987. "OBSBasic.StartVirtualCam",
  1988. Str("Basic.Main.StartVirtualCam"),
  1989. "OBSBasic.StopVirtualCam",
  1990. Str("Basic.Main.StopVirtualCam"),
  1991. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  1992. basic.StartVirtualCam,
  1993. "Starting virtual camera"),
  1994. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  1995. basic.StopVirtualCam,
  1996. "Stopping virtual camera"),
  1997. this, this);
  1998. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  1999. "OBSBasic.StopVirtualCam");
  2000. }
  2001. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2002. "OBSBasic.EnablePreview",
  2003. Str("Basic.Main.PreviewConextMenu.Enable"),
  2004. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2005. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2006. "Enabling preview"),
  2007. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2008. "Disabling preview"),
  2009. this, this);
  2010. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2011. "OBSBasic.DisablePreview");
  2012. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2013. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2014. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2015. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2016. basic.ShowContextBar, "Showing Context Bar"),
  2017. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2018. basic.HideContextBar, "Hiding Context Bar"),
  2019. this, this);
  2020. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2021. "OBSBasic.HideContextBar");
  2022. #undef MAKE_CALLBACK
  2023. auto togglePreviewProgram = [](void *data, obs_hotkey_id,
  2024. obs_hotkey_t *, bool pressed) {
  2025. if (pressed)
  2026. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2027. "on_modeSwitch_clicked",
  2028. Qt::QueuedConnection);
  2029. };
  2030. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  2031. "OBSBasic.TogglePreviewProgram",
  2032. Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
  2033. this);
  2034. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  2035. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2036. bool pressed) {
  2037. if (pressed)
  2038. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2039. "TransitionClicked",
  2040. Qt::QueuedConnection);
  2041. };
  2042. transitionHotkey = obs_hotkey_register_frontend(
  2043. "OBSBasic.Transition", Str("Transition"), transition, this);
  2044. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2045. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2046. bool pressed) {
  2047. if (pressed)
  2048. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2049. "ResetStatsHotkey",
  2050. Qt::QueuedConnection);
  2051. };
  2052. statsHotkey = obs_hotkey_register_frontend(
  2053. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2054. resetStats, this);
  2055. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2056. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2057. bool pressed) {
  2058. if (pressed)
  2059. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2060. "Screenshot",
  2061. Qt::QueuedConnection);
  2062. };
  2063. screenshotHotkey = obs_hotkey_register_frontend(
  2064. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2065. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2066. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2067. bool pressed) {
  2068. if (pressed)
  2069. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2070. "ScreenshotSelectedSource",
  2071. Qt::QueuedConnection);
  2072. };
  2073. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2074. "OBSBasic.SelectedSourceScreenshot",
  2075. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2076. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2077. }
  2078. void OBSBasic::ClearHotkeys()
  2079. {
  2080. obs_hotkey_pair_unregister(streamingHotkeys);
  2081. obs_hotkey_pair_unregister(recordingHotkeys);
  2082. obs_hotkey_pair_unregister(pauseHotkeys);
  2083. obs_hotkey_pair_unregister(replayBufHotkeys);
  2084. obs_hotkey_pair_unregister(vcamHotkeys);
  2085. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2086. obs_hotkey_pair_unregister(contextBarHotkeys);
  2087. obs_hotkey_unregister(forceStreamingStopHotkey);
  2088. obs_hotkey_unregister(togglePreviewProgramHotkey);
  2089. obs_hotkey_unregister(transitionHotkey);
  2090. obs_hotkey_unregister(statsHotkey);
  2091. obs_hotkey_unregister(screenshotHotkey);
  2092. obs_hotkey_unregister(sourceScreenshotHotkey);
  2093. }
  2094. OBSBasic::~OBSBasic()
  2095. {
  2096. /* clear out UI event queue */
  2097. QApplication::sendPostedEvents(App());
  2098. if (updateCheckThread && updateCheckThread->isRunning())
  2099. updateCheckThread->wait();
  2100. delete screenshotData;
  2101. delete multiviewProjectorMenu;
  2102. delete previewProjector;
  2103. delete studioProgramProjector;
  2104. delete previewProjectorSource;
  2105. delete previewProjectorMain;
  2106. delete sourceProjector;
  2107. delete sceneProjectorMenu;
  2108. delete scaleFilteringMenu;
  2109. delete colorMenu;
  2110. delete colorWidgetAction;
  2111. delete colorSelect;
  2112. delete deinterlaceMenu;
  2113. delete perSceneTransitionMenu;
  2114. delete shortcutFilter;
  2115. delete trayMenu;
  2116. delete programOptions;
  2117. delete program;
  2118. /* XXX: any obs data must be released before calling obs_shutdown.
  2119. * currently, we can't automate this with C++ RAII because of the
  2120. * delicate nature of obs_shutdown needing to be freed before the UI
  2121. * can be freed, and we have no control over the destruction order of
  2122. * the Qt UI stuff, so we have to manually clear any references to
  2123. * libobs. */
  2124. delete cpuUsageTimer;
  2125. os_cpu_usage_info_destroy(cpuUsageInfo);
  2126. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2127. ClearHotkeys();
  2128. service = nullptr;
  2129. outputHandler.reset();
  2130. if (interaction)
  2131. delete interaction;
  2132. if (properties)
  2133. delete properties;
  2134. if (filters)
  2135. delete filters;
  2136. if (transformWindow)
  2137. delete transformWindow;
  2138. if (advAudioWindow)
  2139. delete advAudioWindow;
  2140. if (about)
  2141. delete about;
  2142. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2143. OBSBasic::RenderMain, this);
  2144. obs_enter_graphics();
  2145. gs_vertexbuffer_destroy(box);
  2146. gs_vertexbuffer_destroy(boxLeft);
  2147. gs_vertexbuffer_destroy(boxTop);
  2148. gs_vertexbuffer_destroy(boxRight);
  2149. gs_vertexbuffer_destroy(boxBottom);
  2150. gs_vertexbuffer_destroy(circle);
  2151. gs_vertexbuffer_destroy(actionSafeMargin);
  2152. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2153. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2154. gs_vertexbuffer_destroy(leftLine);
  2155. gs_vertexbuffer_destroy(topLine);
  2156. gs_vertexbuffer_destroy(rightLine);
  2157. obs_leave_graphics();
  2158. /* When shutting down, sometimes source references can get in to the
  2159. * event queue, and if we don't forcibly process those events they
  2160. * won't get processed until after obs_shutdown has been called. I
  2161. * really wish there were a more elegant way to deal with this via C++,
  2162. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2163. * normal C++ behavior for your data to be freed in the order that you
  2164. * expect or want it to. */
  2165. QApplication::sendPostedEvents(this);
  2166. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2167. LIBOBS_API_VER);
  2168. #if OBS_RELEASE_CANDIDATE > 0
  2169. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2170. OBS_RELEASE_CANDIDATE_VER);
  2171. #endif
  2172. bool alwaysOnTop = IsAlwaysOnTop(this);
  2173. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2174. previewEnabled);
  2175. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2176. alwaysOnTop);
  2177. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2178. "SceneDuplicationMode", sceneDuplicationMode);
  2179. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2180. swapScenesMode);
  2181. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2182. "EditPropertiesMode", editPropertiesMode);
  2183. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2184. "PreviewProgramMode", IsPreviewProgramMode());
  2185. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2186. ui->lockUI->isChecked());
  2187. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2188. #ifdef _WIN32
  2189. uint32_t winVer = GetWindowsVersion();
  2190. if (winVer > 0 && winVer < 0x602) {
  2191. bool disableAero =
  2192. config_get_bool(basicConfig, "Video", "DisableAero");
  2193. if (disableAero) {
  2194. SetAeroEnabled(true);
  2195. }
  2196. }
  2197. #endif
  2198. #ifdef BROWSER_AVAILABLE
  2199. DestroyPanelCookieManager();
  2200. delete cef;
  2201. cef = nullptr;
  2202. #endif
  2203. }
  2204. void OBSBasic::SaveProjectNow()
  2205. {
  2206. if (disableSaving)
  2207. return;
  2208. projectChanged = true;
  2209. SaveProjectDeferred();
  2210. }
  2211. void OBSBasic::SaveProject()
  2212. {
  2213. if (disableSaving)
  2214. return;
  2215. projectChanged = true;
  2216. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2217. Qt::QueuedConnection);
  2218. }
  2219. void OBSBasic::SaveProjectDeferred()
  2220. {
  2221. if (disableSaving)
  2222. return;
  2223. if (!projectChanged)
  2224. return;
  2225. projectChanged = false;
  2226. const char *sceneCollection = config_get_string(
  2227. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2228. char savePath[1024];
  2229. char fileName[1024];
  2230. int ret;
  2231. if (!sceneCollection)
  2232. return;
  2233. ret = snprintf(fileName, sizeof(fileName),
  2234. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2235. if (ret <= 0)
  2236. return;
  2237. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2238. if (ret <= 0)
  2239. return;
  2240. Save(savePath);
  2241. }
  2242. OBSSource OBSBasic::GetProgramSource()
  2243. {
  2244. return OBSGetStrongRef(programScene);
  2245. }
  2246. OBSScene OBSBasic::GetCurrentScene()
  2247. {
  2248. QListWidgetItem *item = ui->scenes->currentItem();
  2249. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  2250. }
  2251. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2252. {
  2253. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2254. }
  2255. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2256. {
  2257. return ui->sources->Get(GetTopSelectedSourceItem());
  2258. }
  2259. void OBSBasic::UpdatePreviewScalingMenu()
  2260. {
  2261. bool fixedScaling = ui->preview->IsFixedScaling();
  2262. float scalingAmount = ui->preview->GetScalingAmount();
  2263. if (!fixedScaling) {
  2264. ui->actionScaleWindow->setChecked(true);
  2265. ui->actionScaleCanvas->setChecked(false);
  2266. ui->actionScaleOutput->setChecked(false);
  2267. return;
  2268. }
  2269. obs_video_info ovi;
  2270. obs_get_video_info(&ovi);
  2271. ui->actionScaleWindow->setChecked(false);
  2272. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2273. ui->actionScaleOutput->setChecked(scalingAmount ==
  2274. float(ovi.output_width) /
  2275. float(ovi.base_width));
  2276. }
  2277. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2278. {
  2279. bool closed = true;
  2280. if (interaction)
  2281. closed = interaction->close();
  2282. if (!closed)
  2283. return;
  2284. interaction = new OBSBasicInteraction(this, source);
  2285. interaction->Init();
  2286. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2287. }
  2288. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2289. {
  2290. bool closed = true;
  2291. if (properties)
  2292. closed = properties->close();
  2293. if (!closed)
  2294. return;
  2295. properties = new OBSBasicProperties(this, source);
  2296. properties->Init();
  2297. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2298. }
  2299. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2300. {
  2301. bool closed = true;
  2302. if (filters)
  2303. closed = filters->close();
  2304. if (!closed)
  2305. return;
  2306. filters = new OBSBasicFilters(this, source);
  2307. filters->Init();
  2308. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2309. }
  2310. /* Qt callbacks for invokeMethod */
  2311. void OBSBasic::AddScene(OBSSource source)
  2312. {
  2313. const char *name = obs_source_get_name(source);
  2314. obs_scene_t *scene = obs_scene_from_source(source);
  2315. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2316. SetOBSRef(item, OBSScene(scene));
  2317. ui->scenes->addItem(item);
  2318. obs_hotkey_register_source(
  2319. source, "OBSBasic.SelectScene",
  2320. Str("Basic.Hotkeys.SelectScene"),
  2321. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2322. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2323. App()->GetMainWindow());
  2324. auto potential_source =
  2325. static_cast<obs_source_t *>(data);
  2326. auto source = obs_source_get_ref(potential_source);
  2327. if (source && pressed)
  2328. main->SetCurrentScene(source);
  2329. obs_source_release(source);
  2330. },
  2331. static_cast<obs_source_t *>(source));
  2332. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2333. SignalContainer<OBSScene> container;
  2334. container.ref = scene;
  2335. container.handlers.assign({
  2336. std::make_shared<OBSSignal>(handler, "item_add",
  2337. OBSBasic::SceneItemAdded, this),
  2338. std::make_shared<OBSSignal>(handler, "reorder",
  2339. OBSBasic::SceneReordered, this),
  2340. std::make_shared<OBSSignal>(handler, "refresh",
  2341. OBSBasic::SceneRefreshed, this),
  2342. });
  2343. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2344. QVariant::fromValue(container));
  2345. /* if the scene already has items (a duplicated scene) add them */
  2346. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2347. AddSceneItem(item);
  2348. };
  2349. using addSceneItem_t = decltype(addSceneItem);
  2350. obs_scene_enum_items(
  2351. scene,
  2352. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2353. addSceneItem_t *func;
  2354. func = reinterpret_cast<addSceneItem_t *>(param);
  2355. (*func)(item);
  2356. return true;
  2357. },
  2358. &addSceneItem);
  2359. SaveProject();
  2360. if (!disableSaving) {
  2361. obs_source_t *source = obs_scene_get_source(scene);
  2362. blog(LOG_INFO, "User added scene '%s'",
  2363. obs_source_get_name(source));
  2364. OBSProjector::UpdateMultiviewProjectors();
  2365. }
  2366. if (api)
  2367. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2368. }
  2369. void OBSBasic::RemoveScene(OBSSource source)
  2370. {
  2371. obs_scene_t *scene = obs_scene_from_source(source);
  2372. QListWidgetItem *sel = nullptr;
  2373. int count = ui->scenes->count();
  2374. for (int i = 0; i < count; i++) {
  2375. auto item = ui->scenes->item(i);
  2376. auto cur_scene = GetOBSRef<OBSScene>(item);
  2377. if (cur_scene != scene)
  2378. continue;
  2379. sel = item;
  2380. break;
  2381. }
  2382. if (sel != nullptr) {
  2383. if (sel == ui->scenes->currentItem())
  2384. ui->sources->Clear();
  2385. delete sel;
  2386. }
  2387. SaveProject();
  2388. if (!disableSaving) {
  2389. blog(LOG_INFO, "User Removed scene '%s'",
  2390. obs_source_get_name(source));
  2391. OBSProjector::UpdateMultiviewProjectors();
  2392. }
  2393. if (api)
  2394. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2395. }
  2396. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2397. {
  2398. obs_sceneitem_t *selectedItem =
  2399. reinterpret_cast<obs_sceneitem_t *>(param);
  2400. if (obs_sceneitem_is_group(item))
  2401. obs_sceneitem_group_enum_items(item, select_one, param);
  2402. obs_sceneitem_select(item, (selectedItem == item));
  2403. UNUSED_PARAMETER(scene);
  2404. return true;
  2405. }
  2406. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2407. {
  2408. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2409. if (GetCurrentScene() == scene)
  2410. ui->sources->Add(item);
  2411. SaveProject();
  2412. if (!disableSaving) {
  2413. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2414. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2415. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2416. obs_source_get_name(itemSource),
  2417. obs_source_get_id(itemSource),
  2418. obs_source_get_name(sceneSource));
  2419. obs_scene_enum_items(scene, select_one,
  2420. (obs_sceneitem_t *)item);
  2421. }
  2422. }
  2423. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2424. const QString &prevName)
  2425. {
  2426. QList<QListWidgetItem *> items =
  2427. listWidget->findItems(prevName, Qt::MatchExactly);
  2428. for (int i = 0; i < items.count(); i++)
  2429. items[i]->setText(newName);
  2430. }
  2431. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2432. QString prevName)
  2433. {
  2434. RenameListValues(ui->scenes, newName, prevName);
  2435. for (size_t i = 0; i < volumes.size(); i++) {
  2436. if (volumes[i]->GetName().compare(prevName) == 0)
  2437. volumes[i]->SetName(newName);
  2438. }
  2439. for (size_t i = 0; i < projectors.size(); i++) {
  2440. if (projectors[i]->GetSource() == source)
  2441. projectors[i]->RenameProjector(prevName, newName);
  2442. }
  2443. SaveProject();
  2444. obs_scene_t *scene = obs_scene_from_source(source);
  2445. if (scene)
  2446. OBSProjector::UpdateMultiviewProjectors();
  2447. UpdateContextBar();
  2448. }
  2449. void OBSBasic::ClearContextBar()
  2450. {
  2451. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2452. if (la) {
  2453. delete la->widget();
  2454. ui->emptySpace->layout()->removeItem(la);
  2455. }
  2456. }
  2457. static bool is_network_media_source(obs_source_t *source, const char *id)
  2458. {
  2459. if (strcmp(id, "ffmpeg_source") != 0)
  2460. return false;
  2461. obs_data_t *s = obs_source_get_settings(source);
  2462. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2463. obs_data_release(s);
  2464. return !is_local_file;
  2465. }
  2466. void OBSBasic::UpdateContextBarDeferred(bool force)
  2467. {
  2468. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2469. Qt::QueuedConnection, Q_ARG(bool, force));
  2470. }
  2471. void OBSBasic::UpdateContextBar(bool force)
  2472. {
  2473. if (!ui->contextContainer->isVisible() && !force)
  2474. return;
  2475. OBSSceneItem item = GetCurrentSceneItem();
  2476. ClearContextBar();
  2477. if (item) {
  2478. obs_source_t *source = obs_sceneitem_get_source(item);
  2479. const char *id = obs_source_get_unversioned_id(source);
  2480. uint32_t flags = obs_source_get_output_flags(source);
  2481. ui->sourceInteractButton->setVisible(flags &
  2482. OBS_SOURCE_INTERACTION);
  2483. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2484. if (!is_network_media_source(source, id)) {
  2485. MediaControls *mediaControls =
  2486. new MediaControls(ui->emptySpace);
  2487. mediaControls->SetSource(source);
  2488. ui->emptySpace->layout()->addWidget(
  2489. mediaControls);
  2490. }
  2491. } else if (strcmp(id, "browser_source") == 0) {
  2492. BrowserToolbar *c =
  2493. new BrowserToolbar(ui->emptySpace, source);
  2494. ui->emptySpace->layout()->addWidget(c);
  2495. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2496. strcmp(id, "wasapi_output_capture") == 0 ||
  2497. strcmp(id, "coreaudio_input_capture") == 0 ||
  2498. strcmp(id, "coreaudio_output_capture") == 0 ||
  2499. strcmp(id, "pulse_input_capture") == 0 ||
  2500. strcmp(id, "pulse_output_capture") == 0 ||
  2501. strcmp(id, "alsa_input_capture") == 0) {
  2502. AudioCaptureToolbar *c =
  2503. new AudioCaptureToolbar(ui->emptySpace, source);
  2504. c->Init();
  2505. ui->emptySpace->layout()->addWidget(c);
  2506. } else if (strcmp(id, "window_capture") == 0 ||
  2507. strcmp(id, "xcomposite_input") == 0) {
  2508. WindowCaptureToolbar *c = new WindowCaptureToolbar(
  2509. ui->emptySpace, source);
  2510. c->Init();
  2511. ui->emptySpace->layout()->addWidget(c);
  2512. } else if (strcmp(id, "monitor_capture") == 0 ||
  2513. strcmp(id, "display_capture") == 0 ||
  2514. strcmp(id, "xshm_input") == 0) {
  2515. DisplayCaptureToolbar *c = new DisplayCaptureToolbar(
  2516. ui->emptySpace, source);
  2517. c->Init();
  2518. ui->emptySpace->layout()->addWidget(c);
  2519. } else if (strcmp(id, "dshow_input") == 0) {
  2520. DeviceCaptureToolbar *c = new DeviceCaptureToolbar(
  2521. ui->emptySpace, source);
  2522. ui->emptySpace->layout()->addWidget(c);
  2523. } else if (strcmp(id, "game_capture") == 0) {
  2524. GameCaptureToolbar *c =
  2525. new GameCaptureToolbar(ui->emptySpace, source);
  2526. ui->emptySpace->layout()->addWidget(c);
  2527. } else if (strcmp(id, "image_source") == 0) {
  2528. ImageSourceToolbar *c =
  2529. new ImageSourceToolbar(ui->emptySpace, source);
  2530. ui->emptySpace->layout()->addWidget(c);
  2531. } else if (strcmp(id, "color_source") == 0) {
  2532. ColorSourceToolbar *c =
  2533. new ColorSourceToolbar(ui->emptySpace, source);
  2534. ui->emptySpace->layout()->addWidget(c);
  2535. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2536. strcmp(id, "text_gdiplus") == 0) {
  2537. TextSourceToolbar *c =
  2538. new TextSourceToolbar(ui->emptySpace, source);
  2539. ui->emptySpace->layout()->addWidget(c);
  2540. }
  2541. QIcon icon;
  2542. if (strcmp(id, "scene") == 0)
  2543. icon = GetSceneIcon();
  2544. else if (strcmp(id, "group") == 0)
  2545. icon = GetGroupIcon();
  2546. else
  2547. icon = GetSourceIcon(id);
  2548. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2549. ui->contextSourceIcon->setPixmap(pixmap);
  2550. ui->contextSourceIcon->show();
  2551. const char *name = obs_source_get_name(source);
  2552. ui->contextSourceLabel->setText(name);
  2553. ui->sourceFiltersButton->setEnabled(true);
  2554. ui->sourcePropertiesButton->setEnabled(
  2555. obs_source_configurable(source));
  2556. } else {
  2557. ui->contextSourceIcon->hide();
  2558. ui->contextSourceLabel->setText(
  2559. QTStr("ContextBar.NoSelectedSource"));
  2560. ui->sourceFiltersButton->setEnabled(false);
  2561. ui->sourcePropertiesButton->setEnabled(false);
  2562. ui->sourceInteractButton->setVisible(false);
  2563. }
  2564. }
  2565. static inline bool SourceMixerHidden(obs_source_t *source)
  2566. {
  2567. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2568. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2569. obs_data_release(priv_settings);
  2570. return hidden;
  2571. }
  2572. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2573. {
  2574. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2575. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2576. obs_data_release(priv_settings);
  2577. }
  2578. void OBSBasic::GetAudioSourceFilters()
  2579. {
  2580. QAction *action = reinterpret_cast<QAction *>(sender());
  2581. VolControl *vol = action->property("volControl").value<VolControl *>();
  2582. obs_source_t *source = vol->GetSource();
  2583. CreateFiltersWindow(source);
  2584. }
  2585. void OBSBasic::GetAudioSourceProperties()
  2586. {
  2587. QAction *action = reinterpret_cast<QAction *>(sender());
  2588. VolControl *vol = action->property("volControl").value<VolControl *>();
  2589. obs_source_t *source = vol->GetSource();
  2590. CreatePropertiesWindow(source);
  2591. }
  2592. void OBSBasic::HideAudioControl()
  2593. {
  2594. QAction *action = reinterpret_cast<QAction *>(sender());
  2595. VolControl *vol = action->property("volControl").value<VolControl *>();
  2596. obs_source_t *source = vol->GetSource();
  2597. if (!SourceMixerHidden(source)) {
  2598. SetSourceMixerHidden(source, true);
  2599. DeactivateAudioSource(source);
  2600. }
  2601. }
  2602. void OBSBasic::UnhideAllAudioControls()
  2603. {
  2604. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2605. {
  2606. if (!obs_source_active(source))
  2607. return true;
  2608. if (!SourceMixerHidden(source))
  2609. return true;
  2610. SetSourceMixerHidden(source, false);
  2611. ActivateAudioSource(source);
  2612. return true;
  2613. };
  2614. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2615. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2616. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2617. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2618. }
  2619. void OBSBasic::ToggleHideMixer()
  2620. {
  2621. OBSSceneItem item = GetCurrentSceneItem();
  2622. OBSSource source = obs_sceneitem_get_source(item);
  2623. if (!SourceMixerHidden(source)) {
  2624. SetSourceMixerHidden(source, true);
  2625. DeactivateAudioSource(source);
  2626. } else {
  2627. SetSourceMixerHidden(source, false);
  2628. ActivateAudioSource(source);
  2629. }
  2630. }
  2631. void OBSBasic::MixerRenameSource()
  2632. {
  2633. QAction *action = reinterpret_cast<QAction *>(sender());
  2634. VolControl *vol = action->property("volControl").value<VolControl *>();
  2635. OBSSource source = vol->GetSource();
  2636. const char *prevName = obs_source_get_name(source);
  2637. for (;;) {
  2638. string name;
  2639. bool accepted = NameDialog::AskForName(
  2640. this, QTStr("Basic.Main.MixerRename.Title"),
  2641. QTStr("Basic.Main.MixerRename.Text"), name,
  2642. QT_UTF8(prevName));
  2643. if (!accepted)
  2644. return;
  2645. if (name.empty()) {
  2646. OBSMessageBox::warning(this,
  2647. QTStr("NoNameEntered.Title"),
  2648. QTStr("NoNameEntered.Text"));
  2649. continue;
  2650. }
  2651. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2652. obs_source_release(sourceTest);
  2653. if (sourceTest) {
  2654. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2655. QTStr("NameExists.Text"));
  2656. continue;
  2657. }
  2658. obs_source_set_name(source, name.c_str());
  2659. break;
  2660. }
  2661. }
  2662. static inline bool SourceVolumeLocked(obs_source_t *source)
  2663. {
  2664. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2665. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2666. obs_data_release(priv_settings);
  2667. return lock;
  2668. }
  2669. void OBSBasic::LockVolumeControl(bool lock)
  2670. {
  2671. QAction *action = reinterpret_cast<QAction *>(sender());
  2672. VolControl *vol = action->property("volControl").value<VolControl *>();
  2673. obs_source_t *source = vol->GetSource();
  2674. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2675. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2676. obs_data_release(priv_settings);
  2677. vol->EnableSlider(!lock);
  2678. }
  2679. void OBSBasic::VolControlContextMenu()
  2680. {
  2681. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2682. /* ------------------- */
  2683. QAction lockAction(QTStr("LockVolume"), this);
  2684. lockAction.setCheckable(true);
  2685. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2686. QAction hideAction(QTStr("Hide"), this);
  2687. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2688. QAction mixerRenameAction(QTStr("Rename"), this);
  2689. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2690. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2691. QAction filtersAction(QTStr("Filters"), this);
  2692. QAction propertiesAction(QTStr("Properties"), this);
  2693. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2694. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2695. toggleControlLayoutAction.setCheckable(true);
  2696. toggleControlLayoutAction.setChecked(config_get_bool(
  2697. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2698. /* ------------------- */
  2699. connect(&hideAction, &QAction::triggered, this,
  2700. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2701. connect(&unhideAllAction, &QAction::triggered, this,
  2702. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2703. connect(&lockAction, &QAction::toggled, this,
  2704. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2705. connect(&mixerRenameAction, &QAction::triggered, this,
  2706. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2707. connect(&copyFiltersAction, &QAction::triggered, this,
  2708. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2709. connect(&pasteFiltersAction, &QAction::triggered, this,
  2710. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2711. connect(&filtersAction, &QAction::triggered, this,
  2712. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2713. connect(&propertiesAction, &QAction::triggered, this,
  2714. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2715. connect(&advPropAction, &QAction::triggered, this,
  2716. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2717. Qt::DirectConnection);
  2718. /* ------------------- */
  2719. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2720. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2721. /* ------------------- */
  2722. hideAction.setProperty("volControl",
  2723. QVariant::fromValue<VolControl *>(vol));
  2724. lockAction.setProperty("volControl",
  2725. QVariant::fromValue<VolControl *>(vol));
  2726. mixerRenameAction.setProperty("volControl",
  2727. QVariant::fromValue<VolControl *>(vol));
  2728. copyFiltersAction.setProperty("volControl",
  2729. QVariant::fromValue<VolControl *>(vol));
  2730. pasteFiltersAction.setProperty("volControl",
  2731. QVariant::fromValue<VolControl *>(vol));
  2732. filtersAction.setProperty("volControl",
  2733. QVariant::fromValue<VolControl *>(vol));
  2734. propertiesAction.setProperty("volControl",
  2735. QVariant::fromValue<VolControl *>(vol));
  2736. /* ------------------- */
  2737. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  2738. 0);
  2739. if (copyFiltersString == nullptr)
  2740. pasteFiltersAction.setEnabled(false);
  2741. else
  2742. pasteFiltersAction.setEnabled(true);
  2743. QMenu popup;
  2744. vol->SetContextMenu(&popup);
  2745. popup.addAction(&lockAction);
  2746. popup.addSeparator();
  2747. popup.addAction(&unhideAllAction);
  2748. popup.addAction(&hideAction);
  2749. popup.addAction(&mixerRenameAction);
  2750. popup.addSeparator();
  2751. popup.addAction(&copyFiltersAction);
  2752. popup.addAction(&pasteFiltersAction);
  2753. popup.addSeparator();
  2754. popup.addAction(&toggleControlLayoutAction);
  2755. popup.addSeparator();
  2756. popup.addAction(&filtersAction);
  2757. popup.addAction(&propertiesAction);
  2758. popup.addAction(&advPropAction);
  2759. popup.exec(QCursor::pos());
  2760. vol->SetContextMenu(nullptr);
  2761. }
  2762. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2763. {
  2764. StackedMixerAreaContextMenuRequested();
  2765. }
  2766. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2767. {
  2768. StackedMixerAreaContextMenuRequested();
  2769. }
  2770. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2771. {
  2772. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2773. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2774. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2775. toggleControlLayoutAction.setCheckable(true);
  2776. toggleControlLayoutAction.setChecked(config_get_bool(
  2777. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2778. /* ------------------- */
  2779. connect(&unhideAllAction, &QAction::triggered, this,
  2780. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2781. connect(&advPropAction, &QAction::triggered, this,
  2782. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2783. Qt::DirectConnection);
  2784. /* ------------------- */
  2785. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2786. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2787. /* ------------------- */
  2788. QMenu popup;
  2789. popup.addAction(&unhideAllAction);
  2790. popup.addSeparator();
  2791. popup.addAction(&toggleControlLayoutAction);
  2792. popup.addSeparator();
  2793. popup.addAction(&advPropAction);
  2794. popup.exec(QCursor::pos());
  2795. }
  2796. void OBSBasic::ToggleMixerLayout(bool vertical)
  2797. {
  2798. if (vertical) {
  2799. ui->stackedMixerArea->setMinimumSize(180, 220);
  2800. ui->stackedMixerArea->setCurrentIndex(1);
  2801. } else {
  2802. ui->stackedMixerArea->setMinimumSize(220, 0);
  2803. ui->stackedMixerArea->setCurrentIndex(0);
  2804. }
  2805. }
  2806. void OBSBasic::ToggleVolControlLayout()
  2807. {
  2808. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2809. "VerticalVolControl");
  2810. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2811. vertical);
  2812. ToggleMixerLayout(vertical);
  2813. // We need to store it so we can delete current and then add
  2814. // at the right order
  2815. vector<OBSSource> sources;
  2816. for (size_t i = 0; i != volumes.size(); i++)
  2817. sources.emplace_back(volumes[i]->GetSource());
  2818. ClearVolumeControls();
  2819. for (const auto &source : sources)
  2820. ActivateAudioSource(source);
  2821. }
  2822. void OBSBasic::ActivateAudioSource(OBSSource source)
  2823. {
  2824. if (SourceMixerHidden(source))
  2825. return;
  2826. if (!obs_source_audio_active(source))
  2827. return;
  2828. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2829. "VerticalVolControl");
  2830. VolControl *vol = new VolControl(source, true, vertical);
  2831. vol->EnableSlider(!SourceVolumeLocked(source));
  2832. double meterDecayRate =
  2833. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2834. vol->SetMeterDecayRate(meterDecayRate);
  2835. uint32_t peakMeterTypeIdx =
  2836. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2837. enum obs_peak_meter_type peakMeterType;
  2838. switch (peakMeterTypeIdx) {
  2839. case 0:
  2840. peakMeterType = SAMPLE_PEAK_METER;
  2841. break;
  2842. case 1:
  2843. peakMeterType = TRUE_PEAK_METER;
  2844. break;
  2845. default:
  2846. peakMeterType = SAMPLE_PEAK_METER;
  2847. break;
  2848. }
  2849. vol->setPeakMeterType(peakMeterType);
  2850. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2851. connect(vol, &QWidget::customContextMenuRequested, this,
  2852. &OBSBasic::VolControlContextMenu);
  2853. connect(vol, &VolControl::ConfigClicked, this,
  2854. &OBSBasic::VolControlContextMenu);
  2855. InsertQObjectByName(volumes, vol);
  2856. for (auto volume : volumes) {
  2857. if (vertical)
  2858. ui->vVolControlLayout->addWidget(volume);
  2859. else
  2860. ui->hVolControlLayout->addWidget(volume);
  2861. }
  2862. }
  2863. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2864. {
  2865. for (size_t i = 0; i < volumes.size(); i++) {
  2866. if (volumes[i]->GetSource() == source) {
  2867. delete volumes[i];
  2868. volumes.erase(volumes.begin() + i);
  2869. break;
  2870. }
  2871. }
  2872. }
  2873. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2874. {
  2875. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2876. !obs_source_is_group(source)) {
  2877. int count = ui->scenes->count();
  2878. if (count == 1) {
  2879. OBSMessageBox::information(this,
  2880. QTStr("FinalScene.Title"),
  2881. QTStr("FinalScene.Text"));
  2882. return false;
  2883. }
  2884. }
  2885. const char *name = obs_source_get_name(source);
  2886. QString text = QTStr("ConfirmRemove.Text");
  2887. text.replace("$1", QT_UTF8(name));
  2888. QMessageBox remove_source(this);
  2889. remove_source.setText(text);
  2890. QPushButton *Yes =
  2891. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2892. remove_source.setDefaultButton(Yes);
  2893. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2894. remove_source.setIcon(QMessageBox::Question);
  2895. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2896. remove_source.exec();
  2897. return Yes == remove_source.clickedButton();
  2898. }
  2899. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2900. #ifdef UPDATE_SPARKLE
  2901. void init_sparkle_updater(bool update_to_undeployed);
  2902. void trigger_sparkle_update();
  2903. #endif
  2904. void OBSBasic::TimedCheckForUpdates()
  2905. {
  2906. if (App()->IsUpdaterDisabled())
  2907. return;
  2908. if (!config_get_bool(App()->GlobalConfig(), "General",
  2909. "EnableAutoUpdates"))
  2910. return;
  2911. #ifdef UPDATE_SPARKLE
  2912. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2913. "UpdateToUndeployed"));
  2914. #elif _WIN32
  2915. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2916. "LastUpdateCheck");
  2917. uint32_t lastVersion =
  2918. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2919. if (lastVersion < LIBOBS_API_VER) {
  2920. lastUpdate = 0;
  2921. config_set_int(App()->GlobalConfig(), "General",
  2922. "LastUpdateCheck", 0);
  2923. }
  2924. long long t = (long long)time(nullptr);
  2925. long long secs = t - lastUpdate;
  2926. if (secs > UPDATE_CHECK_INTERVAL)
  2927. CheckForUpdates(false);
  2928. #endif
  2929. }
  2930. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2931. {
  2932. #ifdef UPDATE_SPARKLE
  2933. trigger_sparkle_update();
  2934. #elif _WIN32
  2935. ui->actionCheckForUpdates->setEnabled(false);
  2936. if (updateCheckThread && updateCheckThread->isRunning())
  2937. return;
  2938. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2939. updateCheckThread->start();
  2940. #endif
  2941. UNUSED_PARAMETER(manualUpdate);
  2942. }
  2943. void OBSBasic::updateCheckFinished()
  2944. {
  2945. ui->actionCheckForUpdates->setEnabled(true);
  2946. }
  2947. void OBSBasic::DuplicateSelectedScene()
  2948. {
  2949. OBSScene curScene = GetCurrentScene();
  2950. if (!curScene)
  2951. return;
  2952. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2953. QString format{obs_source_get_name(curSceneSource)};
  2954. format += " %1";
  2955. int i = 2;
  2956. QString placeHolderText = format.arg(i);
  2957. obs_source_t *source = nullptr;
  2958. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2959. obs_source_release(source);
  2960. placeHolderText = format.arg(++i);
  2961. }
  2962. for (;;) {
  2963. string name;
  2964. bool accepted = NameDialog::AskForName(
  2965. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2966. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2967. placeHolderText);
  2968. if (!accepted)
  2969. return;
  2970. if (name.empty()) {
  2971. OBSMessageBox::warning(this,
  2972. QTStr("NoNameEntered.Title"),
  2973. QTStr("NoNameEntered.Text"));
  2974. continue;
  2975. }
  2976. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2977. if (source) {
  2978. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2979. QTStr("NameExists.Text"));
  2980. obs_source_release(source);
  2981. continue;
  2982. }
  2983. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2984. OBS_SCENE_DUP_REFS);
  2985. source = obs_scene_get_source(scene);
  2986. SetCurrentScene(source, true);
  2987. auto undo = [](const std::string &data) {
  2988. obs_source_t *source =
  2989. obs_get_source_by_name(data.c_str());
  2990. obs_source_remove(source);
  2991. obs_source_release(source);
  2992. };
  2993. auto redo = [this, name](const std::string &data) {
  2994. obs_source_t *source =
  2995. obs_get_source_by_name(data.c_str());
  2996. obs_scene_t *scene = obs_scene_from_source(source);
  2997. obs_source_release(source);
  2998. scene = obs_scene_duplicate(scene, name.c_str(),
  2999. OBS_SCENE_DUP_REFS);
  3000. source = obs_scene_get_source(scene);
  3001. SetCurrentScene(source, true);
  3002. obs_scene_release(scene);
  3003. };
  3004. undo_s.add_action(
  3005. QTStr("Undo.Scene.Duplicate")
  3006. .arg(obs_source_get_name(source)),
  3007. undo, redo, obs_source_get_name(source),
  3008. obs_source_get_name(obs_scene_get_source(curScene)));
  3009. obs_scene_release(scene);
  3010. break;
  3011. }
  3012. }
  3013. static bool save_undo_source_enum(obs_scene_t *scene, obs_sceneitem_t *item,
  3014. void *p)
  3015. {
  3016. UNUSED_PARAMETER(scene);
  3017. obs_source_t *source = obs_sceneitem_get_source(item);
  3018. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3019. return true;
  3020. obs_data_array_t *array = (obs_data_array_t *)p;
  3021. /* check if the source is already stored in the array */
  3022. const char *name = obs_source_get_name(source);
  3023. const size_t count = obs_data_array_count(array);
  3024. for (size_t i = 0; i < count; i++) {
  3025. obs_data_t *sourceData = obs_data_array_item(array, i);
  3026. if (strcmp(name, obs_data_get_string(sourceData, "name")) ==
  3027. 0) {
  3028. obs_data_release(sourceData);
  3029. return true;
  3030. }
  3031. obs_data_release(sourceData);
  3032. }
  3033. if (obs_source_is_group(source))
  3034. obs_scene_enum_items(obs_group_from_source(source),
  3035. save_undo_source_enum, p);
  3036. obs_data_t *source_data = obs_save_source(source);
  3037. obs_data_array_push_back(array, source_data);
  3038. obs_data_release(source_data);
  3039. return true;
  3040. }
  3041. void OBSBasic::RemoveSelectedScene()
  3042. {
  3043. OBSScene scene = GetCurrentScene();
  3044. obs_source_t *source = obs_scene_get_source(scene);
  3045. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  3046. if (!source || !QueryRemoveSource(source)) {
  3047. return;
  3048. }
  3049. /* ------------------------------ */
  3050. /* save all sources in scene */
  3051. obs_data_array_t *array = obs_data_array_create();
  3052. obs_scene_enum_items(scene, save_undo_source_enum, array);
  3053. obs_data_t *scene_data = obs_save_source(source);
  3054. obs_data_array_push_back(array, scene_data);
  3055. obs_data_release(scene_data);
  3056. /* ----------------------------------------------- */
  3057. /* save all scenes and groups the scene is used in */
  3058. for (int i = 0; i < ui->scenes->count(); i++) {
  3059. QListWidgetItem *widget_item = ui->scenes->item(i);
  3060. auto item_scene = GetOBSRef<OBSScene>(widget_item);
  3061. if (scene == item_scene)
  3062. continue;
  3063. auto *item = obs_scene_find_source_recursive(
  3064. item_scene, obs_source_get_name(source));
  3065. if (item) {
  3066. scene_data = obs_save_source(obs_scene_get_source(
  3067. obs_sceneitem_get_scene(item)));
  3068. obs_data_array_push_back(array, scene_data);
  3069. obs_data_release(scene_data);
  3070. }
  3071. }
  3072. /* --------------------------- */
  3073. /* undo/redo */
  3074. auto undo = [this](const std::string &json) {
  3075. obs_data_t *base = obs_data_create_from_json(json.c_str());
  3076. obs_data_array_t *array = obs_data_get_array(base, "array");
  3077. int savedIndex = (int)obs_data_get_int(base, "index");
  3078. std::vector<obs_source_t *> sources;
  3079. /* create missing sources */
  3080. size_t count = obs_data_array_count(array);
  3081. sources.reserve(count);
  3082. for (size_t i = 0; i < count; i++) {
  3083. obs_data_t *data = obs_data_array_item(array, i);
  3084. const char *name = obs_data_get_string(data, "name");
  3085. obs_source_t *source = obs_get_source_by_name(name);
  3086. if (!source)
  3087. source = obs_load_source(data);
  3088. sources.push_back(source);
  3089. obs_data_release(data);
  3090. }
  3091. /* actually load sources now */
  3092. for (obs_source_t *source : sources)
  3093. obs_source_load2(source);
  3094. obs_source_t *scene_source = sources.back();
  3095. OBSScene scene = obs_scene_from_source(scene_source);
  3096. SetCurrentScene(scene, true);
  3097. /* set original index in list box */
  3098. ui->scenes->blockSignals(true);
  3099. int curIndex = ui->scenes->currentRow();
  3100. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3101. ui->scenes->insertItem(savedIndex, item);
  3102. ui->scenes->setCurrentRow(savedIndex);
  3103. ui->scenes->blockSignals(false);
  3104. /* release sources */
  3105. for (obs_source_t *source : sources)
  3106. obs_source_release(source);
  3107. obs_data_array_release(array);
  3108. obs_data_release(base);
  3109. };
  3110. auto redo = [](const std::string &name) {
  3111. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3112. obs_source_remove(source);
  3113. obs_source_release(source);
  3114. };
  3115. obs_data_t *data = obs_data_create();
  3116. obs_data_set_array(data, "array", array);
  3117. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3118. const char *scene_name = obs_source_get_name(source);
  3119. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3120. obs_data_get_json(data), scene_name);
  3121. obs_data_array_release(array);
  3122. obs_data_release(data);
  3123. /* --------------------------- */
  3124. /* remove */
  3125. obs_source_remove(source);
  3126. if (api)
  3127. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3128. }
  3129. void OBSBasic::RemoveSelectedSceneItem()
  3130. {
  3131. OBSSceneItem item = GetCurrentSceneItem();
  3132. if (item) {
  3133. obs_source_t *source = obs_sceneitem_get_source(item);
  3134. if (QueryRemoveSource(source))
  3135. obs_sceneitem_remove(item);
  3136. }
  3137. }
  3138. void OBSBasic::ReorderSources(OBSScene scene)
  3139. {
  3140. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3141. return;
  3142. ui->sources->ReorderItems();
  3143. SaveProject();
  3144. }
  3145. void OBSBasic::RefreshSources(OBSScene scene)
  3146. {
  3147. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3148. return;
  3149. ui->sources->RefreshItems();
  3150. SaveProject();
  3151. }
  3152. /* OBS Callbacks */
  3153. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3154. {
  3155. OBSBasic *window = static_cast<OBSBasic *>(data);
  3156. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3157. QMetaObject::invokeMethod(window, "ReorderSources",
  3158. Q_ARG(OBSScene, OBSScene(scene)));
  3159. }
  3160. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3161. {
  3162. OBSBasic *window = static_cast<OBSBasic *>(data);
  3163. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3164. QMetaObject::invokeMethod(window, "RefreshSources",
  3165. Q_ARG(OBSScene, OBSScene(scene)));
  3166. }
  3167. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3168. {
  3169. OBSBasic *window = static_cast<OBSBasic *>(data);
  3170. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3171. QMetaObject::invokeMethod(window, "AddSceneItem",
  3172. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3173. }
  3174. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3175. {
  3176. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3177. if (obs_scene_from_source(source) != NULL)
  3178. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3179. "AddScene", WaitConnection(),
  3180. Q_ARG(OBSSource, OBSSource(source)));
  3181. }
  3182. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3183. {
  3184. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3185. if (obs_scene_from_source(source) != NULL)
  3186. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3187. "RemoveScene",
  3188. Q_ARG(OBSSource, OBSSource(source)));
  3189. }
  3190. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3191. {
  3192. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3193. uint32_t flags = obs_source_get_output_flags(source);
  3194. if (flags & OBS_SOURCE_AUDIO)
  3195. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3196. "ActivateAudioSource",
  3197. Q_ARG(OBSSource, OBSSource(source)));
  3198. }
  3199. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3200. {
  3201. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3202. uint32_t flags = obs_source_get_output_flags(source);
  3203. if (flags & OBS_SOURCE_AUDIO)
  3204. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3205. "DeactivateAudioSource",
  3206. Q_ARG(OBSSource, OBSSource(source)));
  3207. }
  3208. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3209. {
  3210. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3211. if (obs_source_active(source))
  3212. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3213. "ActivateAudioSource",
  3214. Q_ARG(OBSSource, OBSSource(source)));
  3215. }
  3216. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3217. {
  3218. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3219. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3220. "DeactivateAudioSource",
  3221. Q_ARG(OBSSource, OBSSource(source)));
  3222. }
  3223. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3224. {
  3225. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3226. const char *newName = calldata_string(params, "new_name");
  3227. const char *prevName = calldata_string(params, "prev_name");
  3228. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3229. "RenameSources", Q_ARG(OBSSource, source),
  3230. Q_ARG(QString, QT_UTF8(newName)),
  3231. Q_ARG(QString, QT_UTF8(prevName)));
  3232. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3233. }
  3234. void OBSBasic::DrawBackdrop(float cx, float cy)
  3235. {
  3236. if (!box)
  3237. return;
  3238. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3239. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3240. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3241. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3242. vec4 colorVal;
  3243. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3244. gs_effect_set_vec4(color, &colorVal);
  3245. gs_technique_begin(tech);
  3246. gs_technique_begin_pass(tech, 0);
  3247. gs_matrix_push();
  3248. gs_matrix_identity();
  3249. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3250. gs_load_vertexbuffer(box);
  3251. gs_draw(GS_TRISTRIP, 0, 0);
  3252. gs_matrix_pop();
  3253. gs_technique_end_pass(tech);
  3254. gs_technique_end(tech);
  3255. gs_load_vertexbuffer(nullptr);
  3256. GS_DEBUG_MARKER_END();
  3257. }
  3258. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  3259. {
  3260. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3261. OBSBasic *window = static_cast<OBSBasic *>(data);
  3262. obs_video_info ovi;
  3263. obs_get_video_info(&ovi);
  3264. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3265. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3266. gs_viewport_push();
  3267. gs_projection_push();
  3268. obs_display_t *display = window->ui->preview->GetDisplay();
  3269. uint32_t width, height;
  3270. obs_display_size(display, &width, &height);
  3271. float right = float(width) - window->previewX;
  3272. float bottom = float(height) - window->previewY;
  3273. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3274. 100.0f);
  3275. window->ui->preview->DrawOverflow();
  3276. /* --------------------------------------- */
  3277. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3278. -100.0f, 100.0f);
  3279. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3280. window->previewCY);
  3281. if (window->IsPreviewProgramMode()) {
  3282. window->DrawBackdrop(float(ovi.base_width),
  3283. float(ovi.base_height));
  3284. OBSScene scene = window->GetCurrentScene();
  3285. obs_source_t *source = obs_scene_get_source(scene);
  3286. if (source)
  3287. obs_source_video_render(source);
  3288. } else {
  3289. obs_render_main_texture_src_color_only();
  3290. }
  3291. gs_load_vertexbuffer(nullptr);
  3292. /* --------------------------------------- */
  3293. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3294. 100.0f);
  3295. gs_reset_viewport();
  3296. window->ui->preview->DrawSceneEditing();
  3297. uint32_t targetCX = window->previewCX;
  3298. uint32_t targetCY = window->previewCY;
  3299. if (window->drawSafeAreas) {
  3300. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3301. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3302. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3303. targetCY);
  3304. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3305. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3306. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3307. }
  3308. /* --------------------------------------- */
  3309. gs_projection_pop();
  3310. gs_viewport_pop();
  3311. GS_DEBUG_MARKER_END();
  3312. UNUSED_PARAMETER(cx);
  3313. UNUSED_PARAMETER(cy);
  3314. }
  3315. /* Main class functions */
  3316. obs_service_t *OBSBasic::GetService()
  3317. {
  3318. if (!service) {
  3319. service =
  3320. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3321. obs_service_release(service);
  3322. }
  3323. return service;
  3324. }
  3325. void OBSBasic::SetService(obs_service_t *newService)
  3326. {
  3327. if (newService)
  3328. service = newService;
  3329. }
  3330. int OBSBasic::GetTransitionDuration()
  3331. {
  3332. return ui->transitionDuration->value();
  3333. }
  3334. bool OBSBasic::StreamingActive() const
  3335. {
  3336. if (!outputHandler)
  3337. return false;
  3338. return outputHandler->StreamingActive();
  3339. }
  3340. bool OBSBasic::Active() const
  3341. {
  3342. if (!outputHandler)
  3343. return false;
  3344. return outputHandler->Active();
  3345. }
  3346. #ifdef _WIN32
  3347. #define IS_WIN32 1
  3348. #else
  3349. #define IS_WIN32 0
  3350. #endif
  3351. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3352. {
  3353. return obs_reset_video(ovi);
  3354. }
  3355. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3356. {
  3357. const char *scaleTypeStr =
  3358. config_get_string(basicConfig, "Video", "ScaleType");
  3359. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3360. return OBS_SCALE_BILINEAR;
  3361. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3362. return OBS_SCALE_LANCZOS;
  3363. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3364. return OBS_SCALE_AREA;
  3365. else
  3366. return OBS_SCALE_BICUBIC;
  3367. }
  3368. static inline enum video_format GetVideoFormatFromName(const char *name)
  3369. {
  3370. if (astrcmpi(name, "I420") == 0)
  3371. return VIDEO_FORMAT_I420;
  3372. else if (astrcmpi(name, "NV12") == 0)
  3373. return VIDEO_FORMAT_NV12;
  3374. else if (astrcmpi(name, "I444") == 0)
  3375. return VIDEO_FORMAT_I444;
  3376. #if 0 //currently unsupported
  3377. else if (astrcmpi(name, "YVYU") == 0)
  3378. return VIDEO_FORMAT_YVYU;
  3379. else if (astrcmpi(name, "YUY2") == 0)
  3380. return VIDEO_FORMAT_YUY2;
  3381. else if (astrcmpi(name, "UYVY") == 0)
  3382. return VIDEO_FORMAT_UYVY;
  3383. #endif
  3384. else
  3385. return VIDEO_FORMAT_RGBA;
  3386. }
  3387. void OBSBasic::ResetUI()
  3388. {
  3389. bool studioPortraitLayout = config_get_bool(
  3390. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3391. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3392. "StudioModeLabels");
  3393. if (studioPortraitLayout)
  3394. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  3395. else
  3396. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3397. if (previewProgramMode)
  3398. ui->previewLabel->setHidden(!labels);
  3399. if (programLabel)
  3400. programLabel->setHidden(!labels);
  3401. }
  3402. int OBSBasic::ResetVideo()
  3403. {
  3404. if (outputHandler && outputHandler->Active())
  3405. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3406. ProfileScope("OBSBasic::ResetVideo");
  3407. struct obs_video_info ovi;
  3408. int ret;
  3409. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3410. const char *colorFormat =
  3411. config_get_string(basicConfig, "Video", "ColorFormat");
  3412. const char *colorSpace =
  3413. config_get_string(basicConfig, "Video", "ColorSpace");
  3414. const char *colorRange =
  3415. config_get_string(basicConfig, "Video", "ColorRange");
  3416. ovi.graphics_module = App()->GetRenderModule();
  3417. ovi.base_width =
  3418. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3419. ovi.base_height =
  3420. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3421. ovi.output_width =
  3422. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3423. ovi.output_height =
  3424. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3425. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3426. ovi.colorspace = astrcmpi(colorSpace, "601") == 0
  3427. ? VIDEO_CS_601
  3428. : (astrcmpi(colorSpace, "709") == 0
  3429. ? VIDEO_CS_709
  3430. : VIDEO_CS_SRGB);
  3431. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3432. : VIDEO_RANGE_PARTIAL;
  3433. ovi.adapter =
  3434. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3435. ovi.gpu_conversion = true;
  3436. ovi.scale_type = GetScaleType(basicConfig);
  3437. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3438. ovi.base_width = 1920;
  3439. ovi.base_height = 1080;
  3440. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3441. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3442. }
  3443. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3444. ovi.output_width = ovi.base_width;
  3445. ovi.output_height = ovi.base_height;
  3446. config_set_uint(basicConfig, "Video", "OutputCX",
  3447. ovi.base_width);
  3448. config_set_uint(basicConfig, "Video", "OutputCY",
  3449. ovi.base_height);
  3450. }
  3451. ret = AttemptToResetVideo(&ovi);
  3452. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3453. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3454. blog(LOG_WARNING, "Tried to reset when "
  3455. "already active");
  3456. return ret;
  3457. }
  3458. /* Try OpenGL if DirectX fails on windows */
  3459. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3460. blog(LOG_WARNING,
  3461. "Failed to initialize obs video (%d) "
  3462. "with graphics_module='%s', retrying "
  3463. "with graphics_module='%s'",
  3464. ret, ovi.graphics_module, DL_OPENGL);
  3465. ovi.graphics_module = DL_OPENGL;
  3466. ret = AttemptToResetVideo(&ovi);
  3467. }
  3468. } else if (ret == OBS_VIDEO_SUCCESS) {
  3469. ResizePreview(ovi.base_width, ovi.base_height);
  3470. if (program)
  3471. ResizeProgram(ovi.base_width, ovi.base_height);
  3472. }
  3473. if (ret == OBS_VIDEO_SUCCESS) {
  3474. OBSBasicStats::InitializeValues();
  3475. OBSProjector::UpdateMultiviewProjectors();
  3476. }
  3477. return ret;
  3478. }
  3479. bool OBSBasic::ResetAudio()
  3480. {
  3481. ProfileScope("OBSBasic::ResetAudio");
  3482. struct obs_audio_info ai;
  3483. ai.samples_per_sec =
  3484. config_get_uint(basicConfig, "Audio", "SampleRate");
  3485. const char *channelSetupStr =
  3486. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3487. if (strcmp(channelSetupStr, "Mono") == 0)
  3488. ai.speakers = SPEAKERS_MONO;
  3489. else if (strcmp(channelSetupStr, "2.1") == 0)
  3490. ai.speakers = SPEAKERS_2POINT1;
  3491. else if (strcmp(channelSetupStr, "4.0") == 0)
  3492. ai.speakers = SPEAKERS_4POINT0;
  3493. else if (strcmp(channelSetupStr, "4.1") == 0)
  3494. ai.speakers = SPEAKERS_4POINT1;
  3495. else if (strcmp(channelSetupStr, "5.1") == 0)
  3496. ai.speakers = SPEAKERS_5POINT1;
  3497. else if (strcmp(channelSetupStr, "7.1") == 0)
  3498. ai.speakers = SPEAKERS_7POINT1;
  3499. else
  3500. ai.speakers = SPEAKERS_STEREO;
  3501. return obs_reset_audio(&ai);
  3502. }
  3503. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3504. const char *deviceDesc, int channel)
  3505. {
  3506. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3507. obs_source_t *source;
  3508. obs_data_t *settings;
  3509. source = obs_get_output_source(channel);
  3510. if (source) {
  3511. if (disable) {
  3512. obs_set_output_source(channel, nullptr);
  3513. } else {
  3514. settings = obs_source_get_settings(source);
  3515. const char *oldId =
  3516. obs_data_get_string(settings, "device_id");
  3517. if (strcmp(oldId, deviceId) != 0) {
  3518. obs_data_set_string(settings, "device_id",
  3519. deviceId);
  3520. obs_source_update(source, settings);
  3521. }
  3522. obs_data_release(settings);
  3523. }
  3524. obs_source_release(source);
  3525. } else if (!disable) {
  3526. settings = obs_data_create();
  3527. obs_data_set_string(settings, "device_id", deviceId);
  3528. source = obs_source_create(sourceId, deviceDesc, settings,
  3529. nullptr);
  3530. obs_data_release(settings);
  3531. obs_set_output_source(channel, source);
  3532. obs_source_release(source);
  3533. }
  3534. }
  3535. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3536. {
  3537. QSize targetSize;
  3538. bool isFixedScaling;
  3539. obs_video_info ovi;
  3540. /* resize preview panel to fix to the top section of the window */
  3541. targetSize = GetPixelSize(ui->preview);
  3542. isFixedScaling = ui->preview->IsFixedScaling();
  3543. obs_get_video_info(&ovi);
  3544. if (isFixedScaling) {
  3545. previewScale = ui->preview->GetScalingAmount();
  3546. GetCenterPosFromFixedScale(
  3547. int(cx), int(cy),
  3548. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3549. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3550. previewY, previewScale);
  3551. previewX += ui->preview->GetScrollX();
  3552. previewY += ui->preview->GetScrollY();
  3553. } else {
  3554. GetScaleAndCenterPos(int(cx), int(cy),
  3555. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3556. targetSize.height() -
  3557. PREVIEW_EDGE_SIZE * 2,
  3558. previewX, previewY, previewScale);
  3559. }
  3560. previewX += float(PREVIEW_EDGE_SIZE);
  3561. previewY += float(PREVIEW_EDGE_SIZE);
  3562. }
  3563. void OBSBasic::CloseDialogs()
  3564. {
  3565. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3566. if (!childDialogs.isEmpty()) {
  3567. for (int i = 0; i < childDialogs.size(); ++i) {
  3568. childDialogs.at(i)->close();
  3569. }
  3570. }
  3571. if (!stats.isNull())
  3572. stats->close(); //call close to save Stats geometry
  3573. if (!remux.isNull())
  3574. remux->close();
  3575. }
  3576. void OBSBasic::EnumDialogs()
  3577. {
  3578. visDialogs.clear();
  3579. modalDialogs.clear();
  3580. visMsgBoxes.clear();
  3581. /* fill list of Visible dialogs and Modal dialogs */
  3582. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3583. for (QDialog *dialog : dialogs) {
  3584. if (dialog->isVisible())
  3585. visDialogs.append(dialog);
  3586. if (dialog->isModal())
  3587. modalDialogs.append(dialog);
  3588. }
  3589. /* fill list of Visible message boxes */
  3590. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3591. for (QMessageBox *msgbox : msgBoxes) {
  3592. if (msgbox->isVisible())
  3593. visMsgBoxes.append(msgbox);
  3594. }
  3595. }
  3596. void OBSBasic::ClearProjectors()
  3597. {
  3598. for (size_t i = 0; i < projectors.size(); i++) {
  3599. if (projectors[i])
  3600. delete projectors[i];
  3601. }
  3602. projectors.clear();
  3603. }
  3604. void OBSBasic::ClearSceneData()
  3605. {
  3606. disableSaving++;
  3607. CloseDialogs();
  3608. ClearVolumeControls();
  3609. ClearListItems(ui->scenes);
  3610. ui->sources->Clear();
  3611. ClearQuickTransitions();
  3612. ui->transitions->clear();
  3613. ClearProjectors();
  3614. for (int i = 0; i < MAX_CHANNELS; i++)
  3615. obs_set_output_source(i, nullptr);
  3616. lastScene = nullptr;
  3617. swapScene = nullptr;
  3618. programScene = nullptr;
  3619. prevFTBSource = nullptr;
  3620. copyStrings.clear();
  3621. copyFiltersString = nullptr;
  3622. copyFilter = nullptr;
  3623. auto cb = [](void *unused, obs_source_t *source) {
  3624. obs_source_remove(source);
  3625. UNUSED_PARAMETER(unused);
  3626. return true;
  3627. };
  3628. obs_enum_scenes(cb, nullptr);
  3629. obs_enum_sources(cb, nullptr);
  3630. if (api)
  3631. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3632. undo_s.clear();
  3633. disableSaving--;
  3634. blog(LOG_INFO, "All scene data cleared");
  3635. blog(LOG_INFO, "------------------------------------------------");
  3636. }
  3637. void OBSBasic::closeEvent(QCloseEvent *event)
  3638. {
  3639. /* Do not close window if inside of a temporary event loop because we
  3640. * could be inside of an Auth::LoadUI call. Keep trying once per
  3641. * second until we've exit any known sub-loops. */
  3642. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3643. QTimer::singleShot(1000, this, SLOT(close()));
  3644. event->ignore();
  3645. return;
  3646. }
  3647. #if YOUTUBE_ENABLED
  3648. /* Also don't close the window if the youtube stream check is active */
  3649. if (youtubeStreamCheckThread) {
  3650. QTimer::singleShot(1000, this, SLOT(close()));
  3651. event->ignore();
  3652. return;
  3653. }
  3654. #endif
  3655. if (isVisible())
  3656. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3657. "geometry",
  3658. saveGeometry().toBase64().constData());
  3659. if (outputHandler && outputHandler->Active()) {
  3660. SetShowing(true);
  3661. QMessageBox::StandardButton button = OBSMessageBox::question(
  3662. this, QTStr("ConfirmExit.Title"),
  3663. QTStr("ConfirmExit.Text"));
  3664. if (button == QMessageBox::No) {
  3665. event->ignore();
  3666. restart = false;
  3667. return;
  3668. }
  3669. }
  3670. QWidget::closeEvent(event);
  3671. if (!event->isAccepted())
  3672. return;
  3673. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3674. closing = true;
  3675. if (introCheckThread)
  3676. introCheckThread->wait();
  3677. if (whatsNewInitThread)
  3678. whatsNewInitThread->wait();
  3679. if (updateCheckThread)
  3680. updateCheckThread->wait();
  3681. if (logUploadThread)
  3682. logUploadThread->wait();
  3683. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  3684. devicePropertiesThread->wait();
  3685. devicePropertiesThread.reset();
  3686. }
  3687. QApplication::sendPostedEvents(this);
  3688. signalHandlers.clear();
  3689. Auth::Save();
  3690. SaveProjectNow();
  3691. auth.reset();
  3692. delete extraBrowsers;
  3693. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3694. saveState().toBase64().constData());
  3695. #ifdef BROWSER_AVAILABLE
  3696. SaveExtraBrowserDocks();
  3697. ClearExtraBrowserDocks();
  3698. #endif
  3699. disableSaving++;
  3700. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3701. * sources, etc) so that all references are released before shutdown */
  3702. ClearSceneData();
  3703. if (api)
  3704. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3705. App()->quit();
  3706. }
  3707. void OBSBasic::changeEvent(QEvent *event)
  3708. {
  3709. if (event->type() == QEvent::WindowStateChange) {
  3710. QWindowStateChangeEvent *stateEvent =
  3711. (QWindowStateChangeEvent *)event;
  3712. if (isMinimized()) {
  3713. if (trayIcon && trayIcon->isVisible() &&
  3714. sysTrayMinimizeToTray()) {
  3715. ToggleShowHide();
  3716. }
  3717. if (previewEnabled)
  3718. EnablePreviewDisplay(false);
  3719. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3720. isVisible()) {
  3721. if (previewEnabled)
  3722. EnablePreviewDisplay(true);
  3723. }
  3724. }
  3725. }
  3726. void OBSBasic::on_actionShow_Recordings_triggered()
  3727. {
  3728. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3729. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3730. const char *adv_path =
  3731. strcmp(type, "Standard")
  3732. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3733. : config_get_string(basicConfig, "AdvOut",
  3734. "RecFilePath");
  3735. const char *path = strcmp(mode, "Advanced")
  3736. ? config_get_string(basicConfig,
  3737. "SimpleOutput",
  3738. "FilePath")
  3739. : adv_path;
  3740. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3741. }
  3742. void OBSBasic::on_actionRemux_triggered()
  3743. {
  3744. if (!remux.isNull()) {
  3745. remux->show();
  3746. remux->raise();
  3747. return;
  3748. }
  3749. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3750. const char *path = strcmp(mode, "Advanced")
  3751. ? config_get_string(basicConfig,
  3752. "SimpleOutput",
  3753. "FilePath")
  3754. : config_get_string(basicConfig, "AdvOut",
  3755. "RecFilePath");
  3756. OBSRemux *remuxDlg;
  3757. remuxDlg = new OBSRemux(path, this);
  3758. remuxDlg->show();
  3759. remux = remuxDlg;
  3760. }
  3761. void OBSBasic::on_action_Settings_triggered()
  3762. {
  3763. static bool settings_already_executing = false;
  3764. /* Do not load settings window if inside of a temporary event loop
  3765. * because we could be inside of an Auth::LoadUI call. Keep trying
  3766. * once per second until we've exit any known sub-loops. */
  3767. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3768. QTimer::singleShot(1000, this,
  3769. SLOT(on_action_Settings_triggered()));
  3770. return;
  3771. }
  3772. if (settings_already_executing) {
  3773. return;
  3774. }
  3775. settings_already_executing = true;
  3776. {
  3777. OBSBasicSettings settings(this);
  3778. settings.exec();
  3779. }
  3780. SystemTray(false);
  3781. settings_already_executing = false;
  3782. if (restart) {
  3783. QMessageBox::StandardButton button = OBSMessageBox::question(
  3784. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3785. if (button == QMessageBox::Yes)
  3786. close();
  3787. else
  3788. restart = false;
  3789. }
  3790. }
  3791. static inline void AddMissingFiles(void *data, obs_source_t *source)
  3792. {
  3793. obs_missing_files_t *f = (obs_missing_files_t *)data;
  3794. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  3795. obs_missing_files_append(f, sf);
  3796. obs_missing_files_destroy(sf);
  3797. }
  3798. void OBSBasic::on_actionShowMissingFiles_triggered()
  3799. {
  3800. obs_missing_files_t *files = obs_missing_files_create();
  3801. auto cb_sources = [](void *data, obs_source_t *source) {
  3802. AddMissingFiles(data, source);
  3803. return true;
  3804. };
  3805. obs_enum_sources(cb_sources, files);
  3806. auto cb_transitions = [](void *data, obs_source_t *source) {
  3807. if (obs_source_get_type(source) != OBS_SOURCE_TYPE_TRANSITION)
  3808. return true;
  3809. AddMissingFiles(data, source);
  3810. return true;
  3811. };
  3812. obs_enum_all_sources(cb_transitions, files);
  3813. if (obs_missing_files_count(files) > 0) {
  3814. missDialog = new OBSMissingFiles(files, this);
  3815. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  3816. missDialog->show();
  3817. missDialog->raise();
  3818. } else {
  3819. obs_missing_files_destroy(files);
  3820. OBSMessageBox::information(
  3821. this, QTStr("MissingFiles.NoMissing.Title"),
  3822. QTStr("MissingFiles.NoMissing.Text"));
  3823. }
  3824. }
  3825. void save_audio_source(int channel, obs_data_t *save)
  3826. {
  3827. obs_source_t *source = obs_get_output_source(channel);
  3828. if (!source)
  3829. return;
  3830. obs_data_t *obj = obs_data_create();
  3831. obs_data_set_double(obj, "vol", obs_source_get_volume(source));
  3832. obs_data_set_double(obj, "balance",
  3833. obs_source_get_balance_value(source));
  3834. obs_data_set_double(obj, "mixers", obs_source_get_audio_mixers(source));
  3835. obs_data_set_double(obj, "sync", obs_source_get_sync_offset(source));
  3836. obs_data_set_double(obj, "flags", obs_source_get_flags(source));
  3837. obs_data_set_obj(save, std::to_string(channel).c_str(), obj);
  3838. obs_data_release(obj);
  3839. obs_source_release(source);
  3840. }
  3841. void load_audio_source(int channel, obs_data_t *data)
  3842. {
  3843. obs_source_t *source = obs_get_output_source(channel);
  3844. if (!source)
  3845. return;
  3846. obs_data_t *save =
  3847. obs_data_get_obj(data, std::to_string(channel).c_str());
  3848. obs_source_set_volume(source, obs_data_get_double(save, "vol"));
  3849. obs_source_set_balance_value(source,
  3850. obs_data_get_double(save, "balance"));
  3851. obs_source_set_audio_mixers(source,
  3852. obs_data_get_double(save, "mixers"));
  3853. obs_source_set_sync_offset(source, obs_data_get_double(save, "sync"));
  3854. obs_source_set_flags(source, obs_data_get_double(save, "flags"));
  3855. obs_data_release(save);
  3856. obs_source_release(source);
  3857. }
  3858. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3859. {
  3860. if (advAudioWindow != nullptr) {
  3861. advAudioWindow->raise();
  3862. return;
  3863. }
  3864. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3865. "BasicWindow", "ShowSourceIcons");
  3866. advAudioWindow = new OBSBasicAdvAudio(this);
  3867. advAudioWindow->show();
  3868. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3869. advAudioWindow->SetIconsVisible(iconsVisible);
  3870. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3871. SLOT(AdvAudioPropsDestroyed()));
  3872. }
  3873. void OBSBasic::AdvAudioPropsClicked()
  3874. {
  3875. on_actionAdvAudioProperties_triggered();
  3876. }
  3877. void OBSBasic::AdvAudioPropsDestroyed()
  3878. {
  3879. advAudioWindow = nullptr;
  3880. }
  3881. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3882. QListWidgetItem *prev)
  3883. {
  3884. obs_source_t *source = NULL;
  3885. if (current) {
  3886. obs_scene_t *scene;
  3887. scene = GetOBSRef<OBSScene>(current);
  3888. source = obs_scene_get_source(scene);
  3889. }
  3890. SetCurrentScene(source);
  3891. if (api)
  3892. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3893. UpdateContextBar();
  3894. UNUSED_PARAMETER(prev);
  3895. }
  3896. void OBSBasic::EditSceneName()
  3897. {
  3898. ui->scenesDock->removeAction(renameScene);
  3899. QListWidgetItem *item = ui->scenes->currentItem();
  3900. Qt::ItemFlags flags = item->flags();
  3901. item->setFlags(flags | Qt::ItemIsEditable);
  3902. ui->scenes->editItem(item);
  3903. item->setFlags(flags);
  3904. }
  3905. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3906. const char *slot)
  3907. {
  3908. QAction *action;
  3909. QList<QScreen *> screens = QGuiApplication::screens();
  3910. for (int i = 0; i < screens.size(); i++) {
  3911. QScreen *screen = screens[i];
  3912. QRect screenGeometry = screen->geometry();
  3913. qreal ratio = screen->devicePixelRatio();
  3914. QString name = "";
  3915. #ifdef _WIN32
  3916. QTextStream fullname(&name);
  3917. fullname << GetMonitorName(screen->name());
  3918. fullname << " (";
  3919. fullname << (i + 1);
  3920. fullname << ")";
  3921. #elif defined(__APPLE__)
  3922. name = screen->name();
  3923. #else
  3924. name = screen->model().simplified();
  3925. if (name.length() > 1 && name.endsWith("-"))
  3926. name.chop(1);
  3927. #endif
  3928. name = name.simplified();
  3929. if (name.length() == 0) {
  3930. name = QString("%1 %2")
  3931. .arg(QTStr("Display"))
  3932. .arg(QString::number(i + 1));
  3933. }
  3934. QString str =
  3935. QString("%1: %2x%3 @ %4,%5")
  3936. .arg(name,
  3937. QString::number(screenGeometry.width() *
  3938. ratio),
  3939. QString::number(screenGeometry.height() *
  3940. ratio),
  3941. QString::number(screenGeometry.x()),
  3942. QString::number(screenGeometry.y()));
  3943. action = parent->addAction(str, target, slot);
  3944. action->setProperty("monitor", i);
  3945. }
  3946. }
  3947. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3948. {
  3949. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3950. QMenu popup(this);
  3951. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3952. popup.addAction(QTStr("Add"), this,
  3953. SLOT(on_actionAddScene_triggered()));
  3954. if (item) {
  3955. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  3956. copyFilters->setEnabled(false);
  3957. connect(copyFilters, SIGNAL(triggered()), this,
  3958. SLOT(SceneCopyFilters()));
  3959. QAction *pasteFilters =
  3960. new QAction(QTStr("Paste.Filters"), this);
  3961. pasteFilters->setEnabled(copyFiltersString);
  3962. connect(pasteFilters, SIGNAL(triggered()), this,
  3963. SLOT(ScenePasteFilters()));
  3964. popup.addSeparator();
  3965. popup.addAction(QTStr("Duplicate"), this,
  3966. SLOT(DuplicateSelectedScene()));
  3967. popup.addAction(copyFilters);
  3968. popup.addAction(pasteFilters);
  3969. popup.addSeparator();
  3970. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3971. popup.addAction(QTStr("Remove"), this,
  3972. SLOT(RemoveSelectedScene()));
  3973. popup.addSeparator();
  3974. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3975. SLOT(on_actionSceneUp_triggered()));
  3976. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3977. this, SLOT(on_actionSceneDown_triggered()));
  3978. order.addSeparator();
  3979. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3980. this, SLOT(MoveSceneToTop()));
  3981. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3982. this, SLOT(MoveSceneToBottom()));
  3983. popup.addMenu(&order);
  3984. popup.addSeparator();
  3985. delete sceneProjectorMenu;
  3986. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3987. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3988. SLOT(OpenSceneProjector()));
  3989. popup.addMenu(sceneProjectorMenu);
  3990. QAction *sceneWindow = popup.addAction(
  3991. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3992. popup.addAction(sceneWindow);
  3993. popup.addAction(QTStr("Screenshot.Scene"), this,
  3994. SLOT(ScreenshotScene()));
  3995. popup.addSeparator();
  3996. popup.addAction(QTStr("Filters"), this,
  3997. SLOT(OpenSceneFilters()));
  3998. popup.addSeparator();
  3999. delete perSceneTransitionMenu;
  4000. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4001. popup.addMenu(perSceneTransitionMenu);
  4002. /* ---------------------- */
  4003. QAction *multiviewAction =
  4004. popup.addAction(QTStr("ShowInMultiview"));
  4005. OBSSource source = GetCurrentSceneSource();
  4006. OBSData data = obs_source_get_private_settings(source);
  4007. obs_data_release(data);
  4008. obs_data_set_default_bool(data, "show_in_multiview", true);
  4009. bool show = obs_data_get_bool(data, "show_in_multiview");
  4010. multiviewAction->setCheckable(true);
  4011. multiviewAction->setChecked(show);
  4012. auto showInMultiview = [](OBSData data) {
  4013. bool show =
  4014. obs_data_get_bool(data, "show_in_multiview");
  4015. obs_data_set_bool(data, "show_in_multiview", !show);
  4016. OBSProjector::UpdateMultiviewProjectors();
  4017. };
  4018. connect(multiviewAction, &QAction::triggered,
  4019. std::bind(showInMultiview, data));
  4020. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4021. }
  4022. popup.addSeparator();
  4023. bool grid = ui->scenes->GetGridMode();
  4024. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4025. : QTStr("Basic.Main.GridMode"),
  4026. this);
  4027. connect(gridAction, SIGNAL(triggered()), this,
  4028. SLOT(GridActionClicked()));
  4029. popup.addAction(gridAction);
  4030. popup.exec(QCursor::pos());
  4031. }
  4032. void OBSBasic::GridActionClicked()
  4033. {
  4034. bool gridMode = !ui->scenes->GetGridMode();
  4035. ui->scenes->SetGridMode(gridMode);
  4036. }
  4037. void OBSBasic::on_actionAddScene_triggered()
  4038. {
  4039. string name;
  4040. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4041. int i = 2;
  4042. QString placeHolderText = format.arg(i);
  4043. obs_source_t *source = nullptr;
  4044. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4045. obs_source_release(source);
  4046. placeHolderText = format.arg(++i);
  4047. }
  4048. bool accepted = NameDialog::AskForName(
  4049. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4050. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4051. if (accepted) {
  4052. if (name.empty()) {
  4053. OBSMessageBox::warning(this,
  4054. QTStr("NoNameEntered.Title"),
  4055. QTStr("NoNameEntered.Text"));
  4056. on_actionAddScene_triggered();
  4057. return;
  4058. }
  4059. obs_source_t *source = obs_get_source_by_name(name.c_str());
  4060. if (source) {
  4061. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4062. QTStr("NameExists.Text"));
  4063. obs_source_release(source);
  4064. on_actionAddScene_triggered();
  4065. return;
  4066. }
  4067. auto undo_fn = [](const std::string &data) {
  4068. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4069. if (t) {
  4070. obs_source_release(t);
  4071. obs_source_remove(t);
  4072. }
  4073. };
  4074. auto redo_fn = [this](const std::string &data) {
  4075. obs_scene_t *scene = obs_scene_create(data.c_str());
  4076. obs_source_t *source = obs_scene_get_source(scene);
  4077. SetCurrentScene(source, true);
  4078. obs_scene_release(scene);
  4079. };
  4080. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4081. undo_fn, redo_fn, name, name);
  4082. obs_scene_t *scene = obs_scene_create(name.c_str());
  4083. source = obs_scene_get_source(scene);
  4084. SetCurrentScene(source);
  4085. RefreshSources(scene);
  4086. obs_scene_release(scene);
  4087. }
  4088. }
  4089. void OBSBasic::on_actionRemoveScene_triggered()
  4090. {
  4091. RemoveSelectedScene();
  4092. }
  4093. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4094. {
  4095. int idx = ui->scenes->currentRow();
  4096. if (idx == -1 || idx == invalidIdx)
  4097. return;
  4098. ui->scenes->blockSignals(true);
  4099. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4100. if (!relative)
  4101. idx = 0;
  4102. ui->scenes->insertItem(idx + offset, item);
  4103. ui->scenes->setCurrentRow(idx + offset);
  4104. item->setSelected(true);
  4105. ui->scenes->blockSignals(false);
  4106. OBSProjector::UpdateMultiviewProjectors();
  4107. }
  4108. void OBSBasic::on_actionSceneUp_triggered()
  4109. {
  4110. ChangeSceneIndex(true, -1, 0);
  4111. }
  4112. void OBSBasic::on_actionSceneDown_triggered()
  4113. {
  4114. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4115. }
  4116. void OBSBasic::MoveSceneToTop()
  4117. {
  4118. ChangeSceneIndex(false, 0, 0);
  4119. }
  4120. void OBSBasic::MoveSceneToBottom()
  4121. {
  4122. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4123. ui->scenes->count() - 1);
  4124. }
  4125. void OBSBasic::EditSceneItemName()
  4126. {
  4127. int idx = GetTopSelectedSourceItem();
  4128. ui->sources->Edit(idx);
  4129. }
  4130. void OBSBasic::SetDeinterlacingMode()
  4131. {
  4132. QAction *action = reinterpret_cast<QAction *>(sender());
  4133. obs_deinterlace_mode mode =
  4134. (obs_deinterlace_mode)action->property("mode").toInt();
  4135. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4136. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4137. obs_source_set_deinterlace_mode(source, mode);
  4138. }
  4139. void OBSBasic::SetDeinterlacingOrder()
  4140. {
  4141. QAction *action = reinterpret_cast<QAction *>(sender());
  4142. obs_deinterlace_field_order order =
  4143. (obs_deinterlace_field_order)action->property("order").toInt();
  4144. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4145. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4146. obs_source_set_deinterlace_field_order(source, order);
  4147. }
  4148. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4149. {
  4150. obs_deinterlace_mode deinterlaceMode =
  4151. obs_source_get_deinterlace_mode(source);
  4152. obs_deinterlace_field_order deinterlaceOrder =
  4153. obs_source_get_deinterlace_field_order(source);
  4154. QAction *action;
  4155. #define ADD_MODE(name, mode) \
  4156. action = menu->addAction(QTStr("" name), this, \
  4157. SLOT(SetDeinterlacingMode())); \
  4158. action->setProperty("mode", (int)mode); \
  4159. action->setCheckable(true); \
  4160. action->setChecked(deinterlaceMode == mode);
  4161. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4162. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4163. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4164. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4165. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4166. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4167. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4168. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4169. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4170. #undef ADD_MODE
  4171. menu->addSeparator();
  4172. #define ADD_ORDER(name, order) \
  4173. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4174. SLOT(SetDeinterlacingOrder())); \
  4175. action->setProperty("order", (int)order); \
  4176. action->setCheckable(true); \
  4177. action->setChecked(deinterlaceOrder == order);
  4178. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4179. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4180. #undef ADD_ORDER
  4181. return menu;
  4182. }
  4183. void OBSBasic::SetScaleFilter()
  4184. {
  4185. QAction *action = reinterpret_cast<QAction *>(sender());
  4186. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4187. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4188. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4189. }
  4190. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4191. {
  4192. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4193. QAction *action;
  4194. #define ADD_MODE(name, mode) \
  4195. action = \
  4196. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  4197. action->setProperty("mode", (int)mode); \
  4198. action->setCheckable(true); \
  4199. action->setChecked(scaleFilter == mode);
  4200. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4201. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4202. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4203. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4204. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4205. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4206. #undef ADD_MODE
  4207. return menu;
  4208. }
  4209. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4210. QWidgetAction *widgetAction,
  4211. ColorSelect *select,
  4212. obs_sceneitem_t *item)
  4213. {
  4214. QAction *action;
  4215. menu->setStyleSheet(QString(
  4216. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4217. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4218. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4219. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4220. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4221. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4222. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4223. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4224. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4225. obs_data_release(privData);
  4226. obs_data_set_default_int(privData, "color-preset", 0);
  4227. int preset = obs_data_get_int(privData, "color-preset");
  4228. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  4229. action->setCheckable(true);
  4230. action->setProperty("bgColor", 0);
  4231. action->setChecked(preset == 0);
  4232. action = menu->addAction(QTStr("CustomColor"), this,
  4233. +SLOT(ColorChange()));
  4234. action->setCheckable(true);
  4235. action->setProperty("bgColor", 1);
  4236. action->setChecked(preset == 1);
  4237. menu->addSeparator();
  4238. widgetAction->setDefaultWidget(select);
  4239. for (int i = 1; i < 9; i++) {
  4240. stringstream button;
  4241. button << "preset" << i;
  4242. QPushButton *colorButton =
  4243. select->findChild<QPushButton *>(button.str().c_str());
  4244. if (preset == i + 1)
  4245. colorButton->setStyleSheet("border: 2px solid black");
  4246. colorButton->setProperty("bgColor", i);
  4247. select->connect(colorButton, SIGNAL(released()), this,
  4248. SLOT(ColorChange()));
  4249. }
  4250. menu->addAction(widgetAction);
  4251. return menu;
  4252. }
  4253. ColorSelect::ColorSelect(QWidget *parent)
  4254. : QWidget(parent), ui(new Ui::ColorSelect)
  4255. {
  4256. ui->setupUi(this);
  4257. }
  4258. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4259. {
  4260. QMenu popup(this);
  4261. delete previewProjectorSource;
  4262. delete sourceProjector;
  4263. delete scaleFilteringMenu;
  4264. delete colorMenu;
  4265. delete colorWidgetAction;
  4266. delete colorSelect;
  4267. delete deinterlaceMenu;
  4268. if (preview) {
  4269. QAction *action = popup.addAction(
  4270. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4271. SLOT(TogglePreview()));
  4272. action->setCheckable(true);
  4273. action->setChecked(
  4274. obs_display_enabled(ui->preview->GetDisplay()));
  4275. if (IsPreviewProgramMode())
  4276. action->setEnabled(false);
  4277. popup.addAction(ui->actionLockPreview);
  4278. popup.addMenu(ui->scalingMenu);
  4279. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4280. AddProjectorMenuMonitors(previewProjectorSource, this,
  4281. SLOT(OpenPreviewProjector()));
  4282. popup.addMenu(previewProjectorSource);
  4283. QAction *previewWindow =
  4284. popup.addAction(QTStr("PreviewWindow"), this,
  4285. SLOT(OpenPreviewWindow()));
  4286. popup.addAction(previewWindow);
  4287. popup.addAction(QTStr("Screenshot.Preview"), this,
  4288. SLOT(ScreenshotScene()));
  4289. popup.addSeparator();
  4290. }
  4291. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4292. if (addSourceMenu)
  4293. popup.addMenu(addSourceMenu);
  4294. ui->actionCopyFilters->setEnabled(false);
  4295. ui->actionCopySource->setEnabled(false);
  4296. if (ui->sources->MultipleBaseSelected()) {
  4297. popup.addSeparator();
  4298. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4299. SLOT(GroupSelectedItems()));
  4300. } else if (ui->sources->GroupsSelected()) {
  4301. popup.addSeparator();
  4302. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4303. SLOT(UngroupSelectedGroups()));
  4304. }
  4305. popup.addSeparator();
  4306. popup.addAction(ui->actionCopySource);
  4307. popup.addAction(ui->actionPasteRef);
  4308. popup.addAction(ui->actionPasteDup);
  4309. popup.addSeparator();
  4310. popup.addSeparator();
  4311. popup.addAction(ui->actionCopyFilters);
  4312. popup.addAction(ui->actionPasteFilters);
  4313. popup.addSeparator();
  4314. if (idx != -1) {
  4315. if (addSourceMenu)
  4316. popup.addSeparator();
  4317. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4318. bool lock = obs_sceneitem_locked(sceneItem);
  4319. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4320. uint32_t flags = obs_source_get_output_flags(source);
  4321. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4322. OBS_SOURCE_ASYNC_VIDEO;
  4323. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4324. QAction *action;
  4325. colorMenu = new QMenu(QTStr("ChangeBG"));
  4326. colorWidgetAction = new QWidgetAction(colorMenu);
  4327. colorSelect = new ColorSelect(colorMenu);
  4328. popup.addMenu(AddBackgroundColorMenu(
  4329. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4330. popup.addAction(QTStr("Rename"), this,
  4331. SLOT(EditSceneItemName()));
  4332. popup.addAction(QTStr("Remove"), this,
  4333. SLOT(on_actionRemoveSource_triggered()));
  4334. popup.addSeparator();
  4335. popup.addMenu(ui->orderMenu);
  4336. popup.addMenu(ui->transformMenu);
  4337. ui->actionResetTransform->setEnabled(!lock);
  4338. ui->actionRotate90CW->setEnabled(!lock);
  4339. ui->actionRotate90CCW->setEnabled(!lock);
  4340. ui->actionRotate180->setEnabled(!lock);
  4341. ui->actionFlipHorizontal->setEnabled(!lock);
  4342. ui->actionFlipVertical->setEnabled(!lock);
  4343. ui->actionFitToScreen->setEnabled(!lock);
  4344. ui->actionStretchToScreen->setEnabled(!lock);
  4345. ui->actionCenterToScreen->setEnabled(!lock);
  4346. ui->actionVerticalCenter->setEnabled(!lock);
  4347. ui->actionHorizontalCenter->setEnabled(!lock);
  4348. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4349. AddProjectorMenuMonitors(sourceProjector, this,
  4350. SLOT(OpenSourceProjector()));
  4351. QAction *sourceWindow = popup.addAction(
  4352. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  4353. popup.addAction(sourceWindow);
  4354. popup.addSeparator();
  4355. if (hasAudio) {
  4356. QAction *actionHideMixer =
  4357. popup.addAction(QTStr("HideMixer"), this,
  4358. SLOT(ToggleHideMixer()));
  4359. actionHideMixer->setCheckable(true);
  4360. actionHideMixer->setChecked(SourceMixerHidden(source));
  4361. }
  4362. if (isAsyncVideo) {
  4363. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4364. popup.addMenu(
  4365. AddDeinterlacingMenu(deinterlaceMenu, source));
  4366. popup.addSeparator();
  4367. }
  4368. QAction *resizeOutput =
  4369. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  4370. SLOT(ResizeOutputSizeOfSource()));
  4371. int width = obs_source_get_width(source);
  4372. int height = obs_source_get_height(source);
  4373. resizeOutput->setEnabled(!obs_video_active());
  4374. if (width < 8 || height < 8)
  4375. resizeOutput->setEnabled(false);
  4376. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4377. popup.addMenu(
  4378. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4379. popup.addSeparator();
  4380. popup.addMenu(sourceProjector);
  4381. popup.addAction(sourceWindow);
  4382. popup.addAction(QTStr("Screenshot.Source"), this,
  4383. SLOT(ScreenshotSelectedSource()));
  4384. popup.addSeparator();
  4385. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4386. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4387. popup.addSeparator();
  4388. action = popup.addAction(QTStr("Interact"), this,
  4389. SLOT(on_actionInteract_triggered()));
  4390. action->setEnabled(obs_source_get_output_flags(source) &
  4391. OBS_SOURCE_INTERACTION);
  4392. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4393. popup.addAction(QTStr("Properties"), this,
  4394. SLOT(on_actionSourceProperties_triggered()));
  4395. ui->actionCopyFilters->setEnabled(
  4396. obs_source_filter_count(source) > 0);
  4397. ui->actionCopySource->setEnabled(true);
  4398. }
  4399. ui->actionPasteFilters->setEnabled(copyFiltersString && idx != -1);
  4400. popup.exec(QCursor::pos());
  4401. }
  4402. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4403. {
  4404. if (ui->scenes->count()) {
  4405. QModelIndex idx = ui->sources->indexAt(pos);
  4406. CreateSourcePopupMenu(idx.row(), false);
  4407. }
  4408. }
  4409. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4410. {
  4411. if (!witem)
  4412. return;
  4413. if (IsPreviewProgramMode()) {
  4414. bool doubleClickSwitch =
  4415. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4416. "TransitionOnDoubleClick");
  4417. if (doubleClickSwitch)
  4418. TransitionClicked();
  4419. }
  4420. }
  4421. void OBSBasic::AddSource(const char *id)
  4422. {
  4423. if (id && *id) {
  4424. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  4425. sourceSelect.exec();
  4426. if (sourceSelect.newSource && strcmp(id, "group") != 0) {
  4427. CreatePropertiesWindow(sourceSelect.newSource);
  4428. }
  4429. }
  4430. }
  4431. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4432. {
  4433. const char *unversioned_type;
  4434. const char *type;
  4435. bool foundValues = false;
  4436. bool foundDeprecated = false;
  4437. size_t idx = 0;
  4438. QMenu *popup = new QMenu(QTStr("Add"), this);
  4439. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4440. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4441. QList<QAction *> actions = menu->actions();
  4442. for (QAction *menuAction : actions) {
  4443. if (menuAction->text().compare(name) >= 0)
  4444. return menuAction;
  4445. }
  4446. return (QAction *)nullptr;
  4447. };
  4448. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4449. const char *name) {
  4450. QString qname = QT_UTF8(name);
  4451. QAction *popupItem = new QAction(qname, this);
  4452. popupItem->setData(QT_UTF8(type));
  4453. connect(popupItem, SIGNAL(triggered(bool)), this,
  4454. SLOT(AddSourceFromAction()));
  4455. QIcon icon;
  4456. if (strcmp(type, "scene") == 0)
  4457. icon = GetSceneIcon();
  4458. else
  4459. icon = GetSourceIcon(type);
  4460. popupItem->setIcon(icon);
  4461. QAction *after = getActionAfter(popup, qname);
  4462. popup->insertAction(after, popupItem);
  4463. };
  4464. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4465. const char *name = obs_source_get_display_name(type);
  4466. uint32_t caps = obs_get_source_output_flags(type);
  4467. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4468. continue;
  4469. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4470. addSource(popup, unversioned_type, name);
  4471. } else {
  4472. addSource(deprecated, unversioned_type, name);
  4473. foundDeprecated = true;
  4474. }
  4475. foundValues = true;
  4476. }
  4477. addSource(popup, "scene", Str("Basic.Scene"));
  4478. popup->addSeparator();
  4479. QAction *addGroup = new QAction(QTStr("Group"), this);
  4480. addGroup->setData(QT_UTF8("group"));
  4481. addGroup->setIcon(GetGroupIcon());
  4482. connect(addGroup, SIGNAL(triggered(bool)), this,
  4483. SLOT(AddSourceFromAction()));
  4484. popup->addAction(addGroup);
  4485. if (!foundDeprecated) {
  4486. delete deprecated;
  4487. deprecated = nullptr;
  4488. }
  4489. if (!foundValues) {
  4490. delete popup;
  4491. popup = nullptr;
  4492. } else if (foundDeprecated) {
  4493. popup->addSeparator();
  4494. popup->addMenu(deprecated);
  4495. }
  4496. return popup;
  4497. }
  4498. void OBSBasic::AddSourceFromAction()
  4499. {
  4500. QAction *action = qobject_cast<QAction *>(sender());
  4501. if (!action)
  4502. return;
  4503. AddSource(QT_TO_UTF8(action->data().toString()));
  4504. }
  4505. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4506. {
  4507. if (!GetCurrentScene()) {
  4508. // Tell the user he needs a scene first (help beginners).
  4509. OBSMessageBox::information(
  4510. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4511. QTStr("Basic.Main.AddSourceHelp.Text"));
  4512. return;
  4513. }
  4514. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4515. if (popup)
  4516. popup->exec(pos);
  4517. }
  4518. void OBSBasic::on_actionAddSource_triggered()
  4519. {
  4520. AddSourcePopupMenu(QCursor::pos());
  4521. }
  4522. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4523. {
  4524. vector<OBSSceneItem> &items =
  4525. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4526. if (obs_sceneitem_selected(item)) {
  4527. items.emplace_back(item);
  4528. } else if (obs_sceneitem_is_group(item)) {
  4529. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4530. }
  4531. return true;
  4532. };
  4533. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  4534. std::vector<obs_source_t *> *sources)
  4535. {
  4536. obs_data_array_t *undo_array = obs_data_array_create();
  4537. if (!sources) {
  4538. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  4539. } else {
  4540. for (obs_source_t *source : *sources) {
  4541. obs_data_t *source_data = obs_save_source(source);
  4542. obs_data_array_push_back(undo_array, source_data);
  4543. obs_data_release(source_data);
  4544. }
  4545. }
  4546. obs_data_t *scene_data = obs_save_source(obs_scene_get_source(scene));
  4547. obs_data_array_push_back(undo_array, scene_data);
  4548. obs_data_release(scene_data);
  4549. OBSData data = obs_data_create();
  4550. obs_data_release(data);
  4551. obs_data_set_array(data, "array", undo_array);
  4552. obs_data_get_json(data);
  4553. obs_data_array_release(undo_array);
  4554. return data;
  4555. }
  4556. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  4557. {
  4558. auto sources = static_cast<std::vector<obs_source_t *> *>(p);
  4559. sources->push_back(obs_sceneitem_get_source(item));
  4560. return true;
  4561. }
  4562. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  4563. OBSData undo_data, OBSData redo_data)
  4564. {
  4565. auto undo_redo = [this](const std::string &json) {
  4566. obs_data_t *base = obs_data_create_from_json(json.c_str());
  4567. obs_data_array_t *array = obs_data_get_array(base, "array");
  4568. std::vector<obs_source_t *> sources;
  4569. std::vector<obs_source_t *> old_sources;
  4570. /* create missing sources */
  4571. const size_t count = obs_data_array_count(array);
  4572. sources.reserve(count);
  4573. for (size_t i = 0; i < count; i++) {
  4574. obs_data_t *data = obs_data_array_item(array, i);
  4575. const char *name = obs_data_get_string(data, "name");
  4576. obs_source_t *source = obs_get_source_by_name(name);
  4577. if (!source)
  4578. source = obs_load_source(data);
  4579. sources.push_back(source);
  4580. /* update scene/group settings to restore their
  4581. * contents to their saved settings */
  4582. obs_scene_t *scene =
  4583. obs_group_or_scene_from_source(source);
  4584. if (scene) {
  4585. obs_scene_enum_items(scene, add_source_enum,
  4586. &old_sources);
  4587. obs_data_t *scene_settings =
  4588. obs_data_get_obj(data, "settings");
  4589. obs_source_update(source, scene_settings);
  4590. obs_data_release(scene_settings);
  4591. }
  4592. obs_data_release(data);
  4593. }
  4594. for (obs_source_t *source : old_sources)
  4595. obs_source_addref(source);
  4596. /* actually load sources now */
  4597. for (obs_source_t *source : sources)
  4598. obs_source_load2(source);
  4599. /* release sources */
  4600. for (obs_source_t *source : sources)
  4601. obs_source_release(source);
  4602. for (obs_source_t *source : old_sources)
  4603. obs_source_release(source);
  4604. obs_data_array_release(array);
  4605. obs_data_release(base);
  4606. ui->sources->RefreshItems();
  4607. };
  4608. const char *undo_json = obs_data_get_last_json(undo_data);
  4609. const char *redo_json = obs_data_get_last_json(redo_data);
  4610. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  4611. redo_json);
  4612. }
  4613. void OBSBasic::on_actionRemoveSource_triggered()
  4614. {
  4615. vector<OBSSceneItem> items;
  4616. OBSScene scene = GetCurrentScene();
  4617. obs_source_t *scene_source = obs_scene_get_source(scene);
  4618. obs_scene_enum_items(scene, remove_items, &items);
  4619. if (!items.size())
  4620. return;
  4621. /* ------------------------------------- */
  4622. /* confirm action with user */
  4623. bool confirmed = false;
  4624. if (items.size() > 1) {
  4625. QString text = QTStr("ConfirmRemove.TextMultiple")
  4626. .arg(QString::number(items.size()));
  4627. QMessageBox remove_items(this);
  4628. remove_items.setText(text);
  4629. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4630. QMessageBox::YesRole);
  4631. remove_items.setDefaultButton(Yes);
  4632. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4633. remove_items.setIcon(QMessageBox::Question);
  4634. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4635. remove_items.exec();
  4636. confirmed = Yes == remove_items.clickedButton();
  4637. } else {
  4638. OBSSceneItem &item = items[0];
  4639. obs_source_t *source = obs_sceneitem_get_source(item);
  4640. if (source && QueryRemoveSource(source))
  4641. confirmed = true;
  4642. }
  4643. if (!confirmed)
  4644. return;
  4645. /* ----------------------------------------------- */
  4646. /* save undo data */
  4647. OBSData undo_data = BackupScene(scene_source);
  4648. /* ----------------------------------------------- */
  4649. /* remove items */
  4650. for (auto &item : items)
  4651. obs_sceneitem_remove(item);
  4652. /* ----------------------------------------------- */
  4653. /* save redo data */
  4654. OBSData redo_data = BackupScene(scene_source);
  4655. /* ----------------------------------------------- */
  4656. /* add undo/redo action */
  4657. QString action_name;
  4658. if (items.size() > 1) {
  4659. action_name = QTStr("Undo.Sources.Multi")
  4660. .arg(QString::number(items.size()));
  4661. } else {
  4662. QString str = QTStr("Undo.Delete");
  4663. action_name = str.arg(obs_source_get_name(
  4664. obs_sceneitem_get_source(items[0])));
  4665. }
  4666. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  4667. }
  4668. void OBSBasic::on_actionInteract_triggered()
  4669. {
  4670. OBSSceneItem item = GetCurrentSceneItem();
  4671. OBSSource source = obs_sceneitem_get_source(item);
  4672. if (source)
  4673. CreateInteractionWindow(source);
  4674. }
  4675. void OBSBasic::on_actionSourceProperties_triggered()
  4676. {
  4677. OBSSceneItem item = GetCurrentSceneItem();
  4678. OBSSource source = obs_sceneitem_get_source(item);
  4679. if (source)
  4680. CreatePropertiesWindow(source);
  4681. }
  4682. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  4683. const QString &action_name)
  4684. {
  4685. OBSSceneItem item = GetCurrentSceneItem();
  4686. obs_source_t *source = obs_sceneitem_get_source(item);
  4687. if (!source)
  4688. return;
  4689. OBSScene scene = GetCurrentScene();
  4690. std::vector<obs_source_t *> sources;
  4691. if (scene != obs_sceneitem_get_scene(item))
  4692. sources.push_back(
  4693. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  4694. OBSData undo_data = BackupScene(scene, &sources);
  4695. obs_sceneitem_set_order(item, movement);
  4696. const char *source_name = obs_source_get_name(source);
  4697. const char *scene_name =
  4698. obs_source_get_name(obs_scene_get_source(scene));
  4699. OBSData redo_data = BackupScene(scene, &sources);
  4700. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  4701. undo_data, redo_data);
  4702. }
  4703. void OBSBasic::on_actionSourceUp_triggered()
  4704. {
  4705. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4706. }
  4707. void OBSBasic::on_actionSourceDown_triggered()
  4708. {
  4709. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4710. }
  4711. void OBSBasic::on_actionMoveUp_triggered()
  4712. {
  4713. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4714. }
  4715. void OBSBasic::on_actionMoveDown_triggered()
  4716. {
  4717. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4718. }
  4719. void OBSBasic::on_actionMoveToTop_triggered()
  4720. {
  4721. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  4722. }
  4723. void OBSBasic::on_actionMoveToBottom_triggered()
  4724. {
  4725. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  4726. }
  4727. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4728. {
  4729. char logDir[512];
  4730. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4731. return nullptr;
  4732. string path = logDir;
  4733. path += "/";
  4734. path += log;
  4735. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4736. if (!file)
  4737. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4738. return file;
  4739. }
  4740. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4741. {
  4742. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4743. if (!fileString)
  4744. return;
  4745. if (!*fileString)
  4746. return;
  4747. ui->menuLogFiles->setEnabled(false);
  4748. #if defined(_WIN32)
  4749. ui->menuCrashLogs->setEnabled(false);
  4750. #endif
  4751. stringstream ss;
  4752. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4753. << CurrentDateTimeString() << "\n\n"
  4754. << fileString;
  4755. if (logUploadThread) {
  4756. logUploadThread->wait();
  4757. }
  4758. RemoteTextThread *thread =
  4759. new RemoteTextThread("https://obsproject.com/logs/upload",
  4760. "text/plain", ss.str().c_str());
  4761. logUploadThread.reset(thread);
  4762. if (crash) {
  4763. connect(thread, &RemoteTextThread::Result, this,
  4764. &OBSBasic::crashUploadFinished);
  4765. } else {
  4766. connect(thread, &RemoteTextThread::Result, this,
  4767. &OBSBasic::logUploadFinished);
  4768. }
  4769. logUploadThread->start();
  4770. }
  4771. void OBSBasic::on_actionShowLogs_triggered()
  4772. {
  4773. char logDir[512];
  4774. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4775. return;
  4776. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4777. QDesktopServices::openUrl(url);
  4778. }
  4779. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4780. {
  4781. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  4782. }
  4783. void OBSBasic::on_actionUploadLastLog_triggered()
  4784. {
  4785. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  4786. }
  4787. void OBSBasic::on_actionViewCurrentLog_triggered()
  4788. {
  4789. if (!logView)
  4790. logView = new OBSLogViewer();
  4791. logView->show();
  4792. logView->setWindowState(
  4793. (logView->windowState() & ~Qt::WindowMinimized) |
  4794. Qt::WindowActive);
  4795. logView->activateWindow();
  4796. logView->raise();
  4797. }
  4798. void OBSBasic::on_actionShowCrashLogs_triggered()
  4799. {
  4800. char logDir[512];
  4801. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4802. return;
  4803. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4804. QDesktopServices::openUrl(url);
  4805. }
  4806. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4807. {
  4808. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  4809. }
  4810. void OBSBasic::on_actionCheckForUpdates_triggered()
  4811. {
  4812. CheckForUpdates(true);
  4813. }
  4814. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4815. {
  4816. ui->menuLogFiles->setEnabled(true);
  4817. #if defined(_WIN32)
  4818. ui->menuCrashLogs->setEnabled(true);
  4819. #endif
  4820. if (text.isEmpty()) {
  4821. OBSMessageBox::critical(
  4822. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4823. error);
  4824. return;
  4825. }
  4826. openLogDialog(text, false);
  4827. }
  4828. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  4829. {
  4830. ui->menuLogFiles->setEnabled(true);
  4831. #if defined(_WIN32)
  4832. ui->menuCrashLogs->setEnabled(true);
  4833. #endif
  4834. if (text.isEmpty()) {
  4835. OBSMessageBox::critical(
  4836. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4837. error);
  4838. return;
  4839. }
  4840. openLogDialog(text, true);
  4841. }
  4842. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  4843. {
  4844. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4845. string resURL = obs_data_get_string(returnData, "url");
  4846. QString logURL = resURL.c_str();
  4847. obs_data_release(returnData);
  4848. OBSLogReply logDialog(this, logURL, crash);
  4849. logDialog.exec();
  4850. }
  4851. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4852. obs_source_t *source, const string &name)
  4853. {
  4854. const char *prevName = obs_source_get_name(source);
  4855. if (name == prevName)
  4856. return;
  4857. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4858. QListWidgetItem *listItem = listWidget->currentItem();
  4859. if (foundSource || name.empty()) {
  4860. listItem->setText(QT_UTF8(prevName));
  4861. if (foundSource) {
  4862. OBSMessageBox::warning(parent,
  4863. QTStr("NameExists.Title"),
  4864. QTStr("NameExists.Text"));
  4865. } else if (name.empty()) {
  4866. OBSMessageBox::warning(parent,
  4867. QTStr("NoNameEntered.Title"),
  4868. QTStr("NoNameEntered.Text"));
  4869. }
  4870. obs_source_release(foundSource);
  4871. } else {
  4872. auto undo = [prev = std::string(prevName)](
  4873. const std::string &data) {
  4874. obs_source_t *source =
  4875. obs_get_source_by_name(data.c_str());
  4876. obs_source_set_name(source, prev.c_str());
  4877. obs_source_release(source);
  4878. };
  4879. auto redo = [name](const std::string &data) {
  4880. obs_source_t *source =
  4881. obs_get_source_by_name(data.c_str());
  4882. obs_source_set_name(source, name.c_str());
  4883. obs_source_release(source);
  4884. };
  4885. std::string undo_data(name);
  4886. std::string redo_data(prevName);
  4887. parent->undo_s.add_action(
  4888. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  4889. undo_data, redo_data);
  4890. listItem->setText(QT_UTF8(name.c_str()));
  4891. obs_source_set_name(source, name.c_str());
  4892. }
  4893. }
  4894. void OBSBasic::SceneNameEdited(QWidget *editor,
  4895. QAbstractItemDelegate::EndEditHint endHint)
  4896. {
  4897. OBSScene scene = GetCurrentScene();
  4898. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4899. string text = QT_TO_UTF8(edit->text().trimmed());
  4900. if (!scene)
  4901. return;
  4902. obs_source_t *source = obs_scene_get_source(scene);
  4903. RenameListItem(this, ui->scenes, source, text);
  4904. ui->scenesDock->addAction(renameScene);
  4905. if (api)
  4906. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4907. UNUSED_PARAMETER(endHint);
  4908. }
  4909. void OBSBasic::OpenFilters(OBSSource source)
  4910. {
  4911. if (source == nullptr) {
  4912. OBSSceneItem item = GetCurrentSceneItem();
  4913. source = obs_sceneitem_get_source(item);
  4914. }
  4915. CreateFiltersWindow(source);
  4916. }
  4917. void OBSBasic::OpenProperties(OBSSource source)
  4918. {
  4919. if (source == nullptr) {
  4920. OBSSceneItem item = GetCurrentSceneItem();
  4921. source = obs_sceneitem_get_source(item);
  4922. }
  4923. CreatePropertiesWindow(source);
  4924. }
  4925. void OBSBasic::OpenSceneFilters()
  4926. {
  4927. OBSScene scene = GetCurrentScene();
  4928. OBSSource source = obs_scene_get_source(scene);
  4929. CreateFiltersWindow(source);
  4930. }
  4931. #define RECORDING_START \
  4932. "==== Recording Start ==============================================="
  4933. #define RECORDING_STOP \
  4934. "==== Recording Stop ================================================"
  4935. #define REPLAY_BUFFER_START \
  4936. "==== Replay Buffer Start ==========================================="
  4937. #define REPLAY_BUFFER_STOP \
  4938. "==== Replay Buffer Stop ============================================"
  4939. #define STREAMING_START \
  4940. "==== Streaming Start ==============================================="
  4941. #define STREAMING_STOP \
  4942. "==== Streaming Stop ================================================"
  4943. #define VIRTUAL_CAM_START \
  4944. "==== Virtual Camera Start =========================================="
  4945. #define VIRTUAL_CAM_STOP \
  4946. "==== Virtual Camera Stop ==========================================="
  4947. void OBSBasic::DisplayStreamStartError()
  4948. {
  4949. QString message = !outputHandler->lastError.empty()
  4950. ? QTStr(outputHandler->lastError.c_str())
  4951. : QTStr("Output.StartFailedGeneric");
  4952. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4953. ui->streamButton->setEnabled(true);
  4954. ui->streamButton->setChecked(false);
  4955. if (sysTrayStream) {
  4956. sysTrayStream->setText(ui->streamButton->text());
  4957. sysTrayStream->setEnabled(true);
  4958. }
  4959. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  4960. }
  4961. #if YOUTUBE_ENABLED
  4962. void OBSBasic::YouTubeActionDialogOk(const QString &id, const QString &key,
  4963. bool autostart, bool autostop)
  4964. {
  4965. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  4966. obs_service_t *service_obj = GetService();
  4967. obs_data_t *settings = obs_service_get_settings(service_obj);
  4968. const std::string a_key = QT_TO_UTF8(key);
  4969. obs_data_set_string(settings, "key", a_key.c_str());
  4970. const std::string an_id = QT_TO_UTF8(id);
  4971. obs_data_set_string(settings, "stream_id", an_id.c_str());
  4972. obs_service_update(service_obj, settings);
  4973. autoStartBroadcast = autostart;
  4974. autoStopBroadcast = autostop;
  4975. obs_data_release(settings);
  4976. }
  4977. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  4978. {
  4979. YoutubeApiWrappers *apiYouTube(
  4980. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  4981. if (!apiYouTube) {
  4982. /* technically we should never get here -Jim */
  4983. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  4984. Qt::QueuedConnection);
  4985. youtubeStreamCheckThread->deleteLater();
  4986. blog(LOG_ERROR, "==========================================");
  4987. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  4988. blog(LOG_ERROR, "==========================================");
  4989. return;
  4990. }
  4991. int timeout = 0;
  4992. json11::Json json;
  4993. QString id = key.c_str();
  4994. for (;;) {
  4995. if (timeout == 14) {
  4996. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  4997. Qt::QueuedConnection);
  4998. break;
  4999. }
  5000. if (!apiYouTube->FindStream(id, json)) {
  5001. QMetaObject::invokeMethod(this,
  5002. "DisplayStreamStartError",
  5003. Qt::QueuedConnection);
  5004. QMetaObject::invokeMethod(this, "StopStreaming",
  5005. Qt::QueuedConnection);
  5006. break;
  5007. }
  5008. auto item = json["items"][0];
  5009. auto status = item["status"]["streamStatus"].string_value();
  5010. if (status == "active") {
  5011. QMetaObject::invokeMethod(ui->broadcastButton,
  5012. "setEnabled",
  5013. Q_ARG(bool, true));
  5014. break;
  5015. } else {
  5016. QThread::sleep(1);
  5017. timeout++;
  5018. }
  5019. }
  5020. youtubeStreamCheckThread->deleteLater();
  5021. }
  5022. void OBSBasic::ShowYouTubeAutoStartWarning()
  5023. {
  5024. auto msgBox = []() {
  5025. QMessageBox msgbox(App()->GetMainWindow());
  5026. msgbox.setWindowTitle(QTStr(
  5027. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5028. msgbox.setText(
  5029. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5030. msgbox.setIcon(QMessageBox::Icon::Information);
  5031. msgbox.addButton(QMessageBox::Ok);
  5032. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5033. msgbox.setCheckBox(cb);
  5034. msgbox.exec();
  5035. if (cb->isChecked()) {
  5036. config_set_bool(App()->GlobalConfig(), "General",
  5037. "WarnedAboutYouTubeAutoStart", true);
  5038. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5039. }
  5040. };
  5041. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5042. "WarnedAboutYouTubeAutoStart");
  5043. if (!warned) {
  5044. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5045. Q_ARG(VoidFunc, msgBox));
  5046. }
  5047. }
  5048. #endif
  5049. void OBSBasic::StartStreaming()
  5050. {
  5051. if (outputHandler->StreamingActive())
  5052. return;
  5053. if (disableOutputsRef)
  5054. return;
  5055. Auth *auth = GetAuth();
  5056. if (auth) {
  5057. auth->OnStreamConfig();
  5058. #if YOUTUBE_ENABLED
  5059. if (!broadcastActive && autoStartBroadcast &&
  5060. IsYouTubeService(auth->service())) {
  5061. OBSYoutubeActions *dialog;
  5062. dialog = new OBSYoutubeActions(this, auth);
  5063. connect(dialog, &OBSYoutubeActions::ok, this,
  5064. &OBSBasic::YouTubeActionDialogOk);
  5065. int result = dialog->Valid() ? dialog->exec()
  5066. : QDialog::Rejected;
  5067. if (result != QDialog::Accepted) {
  5068. ui->streamButton->setText(
  5069. QTStr("Basic.Main.StartStreaming"));
  5070. ui->streamButton->setEnabled(true);
  5071. ui->streamButton->setChecked(false);
  5072. if (sysTrayStream) {
  5073. sysTrayStream->setText(
  5074. ui->streamButton->text());
  5075. sysTrayStream->setEnabled(true);
  5076. }
  5077. return;
  5078. }
  5079. }
  5080. #endif
  5081. }
  5082. if (!outputHandler->SetupStreaming(service)) {
  5083. DisplayStreamStartError();
  5084. return;
  5085. }
  5086. if (api)
  5087. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5088. SaveProject();
  5089. ui->streamButton->setEnabled(false);
  5090. ui->streamButton->setChecked(false);
  5091. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5092. if (sysTrayStream) {
  5093. sysTrayStream->setEnabled(false);
  5094. sysTrayStream->setText(ui->streamButton->text());
  5095. }
  5096. if (!outputHandler->StartStreaming(service)) {
  5097. DisplayStreamStartError();
  5098. return;
  5099. }
  5100. if (!autoStartBroadcast) {
  5101. ui->broadcastButton->setVisible(true);
  5102. ui->broadcastButton->setText(
  5103. QTStr("Basic.Main.StartBroadcast"));
  5104. ui->broadcastButton->setProperty("broadcastState", "ready");
  5105. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5106. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5107. // well, we need to disable button while stream is not active
  5108. #if YOUTUBE_ENABLED
  5109. // get a current stream key
  5110. obs_service_t *service_obj = GetService();
  5111. obs_data_t *settings = obs_service_get_settings(service_obj);
  5112. std::string key = obs_data_get_string(settings, "stream_id");
  5113. if (!key.empty() && !youtubeStreamCheckThread) {
  5114. ui->broadcastButton->setEnabled(false);
  5115. youtubeStreamCheckThread = CreateQThread(
  5116. [this, key] { YoutubeStreamCheck(key); });
  5117. youtubeStreamCheckThread->setObjectName(
  5118. "YouTubeStreamCheckThread");
  5119. youtubeStreamCheckThread->start();
  5120. }
  5121. #endif
  5122. } else if (!autoStopBroadcast) {
  5123. broadcastActive = true;
  5124. ui->broadcastButton->setVisible(true);
  5125. ui->broadcastButton->setText(QTStr("Basic.Main.StopBroadcast"));
  5126. ui->broadcastButton->setProperty("broadcastState", "active");
  5127. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5128. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5129. }
  5130. bool recordWhenStreaming = config_get_bool(
  5131. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5132. if (recordWhenStreaming)
  5133. StartRecording();
  5134. bool replayBufferWhileStreaming = config_get_bool(
  5135. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5136. if (replayBufferWhileStreaming)
  5137. StartReplayBuffer();
  5138. #if YOUTUBE_ENABLED
  5139. if (!autoStartBroadcast)
  5140. OBSBasic::ShowYouTubeAutoStartWarning();
  5141. #endif
  5142. }
  5143. void OBSBasic::BroadcastButtonClicked()
  5144. {
  5145. if (!autoStartBroadcast) {
  5146. #if YOUTUBE_ENABLED
  5147. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5148. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5149. if (ytAuth.get()) {
  5150. ytAuth->StartLatestBroadcast();
  5151. }
  5152. #endif
  5153. broadcastActive = true;
  5154. autoStartBroadcast = true; // and clear the flag
  5155. if (!autoStopBroadcast) {
  5156. ui->broadcastButton->setText(
  5157. QTStr("Basic.Main.StopBroadcast"));
  5158. ui->broadcastButton->setProperty("broadcastState",
  5159. "active");
  5160. ui->broadcastButton->style()->unpolish(
  5161. ui->broadcastButton);
  5162. ui->broadcastButton->style()->polish(
  5163. ui->broadcastButton);
  5164. } else {
  5165. ui->broadcastButton->setVisible(false);
  5166. }
  5167. } else if (!autoStopBroadcast) {
  5168. #if YOUTUBE_ENABLED
  5169. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5170. "WarnBeforeStoppingStream");
  5171. if (confirm && isVisible()) {
  5172. QMessageBox::StandardButton button = OBSMessageBox::question(
  5173. this, QTStr("ConfirmStop.Title"),
  5174. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5175. QMessageBox::Yes | QMessageBox::No,
  5176. QMessageBox::No);
  5177. if (button == QMessageBox::No) {
  5178. return;
  5179. }
  5180. }
  5181. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5182. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5183. if (ytAuth.get()) {
  5184. ytAuth->StopLatestBroadcast();
  5185. }
  5186. #endif
  5187. broadcastActive = false;
  5188. autoStopBroadcast = true;
  5189. ui->broadcastButton->setVisible(false);
  5190. QMetaObject::invokeMethod(this, "StopStreaming");
  5191. }
  5192. }
  5193. #ifdef _WIN32
  5194. static inline void UpdateProcessPriority()
  5195. {
  5196. const char *priority = config_get_string(App()->GlobalConfig(),
  5197. "General", "ProcessPriority");
  5198. if (priority && strcmp(priority, "Normal") != 0)
  5199. SetProcessPriority(priority);
  5200. }
  5201. static inline void ClearProcessPriority()
  5202. {
  5203. const char *priority = config_get_string(App()->GlobalConfig(),
  5204. "General", "ProcessPriority");
  5205. if (priority && strcmp(priority, "Normal") != 0)
  5206. SetProcessPriority("Normal");
  5207. }
  5208. #else
  5209. #define UpdateProcessPriority() \
  5210. do { \
  5211. } while (false)
  5212. #define ClearProcessPriority() \
  5213. do { \
  5214. } while (false)
  5215. #endif
  5216. inline void OBSBasic::OnActivate()
  5217. {
  5218. if (ui->profileMenu->isEnabled()) {
  5219. ui->profileMenu->setEnabled(false);
  5220. ui->autoConfigure->setEnabled(false);
  5221. App()->IncrementSleepInhibition();
  5222. UpdateProcessPriority();
  5223. if (trayIcon && trayIcon->isVisible()) {
  5224. #ifdef __APPLE__
  5225. QIcon trayMask =
  5226. QIcon(":/res/images/tray_active_macos.png");
  5227. trayMask.setIsMask(true);
  5228. trayIcon->setIcon(
  5229. QIcon::fromTheme("obs-tray", trayMask));
  5230. #else
  5231. trayIcon->setIcon(QIcon::fromTheme(
  5232. "obs-tray-active",
  5233. QIcon(":/res/images/tray_active.png")));
  5234. #endif
  5235. }
  5236. }
  5237. }
  5238. extern volatile bool recording_paused;
  5239. extern volatile bool replaybuf_active;
  5240. inline void OBSBasic::OnDeactivate()
  5241. {
  5242. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5243. ui->profileMenu->setEnabled(true);
  5244. ui->autoConfigure->setEnabled(true);
  5245. App()->DecrementSleepInhibition();
  5246. ClearProcessPriority();
  5247. if (trayIcon && trayIcon->isVisible()) {
  5248. #ifdef __APPLE__
  5249. QIcon trayIconFile =
  5250. QIcon(":/res/images/obs_macos.png");
  5251. trayIconFile.setIsMask(true);
  5252. #else
  5253. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5254. #endif
  5255. trayIcon->setIcon(
  5256. QIcon::fromTheme("obs-tray", trayIconFile));
  5257. }
  5258. } else if (outputHandler->Active() && trayIcon &&
  5259. trayIcon->isVisible()) {
  5260. if (os_atomic_load_bool(&recording_paused)) {
  5261. #ifdef __APPLE__
  5262. QIcon trayIconFile =
  5263. QIcon(":/res/images/obs_paused_macos.png");
  5264. trayIconFile.setIsMask(true);
  5265. #else
  5266. QIcon trayIconFile =
  5267. QIcon(":/res/images/obs_paused.png");
  5268. #endif
  5269. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5270. trayIconFile));
  5271. } else {
  5272. #ifdef __APPLE__
  5273. QIcon trayIconFile =
  5274. QIcon(":/res/images/tray_active_macos.png");
  5275. trayIconFile.setIsMask(true);
  5276. #else
  5277. QIcon trayIconFile =
  5278. QIcon(":/res/images/tray_active.png");
  5279. #endif
  5280. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5281. trayIconFile));
  5282. }
  5283. }
  5284. }
  5285. void OBSBasic::StopStreaming()
  5286. {
  5287. SaveProject();
  5288. if (outputHandler->StreamingActive())
  5289. outputHandler->StopStreaming(streamingStopping);
  5290. // special case: force reset broadcast state if
  5291. // no autostart and no autostop selected
  5292. if (!autoStartBroadcast && !broadcastActive) {
  5293. broadcastActive = false;
  5294. autoStartBroadcast = true;
  5295. autoStopBroadcast = true;
  5296. ui->broadcastButton->setVisible(false);
  5297. }
  5298. if (autoStopBroadcast)
  5299. broadcastActive = false;
  5300. OnDeactivate();
  5301. bool recordWhenStreaming = config_get_bool(
  5302. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5303. bool keepRecordingWhenStreamStops =
  5304. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5305. "KeepRecordingWhenStreamStops");
  5306. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5307. StopRecording();
  5308. bool replayBufferWhileStreaming = config_get_bool(
  5309. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5310. bool keepReplayBufferStreamStops =
  5311. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5312. "KeepReplayBufferStreamStops");
  5313. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5314. StopReplayBuffer();
  5315. }
  5316. void OBSBasic::ForceStopStreaming()
  5317. {
  5318. SaveProject();
  5319. if (outputHandler->StreamingActive())
  5320. outputHandler->StopStreaming(true);
  5321. OnDeactivate();
  5322. bool recordWhenStreaming = config_get_bool(
  5323. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5324. bool keepRecordingWhenStreamStops =
  5325. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5326. "KeepRecordingWhenStreamStops");
  5327. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5328. StopRecording();
  5329. bool replayBufferWhileStreaming = config_get_bool(
  5330. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5331. bool keepReplayBufferStreamStops =
  5332. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5333. "KeepReplayBufferStreamStops");
  5334. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5335. StopReplayBuffer();
  5336. }
  5337. void OBSBasic::StreamDelayStarting(int sec)
  5338. {
  5339. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5340. ui->streamButton->setEnabled(true);
  5341. ui->streamButton->setChecked(true);
  5342. if (sysTrayStream) {
  5343. sysTrayStream->setText(ui->streamButton->text());
  5344. sysTrayStream->setEnabled(true);
  5345. }
  5346. if (!startStreamMenu.isNull())
  5347. startStreamMenu->deleteLater();
  5348. startStreamMenu = new QMenu();
  5349. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  5350. SLOT(StopStreaming()));
  5351. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5352. SLOT(ForceStopStreaming()));
  5353. ui->streamButton->setMenu(startStreamMenu);
  5354. ui->statusbar->StreamDelayStarting(sec);
  5355. OnActivate();
  5356. }
  5357. void OBSBasic::StreamDelayStopping(int sec)
  5358. {
  5359. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5360. ui->streamButton->setEnabled(true);
  5361. ui->streamButton->setChecked(false);
  5362. if (sysTrayStream) {
  5363. sysTrayStream->setText(ui->streamButton->text());
  5364. sysTrayStream->setEnabled(true);
  5365. }
  5366. if (!startStreamMenu.isNull())
  5367. startStreamMenu->deleteLater();
  5368. startStreamMenu = new QMenu();
  5369. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  5370. SLOT(StartStreaming()));
  5371. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5372. SLOT(ForceStopStreaming()));
  5373. ui->streamButton->setMenu(startStreamMenu);
  5374. ui->statusbar->StreamDelayStopping(sec);
  5375. if (api)
  5376. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5377. }
  5378. void OBSBasic::StreamingStart()
  5379. {
  5380. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5381. ui->streamButton->setEnabled(true);
  5382. ui->streamButton->setChecked(true);
  5383. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  5384. if (sysTrayStream) {
  5385. sysTrayStream->setText(ui->streamButton->text());
  5386. sysTrayStream->setEnabled(true);
  5387. }
  5388. if (api)
  5389. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  5390. OnActivate();
  5391. blog(LOG_INFO, STREAMING_START);
  5392. }
  5393. void OBSBasic::StreamStopping()
  5394. {
  5395. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  5396. if (sysTrayStream)
  5397. sysTrayStream->setText(ui->streamButton->text());
  5398. streamingStopping = true;
  5399. if (api)
  5400. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5401. }
  5402. void OBSBasic::StreamingStop(int code, QString last_error)
  5403. {
  5404. const char *errorDescription = "";
  5405. DStr errorMessage;
  5406. bool use_last_error = false;
  5407. bool encode_error = false;
  5408. switch (code) {
  5409. case OBS_OUTPUT_BAD_PATH:
  5410. errorDescription = Str("Output.ConnectFail.BadPath");
  5411. break;
  5412. case OBS_OUTPUT_CONNECT_FAILED:
  5413. use_last_error = true;
  5414. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  5415. break;
  5416. case OBS_OUTPUT_INVALID_STREAM:
  5417. errorDescription = Str("Output.ConnectFail.InvalidStream");
  5418. break;
  5419. case OBS_OUTPUT_ENCODE_ERROR:
  5420. encode_error = true;
  5421. break;
  5422. default:
  5423. case OBS_OUTPUT_ERROR:
  5424. use_last_error = true;
  5425. errorDescription = Str("Output.ConnectFail.Error");
  5426. break;
  5427. case OBS_OUTPUT_DISCONNECTED:
  5428. /* doesn't happen if output is set to reconnect. note that
  5429. * reconnects are handled in the output, not in the UI */
  5430. use_last_error = true;
  5431. errorDescription = Str("Output.ConnectFail.Disconnected");
  5432. }
  5433. if (use_last_error && !last_error.isEmpty())
  5434. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5435. QT_TO_UTF8(last_error));
  5436. else
  5437. dstr_copy(errorMessage, errorDescription);
  5438. ui->statusbar->StreamStopped();
  5439. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5440. ui->streamButton->setEnabled(true);
  5441. ui->streamButton->setChecked(false);
  5442. if (sysTrayStream) {
  5443. sysTrayStream->setText(ui->streamButton->text());
  5444. sysTrayStream->setEnabled(true);
  5445. }
  5446. streamingStopping = false;
  5447. if (api)
  5448. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  5449. OnDeactivate();
  5450. blog(LOG_INFO, STREAMING_STOP);
  5451. if (encode_error) {
  5452. OBSMessageBox::information(
  5453. this, QTStr("Output.StreamEncodeError.Title"),
  5454. QTStr("Output.StreamEncodeError.Msg"));
  5455. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5456. OBSMessageBox::information(this,
  5457. QTStr("Output.ConnectFail.Title"),
  5458. QT_UTF8(errorMessage));
  5459. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5460. SysTrayNotify(QT_UTF8(errorDescription),
  5461. QSystemTrayIcon::Warning);
  5462. }
  5463. if (!startStreamMenu.isNull()) {
  5464. ui->streamButton->setMenu(nullptr);
  5465. startStreamMenu->deleteLater();
  5466. startStreamMenu = nullptr;
  5467. }
  5468. }
  5469. void OBSBasic::AutoRemux(QString input)
  5470. {
  5471. bool autoRemux = config_get_bool(Config(), "Video", "AutoRemux");
  5472. if (!autoRemux)
  5473. return;
  5474. const char *recType = config_get_string(Config(), "AdvOut", "RecType");
  5475. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  5476. if (ffmpegOutput)
  5477. return;
  5478. if (input.isEmpty())
  5479. return;
  5480. QFileInfo fi(input);
  5481. QString suffix = fi.suffix();
  5482. /* do not remux if lossless */
  5483. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  5484. return;
  5485. }
  5486. QString path = fi.path();
  5487. QString output = input;
  5488. output.resize(output.size() - suffix.size());
  5489. output += "mp4";
  5490. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  5491. remux->show();
  5492. remux->AutoRemux(input, output);
  5493. }
  5494. void OBSBasic::StartRecording()
  5495. {
  5496. if (outputHandler->RecordingActive())
  5497. return;
  5498. if (disableOutputsRef)
  5499. return;
  5500. if (!OutputPathValid()) {
  5501. OutputPathInvalidMessage();
  5502. ui->recordButton->setChecked(false);
  5503. return;
  5504. }
  5505. if (LowDiskSpace()) {
  5506. DiskSpaceMessage();
  5507. ui->recordButton->setChecked(false);
  5508. return;
  5509. }
  5510. if (api)
  5511. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  5512. SaveProject();
  5513. if (!outputHandler->StartRecording())
  5514. ui->recordButton->setChecked(false);
  5515. }
  5516. void OBSBasic::RecordStopping()
  5517. {
  5518. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  5519. if (sysTrayRecord)
  5520. sysTrayRecord->setText(ui->recordButton->text());
  5521. recordingStopping = true;
  5522. if (api)
  5523. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  5524. }
  5525. void OBSBasic::StopRecording()
  5526. {
  5527. SaveProject();
  5528. if (outputHandler->RecordingActive())
  5529. outputHandler->StopRecording(recordingStopping);
  5530. OnDeactivate();
  5531. }
  5532. void OBSBasic::RecordingStart()
  5533. {
  5534. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  5535. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  5536. ui->recordButton->setChecked(true);
  5537. if (sysTrayRecord)
  5538. sysTrayRecord->setText(ui->recordButton->text());
  5539. recordingStopping = false;
  5540. if (api)
  5541. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  5542. if (!diskFullTimer->isActive())
  5543. diskFullTimer->start(1000);
  5544. OnActivate();
  5545. UpdatePause();
  5546. blog(LOG_INFO, RECORDING_START);
  5547. }
  5548. void OBSBasic::RecordingStop(int code, QString last_error)
  5549. {
  5550. ui->statusbar->RecordingStopped();
  5551. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  5552. ui->recordButton->setChecked(false);
  5553. if (sysTrayRecord)
  5554. sysTrayRecord->setText(ui->recordButton->text());
  5555. blog(LOG_INFO, RECORDING_STOP);
  5556. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5557. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5558. QTStr("Output.RecordFail.Unsupported"));
  5559. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  5560. OBSMessageBox::warning(
  5561. this, QTStr("Output.RecordError.Title"),
  5562. QTStr("Output.RecordError.EncodeErrorMsg"));
  5563. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5564. OBSMessageBox::warning(this,
  5565. QTStr("Output.RecordNoSpace.Title"),
  5566. QTStr("Output.RecordNoSpace.Msg"));
  5567. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5568. const char *errorDescription;
  5569. DStr errorMessage;
  5570. bool use_last_error = true;
  5571. errorDescription = Str("Output.RecordError.Msg");
  5572. if (use_last_error && !last_error.isEmpty())
  5573. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5574. QT_TO_UTF8(last_error));
  5575. else
  5576. dstr_copy(errorMessage, errorDescription);
  5577. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5578. QT_UTF8(errorMessage));
  5579. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5580. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5581. QSystemTrayIcon::Warning);
  5582. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5583. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5584. QSystemTrayIcon::Warning);
  5585. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5586. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5587. QSystemTrayIcon::Warning);
  5588. } else if (code == OBS_OUTPUT_SUCCESS) {
  5589. if (outputHandler) {
  5590. std::string path = outputHandler->lastRecordingPath;
  5591. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5592. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  5593. }
  5594. }
  5595. if (api)
  5596. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  5597. if (diskFullTimer->isActive())
  5598. diskFullTimer->stop();
  5599. AutoRemux(outputHandler->lastRecordingPath.c_str());
  5600. OnDeactivate();
  5601. UpdatePause(false);
  5602. }
  5603. void OBSBasic::ShowReplayBufferPauseWarning()
  5604. {
  5605. auto msgBox = []() {
  5606. QMessageBox msgbox(App()->GetMainWindow());
  5607. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  5608. "PauseWarning.Title"));
  5609. msgbox.setText(QTStr("Output.ReplayBuffer."
  5610. "PauseWarning.Text"));
  5611. msgbox.setIcon(QMessageBox::Icon::Information);
  5612. msgbox.addButton(QMessageBox::Ok);
  5613. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5614. msgbox.setCheckBox(cb);
  5615. msgbox.exec();
  5616. if (cb->isChecked()) {
  5617. config_set_bool(App()->GlobalConfig(), "General",
  5618. "WarnedAboutReplayBufferPausing", true);
  5619. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5620. }
  5621. };
  5622. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5623. "WarnedAboutReplayBufferPausing");
  5624. if (!warned) {
  5625. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5626. Q_ARG(VoidFunc, msgBox));
  5627. }
  5628. }
  5629. void OBSBasic::StartReplayBuffer()
  5630. {
  5631. if (!outputHandler || !outputHandler->replayBuffer)
  5632. return;
  5633. if (outputHandler->ReplayBufferActive())
  5634. return;
  5635. if (disableOutputsRef)
  5636. return;
  5637. if (!UIValidation::NoSourcesConfirmation(this)) {
  5638. replayBufferButton->setChecked(false);
  5639. return;
  5640. }
  5641. if (LowDiskSpace()) {
  5642. DiskSpaceMessage();
  5643. replayBufferButton->setChecked(false);
  5644. return;
  5645. }
  5646. if (api)
  5647. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  5648. SaveProject();
  5649. if (!outputHandler->StartReplayBuffer()) {
  5650. replayBufferButton->setChecked(false);
  5651. } else if (os_atomic_load_bool(&recording_paused)) {
  5652. ShowReplayBufferPauseWarning();
  5653. }
  5654. }
  5655. void OBSBasic::ReplayBufferStopping()
  5656. {
  5657. if (!outputHandler || !outputHandler->replayBuffer)
  5658. return;
  5659. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  5660. if (sysTrayReplayBuffer)
  5661. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5662. replayBufferStopping = true;
  5663. if (api)
  5664. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  5665. }
  5666. void OBSBasic::StopReplayBuffer()
  5667. {
  5668. if (!outputHandler || !outputHandler->replayBuffer)
  5669. return;
  5670. SaveProject();
  5671. if (outputHandler->ReplayBufferActive())
  5672. outputHandler->StopReplayBuffer(replayBufferStopping);
  5673. OnDeactivate();
  5674. }
  5675. void OBSBasic::ReplayBufferStart()
  5676. {
  5677. if (!outputHandler || !outputHandler->replayBuffer)
  5678. return;
  5679. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  5680. replayBufferButton->setChecked(true);
  5681. if (sysTrayReplayBuffer)
  5682. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5683. replayBufferStopping = false;
  5684. if (api)
  5685. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  5686. OnActivate();
  5687. UpdateReplayBuffer();
  5688. blog(LOG_INFO, REPLAY_BUFFER_START);
  5689. }
  5690. void OBSBasic::ReplayBufferSave()
  5691. {
  5692. if (!outputHandler || !outputHandler->replayBuffer)
  5693. return;
  5694. if (!outputHandler->ReplayBufferActive())
  5695. return;
  5696. calldata_t cd = {0};
  5697. proc_handler_t *ph =
  5698. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5699. proc_handler_call(ph, "save", &cd);
  5700. calldata_free(&cd);
  5701. }
  5702. void OBSBasic::ReplayBufferSaved()
  5703. {
  5704. if (!outputHandler || !outputHandler->replayBuffer)
  5705. return;
  5706. if (!outputHandler->ReplayBufferActive())
  5707. return;
  5708. calldata_t cd = {0};
  5709. proc_handler_t *ph =
  5710. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5711. proc_handler_call(ph, "get_last_replay", &cd);
  5712. QString path = QT_UTF8(calldata_string(&cd, "path"));
  5713. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(path);
  5714. ShowStatusBarMessage(msg);
  5715. calldata_free(&cd);
  5716. if (api)
  5717. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  5718. AutoRemux(path);
  5719. }
  5720. void OBSBasic::ReplayBufferStop(int code)
  5721. {
  5722. if (!outputHandler || !outputHandler->replayBuffer)
  5723. return;
  5724. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  5725. replayBufferButton->setChecked(false);
  5726. if (sysTrayReplayBuffer)
  5727. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5728. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  5729. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5730. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5731. QTStr("Output.RecordFail.Unsupported"));
  5732. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5733. OBSMessageBox::warning(this,
  5734. QTStr("Output.RecordNoSpace.Title"),
  5735. QTStr("Output.RecordNoSpace.Msg"));
  5736. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5737. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5738. QTStr("Output.RecordError.Msg"));
  5739. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5740. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5741. QSystemTrayIcon::Warning);
  5742. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5743. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5744. QSystemTrayIcon::Warning);
  5745. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5746. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5747. QSystemTrayIcon::Warning);
  5748. }
  5749. if (api)
  5750. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  5751. OnDeactivate();
  5752. UpdateReplayBuffer(false);
  5753. }
  5754. void OBSBasic::StartVirtualCam()
  5755. {
  5756. if (!outputHandler || !outputHandler->virtualCam)
  5757. return;
  5758. if (outputHandler->VirtualCamActive())
  5759. return;
  5760. if (disableOutputsRef)
  5761. return;
  5762. SaveProject();
  5763. if (!outputHandler->StartVirtualCam()) {
  5764. vcamButton->setChecked(false);
  5765. }
  5766. }
  5767. void OBSBasic::StopVirtualCam()
  5768. {
  5769. if (!outputHandler || !outputHandler->virtualCam)
  5770. return;
  5771. SaveProject();
  5772. if (outputHandler->VirtualCamActive())
  5773. outputHandler->StopVirtualCam();
  5774. OnDeactivate();
  5775. }
  5776. void OBSBasic::OnVirtualCamStart()
  5777. {
  5778. if (!outputHandler || !outputHandler->virtualCam)
  5779. return;
  5780. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  5781. if (sysTrayVirtualCam)
  5782. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  5783. vcamButton->setChecked(true);
  5784. if (api)
  5785. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  5786. OnActivate();
  5787. blog(LOG_INFO, VIRTUAL_CAM_START);
  5788. }
  5789. void OBSBasic::OnVirtualCamStop(int)
  5790. {
  5791. if (!outputHandler || !outputHandler->virtualCam)
  5792. return;
  5793. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  5794. if (sysTrayVirtualCam)
  5795. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  5796. vcamButton->setChecked(false);
  5797. if (api)
  5798. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  5799. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  5800. OnDeactivate();
  5801. }
  5802. void OBSBasic::on_streamButton_clicked()
  5803. {
  5804. if (outputHandler->StreamingActive()) {
  5805. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5806. "WarnBeforeStoppingStream");
  5807. #if YOUTUBE_ENABLED
  5808. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  5809. autoStopBroadcast) {
  5810. QMessageBox::StandardButton button = OBSMessageBox::question(
  5811. this, QTStr("ConfirmStop.Title"),
  5812. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5813. QMessageBox::Yes | QMessageBox::No,
  5814. QMessageBox::No);
  5815. if (button == QMessageBox::No) {
  5816. ui->streamButton->setChecked(true);
  5817. return;
  5818. }
  5819. confirm = false;
  5820. }
  5821. #endif
  5822. if (confirm && isVisible()) {
  5823. QMessageBox::StandardButton button =
  5824. OBSMessageBox::question(
  5825. this, QTStr("ConfirmStop.Title"),
  5826. QTStr("ConfirmStop.Text"),
  5827. QMessageBox::Yes | QMessageBox::No,
  5828. QMessageBox::No);
  5829. if (button == QMessageBox::No) {
  5830. ui->streamButton->setChecked(true);
  5831. return;
  5832. }
  5833. }
  5834. StopStreaming();
  5835. } else {
  5836. if (!UIValidation::NoSourcesConfirmation(this)) {
  5837. ui->streamButton->setChecked(false);
  5838. return;
  5839. }
  5840. Auth *auth = GetAuth();
  5841. auto action =
  5842. (auth && auth->external())
  5843. ? StreamSettingsAction::ContinueStream
  5844. : UIValidation::StreamSettingsConfirmation(
  5845. this, service);
  5846. switch (action) {
  5847. case StreamSettingsAction::ContinueStream:
  5848. break;
  5849. case StreamSettingsAction::OpenSettings:
  5850. on_action_Settings_triggered();
  5851. ui->streamButton->setChecked(false);
  5852. return;
  5853. case StreamSettingsAction::Cancel:
  5854. ui->streamButton->setChecked(false);
  5855. return;
  5856. }
  5857. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5858. "WarnBeforeStartingStream");
  5859. bool bwtest = false;
  5860. if (this->auth) {
  5861. obs_data_t *settings =
  5862. obs_service_get_settings(service);
  5863. bwtest = obs_data_get_bool(settings, "bwtest");
  5864. obs_data_release(settings);
  5865. }
  5866. if (bwtest && isVisible()) {
  5867. QMessageBox::StandardButton button =
  5868. OBSMessageBox::question(
  5869. this, QTStr("ConfirmBWTest.Title"),
  5870. QTStr("ConfirmBWTest.Text"));
  5871. if (button == QMessageBox::No) {
  5872. ui->streamButton->setChecked(false);
  5873. return;
  5874. }
  5875. } else if (confirm && isVisible()) {
  5876. QMessageBox::StandardButton button =
  5877. OBSMessageBox::question(
  5878. this, QTStr("ConfirmStart.Title"),
  5879. QTStr("ConfirmStart.Text"),
  5880. QMessageBox::Yes | QMessageBox::No,
  5881. QMessageBox::No);
  5882. if (button == QMessageBox::No) {
  5883. ui->streamButton->setChecked(false);
  5884. return;
  5885. }
  5886. }
  5887. StartStreaming();
  5888. }
  5889. }
  5890. void OBSBasic::on_recordButton_clicked()
  5891. {
  5892. if (outputHandler->RecordingActive()) {
  5893. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5894. "WarnBeforeStoppingRecord");
  5895. if (confirm && isVisible()) {
  5896. QMessageBox::StandardButton button =
  5897. OBSMessageBox::question(
  5898. this, QTStr("ConfirmStopRecord.Title"),
  5899. QTStr("ConfirmStopRecord.Text"),
  5900. QMessageBox::Yes | QMessageBox::No,
  5901. QMessageBox::No);
  5902. if (button == QMessageBox::No) {
  5903. ui->recordButton->setChecked(true);
  5904. return;
  5905. }
  5906. }
  5907. StopRecording();
  5908. } else {
  5909. if (!UIValidation::NoSourcesConfirmation(this)) {
  5910. ui->recordButton->setChecked(false);
  5911. return;
  5912. }
  5913. StartRecording();
  5914. }
  5915. }
  5916. void OBSBasic::VCamButtonClicked()
  5917. {
  5918. if (outputHandler->VirtualCamActive()) {
  5919. StopVirtualCam();
  5920. } else {
  5921. if (!UIValidation::NoSourcesConfirmation(this)) {
  5922. vcamButton->setChecked(false);
  5923. return;
  5924. }
  5925. StartVirtualCam();
  5926. }
  5927. }
  5928. void OBSBasic::on_settingsButton_clicked()
  5929. {
  5930. on_action_Settings_triggered();
  5931. }
  5932. void OBSBasic::on_actionHelpPortal_triggered()
  5933. {
  5934. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  5935. QDesktopServices::openUrl(url);
  5936. }
  5937. void OBSBasic::on_actionWebsite_triggered()
  5938. {
  5939. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  5940. QDesktopServices::openUrl(url);
  5941. }
  5942. void OBSBasic::on_actionDiscord_triggered()
  5943. {
  5944. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  5945. QDesktopServices::openUrl(url);
  5946. }
  5947. void OBSBasic::on_actionShowSettingsFolder_triggered()
  5948. {
  5949. char path[512];
  5950. int ret = GetConfigPath(path, 512, "obs-studio");
  5951. if (ret <= 0)
  5952. return;
  5953. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5954. }
  5955. void OBSBasic::on_actionShowProfileFolder_triggered()
  5956. {
  5957. char path[512];
  5958. int ret = GetProfilePath(path, 512, "");
  5959. if (ret <= 0)
  5960. return;
  5961. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5962. }
  5963. int OBSBasic::GetTopSelectedSourceItem()
  5964. {
  5965. QModelIndexList selectedItems =
  5966. ui->sources->selectionModel()->selectedIndexes();
  5967. return selectedItems.count() ? selectedItems[0].row() : -1;
  5968. }
  5969. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  5970. {
  5971. return ui->sources->selectionModel()->selectedIndexes();
  5972. }
  5973. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  5974. {
  5975. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  5976. UNUSED_PARAMETER(pos);
  5977. }
  5978. void OBSBasic::ProgramViewContextMenuRequested(const QPoint &)
  5979. {
  5980. QMenu popup(this);
  5981. QPointer<QMenu> studioProgramProjector;
  5982. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5983. AddProjectorMenuMonitors(studioProgramProjector, this,
  5984. SLOT(OpenStudioProgramProjector()));
  5985. popup.addMenu(studioProgramProjector);
  5986. QAction *studioProgramWindow =
  5987. popup.addAction(QTStr("StudioProgramWindow"), this,
  5988. SLOT(OpenStudioProgramWindow()));
  5989. popup.addAction(studioProgramWindow);
  5990. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  5991. SLOT(ScreenshotProgram()));
  5992. popup.exec(QCursor::pos());
  5993. }
  5994. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  5995. {
  5996. QMenu popup(this);
  5997. delete previewProjectorMain;
  5998. QAction *action =
  5999. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6000. this, SLOT(TogglePreview()));
  6001. action->setCheckable(true);
  6002. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6003. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6004. AddProjectorMenuMonitors(previewProjectorMain, this,
  6005. SLOT(OpenPreviewProjector()));
  6006. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6007. SLOT(OpenPreviewWindow()));
  6008. popup.addMenu(previewProjectorMain);
  6009. popup.addAction(previewWindow);
  6010. popup.exec(QCursor::pos());
  6011. UNUSED_PARAMETER(pos);
  6012. }
  6013. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6014. {
  6015. #ifndef _WIN32
  6016. /* Make sure all dialogs are safely and successfully closed before
  6017. * switching the always on top mode due to the fact that windows all
  6018. * have to be recreated, so queue the actual toggle to happen after
  6019. * all events related to closing the dialogs have finished */
  6020. CloseDialogs();
  6021. #endif
  6022. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6023. Qt::QueuedConnection);
  6024. }
  6025. void OBSBasic::ToggleAlwaysOnTop()
  6026. {
  6027. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6028. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6029. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6030. show();
  6031. }
  6032. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6033. {
  6034. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6035. if (strcmp(val, "10") == 0) {
  6036. num = 10;
  6037. den = 1;
  6038. } else if (strcmp(val, "20") == 0) {
  6039. num = 20;
  6040. den = 1;
  6041. } else if (strcmp(val, "24 NTSC") == 0) {
  6042. num = 24000;
  6043. den = 1001;
  6044. } else if (strcmp(val, "25 PAL") == 0) {
  6045. num = 25;
  6046. den = 1;
  6047. } else if (strcmp(val, "29.97") == 0) {
  6048. num = 30000;
  6049. den = 1001;
  6050. } else if (strcmp(val, "48") == 0) {
  6051. num = 48;
  6052. den = 1;
  6053. } else if (strcmp(val, "50 PAL") == 0) {
  6054. num = 50;
  6055. den = 1;
  6056. } else if (strcmp(val, "59.94") == 0) {
  6057. num = 60000;
  6058. den = 1001;
  6059. } else if (strcmp(val, "60") == 0) {
  6060. num = 60;
  6061. den = 1;
  6062. } else {
  6063. num = 30;
  6064. den = 1;
  6065. }
  6066. }
  6067. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6068. {
  6069. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6070. den = 1;
  6071. }
  6072. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6073. {
  6074. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6075. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6076. }
  6077. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6078. {
  6079. num = 1000000000;
  6080. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6081. }
  6082. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6083. {
  6084. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6085. if (type == 1) //"Integer"
  6086. GetFPSInteger(num, den);
  6087. else if (type == 2) //"Fraction"
  6088. GetFPSFraction(num, den);
  6089. else if (false) //"Nanoseconds", currently not implemented
  6090. GetFPSNanoseconds(num, den);
  6091. else
  6092. GetFPSCommon(num, den);
  6093. }
  6094. config_t *OBSBasic::Config() const
  6095. {
  6096. return basicConfig;
  6097. }
  6098. void OBSBasic::on_actionEditTransform_triggered()
  6099. {
  6100. if (transformWindow)
  6101. transformWindow->close();
  6102. if (!GetCurrentSceneItem())
  6103. return;
  6104. transformWindow = new OBSBasicTransform(this);
  6105. transformWindow->show();
  6106. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  6107. }
  6108. static obs_transform_info copiedTransformInfo;
  6109. static obs_sceneitem_crop copiedCropInfo;
  6110. void OBSBasic::on_actionCopyTransform_triggered()
  6111. {
  6112. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  6113. if (!obs_sceneitem_selected(item))
  6114. return true;
  6115. obs_sceneitem_defer_update_begin(item);
  6116. obs_sceneitem_get_info(item, &copiedTransformInfo);
  6117. obs_sceneitem_get_crop(item, &copiedCropInfo);
  6118. obs_sceneitem_defer_update_end(item);
  6119. UNUSED_PARAMETER(scene);
  6120. UNUSED_PARAMETER(param);
  6121. return true;
  6122. };
  6123. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  6124. ui->actionPasteTransform->setEnabled(true);
  6125. }
  6126. void undo_redo(const std::string &data)
  6127. {
  6128. obs_data_t *dat = obs_data_create_from_json(data.c_str());
  6129. obs_source_t *source =
  6130. obs_get_source_by_name(obs_data_get_string(dat, "scene_name"));
  6131. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  6132. ->SetCurrentScene(source, true);
  6133. obs_source_release(source);
  6134. obs_data_release(dat);
  6135. obs_scene_load_transform_states(data.c_str());
  6136. }
  6137. void OBSBasic::on_actionPasteTransform_triggered()
  6138. {
  6139. obs_data_t *wrapper =
  6140. obs_scene_save_transform_states(GetCurrentScene(), false);
  6141. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  6142. if (!obs_sceneitem_selected(item))
  6143. return true;
  6144. obs_sceneitem_defer_update_begin(item);
  6145. obs_sceneitem_set_info(item, &copiedTransformInfo);
  6146. obs_sceneitem_set_crop(item, &copiedCropInfo);
  6147. obs_sceneitem_defer_update_end(item);
  6148. UNUSED_PARAMETER(scene);
  6149. UNUSED_PARAMETER(param);
  6150. return true;
  6151. };
  6152. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  6153. obs_data_t *rwrapper =
  6154. obs_scene_save_transform_states(GetCurrentScene(), false);
  6155. std::string undo_data(obs_data_get_json(wrapper));
  6156. std::string redo_data(obs_data_get_json(rwrapper));
  6157. undo_s.add_action(
  6158. QTStr("Undo.Transform.Paste")
  6159. .arg(obs_source_get_name(GetCurrentSceneSource())),
  6160. undo_redo, undo_redo, undo_data, redo_data);
  6161. obs_data_release(wrapper);
  6162. obs_data_release(rwrapper);
  6163. }
  6164. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  6165. {
  6166. if (obs_sceneitem_is_group(item))
  6167. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  6168. if (!obs_sceneitem_selected(item))
  6169. return true;
  6170. if (obs_sceneitem_locked(item))
  6171. return true;
  6172. obs_sceneitem_defer_update_begin(item);
  6173. obs_transform_info info;
  6174. vec2_set(&info.pos, 0.0f, 0.0f);
  6175. vec2_set(&info.scale, 1.0f, 1.0f);
  6176. info.rot = 0.0f;
  6177. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  6178. info.bounds_type = OBS_BOUNDS_NONE;
  6179. info.bounds_alignment = OBS_ALIGN_CENTER;
  6180. vec2_set(&info.bounds, 0.0f, 0.0f);
  6181. obs_sceneitem_set_info(item, &info);
  6182. obs_sceneitem_crop crop = {};
  6183. obs_sceneitem_set_crop(item, &crop);
  6184. obs_sceneitem_defer_update_end(item);
  6185. UNUSED_PARAMETER(scene);
  6186. UNUSED_PARAMETER(param);
  6187. return true;
  6188. }
  6189. void OBSBasic::on_actionResetTransform_triggered()
  6190. {
  6191. obs_scene_t *scene = GetCurrentScene();
  6192. obs_data_t *wrapper = obs_scene_save_transform_states(scene, false);
  6193. obs_scene_enum_items(scene, reset_tr, nullptr);
  6194. obs_data_t *rwrapper = obs_scene_save_transform_states(scene, false);
  6195. std::string undo_data(obs_data_get_json(wrapper));
  6196. std::string redo_data(obs_data_get_json(rwrapper));
  6197. undo_s.add_action(
  6198. QTStr("Undo.Transform.Reset")
  6199. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  6200. undo_redo, undo_redo, undo_data, redo_data);
  6201. obs_data_release(wrapper);
  6202. obs_data_release(rwrapper);
  6203. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  6204. }
  6205. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  6206. {
  6207. matrix4 boxTransform;
  6208. obs_sceneitem_get_box_transform(item, &boxTransform);
  6209. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  6210. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  6211. auto GetMinPos = [&](float x, float y) {
  6212. vec3 pos;
  6213. vec3_set(&pos, x, y, 0.0f);
  6214. vec3_transform(&pos, &pos, &boxTransform);
  6215. vec3_min(&tl, &tl, &pos);
  6216. vec3_max(&br, &br, &pos);
  6217. };
  6218. GetMinPos(0.0f, 0.0f);
  6219. GetMinPos(1.0f, 0.0f);
  6220. GetMinPos(0.0f, 1.0f);
  6221. GetMinPos(1.0f, 1.0f);
  6222. }
  6223. static vec3 GetItemTL(obs_sceneitem_t *item)
  6224. {
  6225. vec3 tl, br;
  6226. GetItemBox(item, tl, br);
  6227. return tl;
  6228. }
  6229. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  6230. {
  6231. vec3 newTL;
  6232. vec2 pos;
  6233. obs_sceneitem_get_pos(item, &pos);
  6234. newTL = GetItemTL(item);
  6235. pos.x += tl.x - newTL.x;
  6236. pos.y += tl.y - newTL.y;
  6237. obs_sceneitem_set_pos(item, &pos);
  6238. }
  6239. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  6240. void *param)
  6241. {
  6242. if (obs_sceneitem_is_group(item))
  6243. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  6244. param);
  6245. if (!obs_sceneitem_selected(item))
  6246. return true;
  6247. if (obs_sceneitem_locked(item))
  6248. return true;
  6249. float rot = *reinterpret_cast<float *>(param);
  6250. vec3 tl = GetItemTL(item);
  6251. rot += obs_sceneitem_get_rot(item);
  6252. if (rot >= 360.0f)
  6253. rot -= 360.0f;
  6254. else if (rot <= -360.0f)
  6255. rot += 360.0f;
  6256. obs_sceneitem_set_rot(item, rot);
  6257. obs_sceneitem_force_update_transform(item);
  6258. SetItemTL(item, tl);
  6259. UNUSED_PARAMETER(scene);
  6260. return true;
  6261. };
  6262. void OBSBasic::on_actionRotate90CW_triggered()
  6263. {
  6264. float f90CW = 90.0f;
  6265. obs_data_t *wrapper =
  6266. obs_scene_save_transform_states(GetCurrentScene(), false);
  6267. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  6268. obs_data_t *rwrapper =
  6269. obs_scene_save_transform_states(GetCurrentScene(), false);
  6270. std::string undo_data(obs_data_get_json(wrapper));
  6271. std::string redo_data(obs_data_get_json(rwrapper));
  6272. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6273. .arg(obs_source_get_name(obs_scene_get_source(
  6274. GetCurrentScene()))),
  6275. undo_redo, undo_redo, undo_data, redo_data);
  6276. obs_data_release(wrapper);
  6277. obs_data_release(rwrapper);
  6278. }
  6279. void OBSBasic::on_actionRotate90CCW_triggered()
  6280. {
  6281. float f90CCW = -90.0f;
  6282. obs_data_t *wrapper =
  6283. obs_scene_save_transform_states(GetCurrentScene(), false);
  6284. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  6285. obs_data_t *rwrapper =
  6286. obs_scene_save_transform_states(GetCurrentScene(), false);
  6287. std::string undo_data(obs_data_get_json(wrapper));
  6288. std::string redo_data(obs_data_get_json(rwrapper));
  6289. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6290. .arg(obs_source_get_name(obs_scene_get_source(
  6291. GetCurrentScene()))),
  6292. undo_redo, undo_redo, undo_data, redo_data);
  6293. obs_data_release(wrapper);
  6294. obs_data_release(rwrapper);
  6295. }
  6296. void OBSBasic::on_actionRotate180_triggered()
  6297. {
  6298. float f180 = 180.0f;
  6299. obs_data_t *wrapper =
  6300. obs_scene_save_transform_states(GetCurrentScene(), false);
  6301. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  6302. obs_data_t *rwrapper =
  6303. obs_scene_save_transform_states(GetCurrentScene(), false);
  6304. std::string undo_data(obs_data_get_json(wrapper));
  6305. std::string redo_data(obs_data_get_json(rwrapper));
  6306. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6307. .arg(obs_source_get_name(obs_scene_get_source(
  6308. GetCurrentScene()))),
  6309. undo_redo, undo_redo, undo_data, redo_data);
  6310. obs_data_release(wrapper);
  6311. obs_data_release(rwrapper);
  6312. }
  6313. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  6314. void *param)
  6315. {
  6316. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  6317. if (obs_sceneitem_is_group(item))
  6318. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  6319. param);
  6320. if (!obs_sceneitem_selected(item))
  6321. return true;
  6322. if (obs_sceneitem_locked(item))
  6323. return true;
  6324. vec3 tl = GetItemTL(item);
  6325. vec2 scale;
  6326. obs_sceneitem_get_scale(item, &scale);
  6327. vec2_mul(&scale, &scale, &mul);
  6328. obs_sceneitem_set_scale(item, &scale);
  6329. obs_sceneitem_force_update_transform(item);
  6330. SetItemTL(item, tl);
  6331. UNUSED_PARAMETER(scene);
  6332. return true;
  6333. }
  6334. void OBSBasic::on_actionFlipHorizontal_triggered()
  6335. {
  6336. vec2 scale;
  6337. vec2_set(&scale, -1.0f, 1.0f);
  6338. obs_data_t *wrapper =
  6339. obs_scene_save_transform_states(GetCurrentScene(), false);
  6340. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6341. &scale);
  6342. obs_data_t *rwrapper =
  6343. obs_scene_save_transform_states(GetCurrentScene(), false);
  6344. std::string undo_data(obs_data_get_json(wrapper));
  6345. std::string redo_data(obs_data_get_json(rwrapper));
  6346. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  6347. .arg(obs_source_get_name(obs_scene_get_source(
  6348. GetCurrentScene()))),
  6349. undo_redo, undo_redo, undo_data, redo_data);
  6350. obs_data_release(wrapper);
  6351. obs_data_release(rwrapper);
  6352. }
  6353. void OBSBasic::on_actionFlipVertical_triggered()
  6354. {
  6355. vec2 scale;
  6356. vec2_set(&scale, 1.0f, -1.0f);
  6357. obs_data_t *wrapper =
  6358. obs_scene_save_transform_states(GetCurrentScene(), false);
  6359. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6360. &scale);
  6361. obs_data_t *rwrapper =
  6362. obs_scene_save_transform_states(GetCurrentScene(), false);
  6363. std::string undo_data(obs_data_get_json(wrapper));
  6364. std::string redo_data(obs_data_get_json(rwrapper));
  6365. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  6366. .arg(obs_source_get_name(obs_scene_get_source(
  6367. GetCurrentScene()))),
  6368. undo_redo, undo_redo, undo_data, redo_data);
  6369. obs_data_release(wrapper);
  6370. obs_data_release(rwrapper);
  6371. }
  6372. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  6373. void *param)
  6374. {
  6375. obs_bounds_type boundsType =
  6376. *reinterpret_cast<obs_bounds_type *>(param);
  6377. if (obs_sceneitem_is_group(item))
  6378. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  6379. param);
  6380. if (!obs_sceneitem_selected(item))
  6381. return true;
  6382. if (obs_sceneitem_locked(item))
  6383. return true;
  6384. obs_video_info ovi;
  6385. obs_get_video_info(&ovi);
  6386. obs_transform_info itemInfo;
  6387. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  6388. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  6389. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  6390. itemInfo.rot = 0.0f;
  6391. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  6392. float(ovi.base_height));
  6393. itemInfo.bounds_type = boundsType;
  6394. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  6395. obs_sceneitem_set_info(item, &itemInfo);
  6396. UNUSED_PARAMETER(scene);
  6397. return true;
  6398. }
  6399. void OBSBasic::on_actionFitToScreen_triggered()
  6400. {
  6401. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  6402. obs_data_t *wrapper =
  6403. obs_scene_save_transform_states(GetCurrentScene(), false);
  6404. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6405. &boundsType);
  6406. obs_data_t *rwrapper =
  6407. obs_scene_save_transform_states(GetCurrentScene(), false);
  6408. std::string undo_data(obs_data_get_json(wrapper));
  6409. std::string redo_data(obs_data_get_json(rwrapper));
  6410. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  6411. .arg(obs_source_get_name(obs_scene_get_source(
  6412. GetCurrentScene()))),
  6413. undo_redo, undo_redo, undo_data, redo_data);
  6414. obs_data_release(wrapper);
  6415. obs_data_release(rwrapper);
  6416. }
  6417. void OBSBasic::on_actionStretchToScreen_triggered()
  6418. {
  6419. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  6420. obs_data_t *wrapper =
  6421. obs_scene_save_transform_states(GetCurrentScene(), false);
  6422. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6423. &boundsType);
  6424. obs_data_t *rwrapper =
  6425. obs_scene_save_transform_states(GetCurrentScene(), false);
  6426. std::string undo_data(obs_data_get_json(wrapper));
  6427. std::string redo_data(obs_data_get_json(rwrapper));
  6428. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  6429. .arg(obs_source_get_name(obs_scene_get_source(
  6430. GetCurrentScene()))),
  6431. undo_redo, undo_redo, undo_data, redo_data);
  6432. obs_data_release(wrapper);
  6433. obs_data_release(rwrapper);
  6434. }
  6435. enum class CenterType {
  6436. Scene,
  6437. Vertical,
  6438. Horizontal,
  6439. };
  6440. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6441. {
  6442. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  6443. vec3 tl, br, itemCenter, screenCenter, offset;
  6444. obs_video_info ovi;
  6445. obs_transform_info oti;
  6446. if (obs_sceneitem_is_group(item))
  6447. obs_sceneitem_group_enum_items(item, center_to_scene,
  6448. &centerType);
  6449. if (!obs_sceneitem_selected(item))
  6450. return true;
  6451. if (obs_sceneitem_locked(item))
  6452. return true;
  6453. obs_get_video_info(&ovi);
  6454. obs_sceneitem_get_info(item, &oti);
  6455. if (centerType == CenterType::Scene)
  6456. vec3_set(&screenCenter, float(ovi.base_width),
  6457. float(ovi.base_height), 0.0f);
  6458. else if (centerType == CenterType::Vertical)
  6459. vec3_set(&screenCenter, float(oti.bounds.x),
  6460. float(ovi.base_height), 0.0f);
  6461. else if (centerType == CenterType::Horizontal)
  6462. vec3_set(&screenCenter, float(ovi.base_width),
  6463. float(oti.bounds.y), 0.0f);
  6464. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  6465. GetItemBox(item, tl, br);
  6466. vec3_sub(&itemCenter, &br, &tl);
  6467. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  6468. vec3_add(&itemCenter, &itemCenter, &tl);
  6469. vec3_sub(&offset, &screenCenter, &itemCenter);
  6470. vec3_add(&tl, &tl, &offset);
  6471. if (centerType == CenterType::Vertical)
  6472. tl.x = oti.pos.x;
  6473. else if (centerType == CenterType::Horizontal)
  6474. tl.y = oti.pos.y;
  6475. SetItemTL(item, tl);
  6476. return true;
  6477. };
  6478. void OBSBasic::on_actionCenterToScreen_triggered()
  6479. {
  6480. CenterType centerType = CenterType::Scene;
  6481. obs_data_t *wrapper =
  6482. obs_scene_save_transform_states(GetCurrentScene(), false);
  6483. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6484. obs_data_t *rwrapper =
  6485. obs_scene_save_transform_states(GetCurrentScene(), false);
  6486. std::string undo_data(obs_data_get_json(wrapper));
  6487. std::string redo_data(obs_data_get_json(rwrapper));
  6488. undo_s.add_action(QTStr("Undo.Transform.Center")
  6489. .arg(obs_source_get_name(obs_scene_get_source(
  6490. GetCurrentScene()))),
  6491. undo_redo, undo_redo, undo_data, redo_data);
  6492. obs_data_release(wrapper);
  6493. obs_data_release(rwrapper);
  6494. }
  6495. void OBSBasic::on_actionVerticalCenter_triggered()
  6496. {
  6497. CenterType centerType = CenterType::Vertical;
  6498. obs_data_t *wrapper =
  6499. obs_scene_save_transform_states(GetCurrentScene(), false);
  6500. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6501. obs_data_t *rwrapper =
  6502. obs_scene_save_transform_states(GetCurrentScene(), false);
  6503. std::string undo_data(obs_data_get_json(wrapper));
  6504. std::string redo_data(obs_data_get_json(rwrapper));
  6505. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  6506. .arg(obs_source_get_name(obs_scene_get_source(
  6507. GetCurrentScene()))),
  6508. undo_redo, undo_redo, undo_data, redo_data);
  6509. obs_data_release(wrapper);
  6510. obs_data_release(rwrapper);
  6511. }
  6512. void OBSBasic::on_actionHorizontalCenter_triggered()
  6513. {
  6514. CenterType centerType = CenterType::Horizontal;
  6515. obs_data_t *wrapper =
  6516. obs_scene_save_transform_states(GetCurrentScene(), false);
  6517. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6518. obs_data_t *rwrapper =
  6519. obs_scene_save_transform_states(GetCurrentScene(), false);
  6520. std::string undo_data(obs_data_get_json(wrapper));
  6521. std::string redo_data(obs_data_get_json(rwrapper));
  6522. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  6523. .arg(obs_source_get_name(obs_scene_get_source(
  6524. GetCurrentScene()))),
  6525. undo_redo, undo_redo, undo_data, redo_data);
  6526. obs_data_release(wrapper);
  6527. obs_data_release(rwrapper);
  6528. }
  6529. void OBSBasic::EnablePreviewDisplay(bool enable)
  6530. {
  6531. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  6532. ui->preview->setVisible(enable);
  6533. ui->previewDisabledWidget->setVisible(!enable);
  6534. }
  6535. void OBSBasic::TogglePreview()
  6536. {
  6537. previewEnabled = !previewEnabled;
  6538. EnablePreviewDisplay(previewEnabled);
  6539. }
  6540. void OBSBasic::EnablePreview()
  6541. {
  6542. if (previewProgramMode)
  6543. return;
  6544. previewEnabled = true;
  6545. EnablePreviewDisplay(true);
  6546. }
  6547. void OBSBasic::DisablePreview()
  6548. {
  6549. if (previewProgramMode)
  6550. return;
  6551. previewEnabled = false;
  6552. EnablePreviewDisplay(false);
  6553. }
  6554. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6555. {
  6556. if (obs_sceneitem_locked(item))
  6557. return true;
  6558. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  6559. struct vec2 pos;
  6560. if (!obs_sceneitem_selected(item)) {
  6561. if (obs_sceneitem_is_group(item)) {
  6562. struct vec3 offset3;
  6563. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  6564. struct matrix4 matrix;
  6565. obs_sceneitem_get_draw_transform(item, &matrix);
  6566. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  6567. matrix4_inv(&matrix, &matrix);
  6568. vec3_transform(&offset3, &offset3, &matrix);
  6569. struct vec2 new_offset;
  6570. vec2_set(&new_offset, offset3.x, offset3.y);
  6571. obs_sceneitem_group_enum_items(item, nudge_callback,
  6572. &new_offset);
  6573. }
  6574. return true;
  6575. }
  6576. obs_sceneitem_get_pos(item, &pos);
  6577. vec2_add(&pos, &pos, &offset);
  6578. obs_sceneitem_set_pos(item, &pos);
  6579. return true;
  6580. }
  6581. void OBSBasic::Nudge(int dist, MoveDir dir)
  6582. {
  6583. if (ui->preview->Locked())
  6584. return;
  6585. struct vec2 offset;
  6586. vec2_set(&offset, 0.0f, 0.0f);
  6587. switch (dir) {
  6588. case MoveDir::Up:
  6589. offset.y = (float)-dist;
  6590. break;
  6591. case MoveDir::Down:
  6592. offset.y = (float)dist;
  6593. break;
  6594. case MoveDir::Left:
  6595. offset.x = (float)-dist;
  6596. break;
  6597. case MoveDir::Right:
  6598. offset.x = (float)dist;
  6599. break;
  6600. }
  6601. if (!recent_nudge) {
  6602. recent_nudge = true;
  6603. obs_data_t *wrapper = obs_scene_save_transform_states(
  6604. GetCurrentScene(), true);
  6605. std::string undo_data(obs_data_get_json(wrapper));
  6606. nudge_timer = new QTimer;
  6607. QObject::connect(
  6608. nudge_timer, &QTimer::timeout,
  6609. [this, &recent_nudge = recent_nudge, undo_data]() {
  6610. obs_data_t *rwrapper =
  6611. obs_scene_save_transform_states(
  6612. GetCurrentScene(), true);
  6613. std::string redo_data(
  6614. obs_data_get_json(rwrapper));
  6615. undo_s.add_action(
  6616. QTStr("Undo.Transform")
  6617. .arg(obs_source_get_name(
  6618. GetCurrentSceneSource())),
  6619. undo_redo, undo_redo, undo_data,
  6620. redo_data);
  6621. recent_nudge = false;
  6622. obs_data_release(rwrapper);
  6623. });
  6624. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  6625. &QTimer::deleteLater);
  6626. nudge_timer->setSingleShot(true);
  6627. obs_data_release(wrapper);
  6628. }
  6629. if (nudge_timer) {
  6630. nudge_timer->stop();
  6631. nudge_timer->start(1000);
  6632. } else {
  6633. blog(LOG_ERROR, "No nudge timer!");
  6634. }
  6635. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  6636. }
  6637. void OBSBasic::NudgeUp()
  6638. {
  6639. Nudge(1, MoveDir::Up);
  6640. }
  6641. void OBSBasic::NudgeDown()
  6642. {
  6643. Nudge(1, MoveDir::Down);
  6644. }
  6645. void OBSBasic::NudgeLeft()
  6646. {
  6647. Nudge(1, MoveDir::Left);
  6648. }
  6649. void OBSBasic::NudgeRight()
  6650. {
  6651. Nudge(1, MoveDir::Right);
  6652. }
  6653. void OBSBasic::DeleteProjector(OBSProjector *projector)
  6654. {
  6655. for (size_t i = 0; i < projectors.size(); i++) {
  6656. if (projectors[i] == projector) {
  6657. projectors[i]->deleteLater();
  6658. projectors.erase(projectors.begin() + i);
  6659. break;
  6660. }
  6661. }
  6662. }
  6663. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  6664. ProjectorType type)
  6665. {
  6666. /* seriously? 10 monitors? */
  6667. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  6668. return nullptr;
  6669. OBSProjector *projector =
  6670. new OBSProjector(nullptr, source, monitor, type);
  6671. projectors.emplace_back(projector);
  6672. return projector;
  6673. }
  6674. void OBSBasic::OpenStudioProgramProjector()
  6675. {
  6676. int monitor = sender()->property("monitor").toInt();
  6677. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  6678. }
  6679. void OBSBasic::OpenPreviewProjector()
  6680. {
  6681. int monitor = sender()->property("monitor").toInt();
  6682. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  6683. }
  6684. void OBSBasic::OpenSourceProjector()
  6685. {
  6686. int monitor = sender()->property("monitor").toInt();
  6687. OBSSceneItem item = GetCurrentSceneItem();
  6688. if (!item)
  6689. return;
  6690. OpenProjector(obs_sceneitem_get_source(item), monitor,
  6691. ProjectorType::Source);
  6692. }
  6693. void OBSBasic::OpenMultiviewProjector()
  6694. {
  6695. int monitor = sender()->property("monitor").toInt();
  6696. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  6697. }
  6698. void OBSBasic::OpenSceneProjector()
  6699. {
  6700. int monitor = sender()->property("monitor").toInt();
  6701. OBSScene scene = GetCurrentScene();
  6702. if (!scene)
  6703. return;
  6704. OpenProjector(obs_scene_get_source(scene), monitor,
  6705. ProjectorType::Scene);
  6706. }
  6707. void OBSBasic::OpenStudioProgramWindow()
  6708. {
  6709. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  6710. }
  6711. void OBSBasic::OpenPreviewWindow()
  6712. {
  6713. OpenProjector(nullptr, -1, ProjectorType::Preview);
  6714. }
  6715. void OBSBasic::OpenSourceWindow()
  6716. {
  6717. OBSSceneItem item = GetCurrentSceneItem();
  6718. if (!item)
  6719. return;
  6720. OBSSource source = obs_sceneitem_get_source(item);
  6721. OpenProjector(obs_sceneitem_get_source(item), -1,
  6722. ProjectorType::Source);
  6723. }
  6724. void OBSBasic::OpenMultiviewWindow()
  6725. {
  6726. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  6727. }
  6728. void OBSBasic::OpenSceneWindow()
  6729. {
  6730. OBSScene scene = GetCurrentScene();
  6731. if (!scene)
  6732. return;
  6733. OBSSource source = obs_scene_get_source(scene);
  6734. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  6735. }
  6736. void OBSBasic::OpenSavedProjectors()
  6737. {
  6738. for (SavedProjectorInfo *info : savedProjectorsArray) {
  6739. OpenSavedProjector(info);
  6740. }
  6741. }
  6742. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  6743. {
  6744. if (info) {
  6745. OBSProjector *projector = nullptr;
  6746. switch (info->type) {
  6747. case ProjectorType::Source:
  6748. case ProjectorType::Scene: {
  6749. OBSSource source =
  6750. obs_get_source_by_name(info->name.c_str());
  6751. if (!source)
  6752. return;
  6753. projector = OpenProjector(source, info->monitor,
  6754. info->type);
  6755. obs_source_release(source);
  6756. break;
  6757. }
  6758. default: {
  6759. projector = OpenProjector(nullptr, info->monitor,
  6760. info->type);
  6761. break;
  6762. }
  6763. }
  6764. if (projector && !info->geometry.empty() && info->monitor < 0) {
  6765. QByteArray byteArray = QByteArray::fromBase64(
  6766. QByteArray(info->geometry.c_str()));
  6767. projector->restoreGeometry(byteArray);
  6768. if (!WindowPositionValid(projector->normalGeometry())) {
  6769. QRect rect = QGuiApplication::primaryScreen()
  6770. ->geometry();
  6771. projector->setGeometry(QStyle::alignedRect(
  6772. Qt::LeftToRight, Qt::AlignCenter,
  6773. size(), rect));
  6774. }
  6775. if (info->alwaysOnTopOverridden)
  6776. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  6777. true);
  6778. }
  6779. }
  6780. }
  6781. void OBSBasic::on_actionFullscreenInterface_triggered()
  6782. {
  6783. if (!isFullScreen())
  6784. showFullScreen();
  6785. else
  6786. showNormal();
  6787. }
  6788. void OBSBasic::UpdateTitleBar()
  6789. {
  6790. stringstream name;
  6791. const char *profile =
  6792. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  6793. const char *sceneCollection = config_get_string(
  6794. App()->GlobalConfig(), "Basic", "SceneCollection");
  6795. name << "OBS ";
  6796. if (previewProgramMode)
  6797. name << "Studio ";
  6798. name << App()->GetVersionString();
  6799. if (App()->IsPortableMode())
  6800. name << " - Portable Mode";
  6801. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  6802. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  6803. setWindowTitle(QT_UTF8(name.str().c_str()));
  6804. }
  6805. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  6806. {
  6807. char profiles_path[512];
  6808. const char *profile =
  6809. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  6810. int ret;
  6811. if (!profile)
  6812. return -1;
  6813. if (!path)
  6814. return -1;
  6815. if (!file)
  6816. file = "";
  6817. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  6818. if (ret <= 0)
  6819. return ret;
  6820. if (!*file)
  6821. return snprintf(path, size, "%s/%s", profiles_path, profile);
  6822. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  6823. }
  6824. void OBSBasic::on_resetUI_triggered()
  6825. {
  6826. /* prune deleted extra docks */
  6827. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6828. if (!extraDocks[i]) {
  6829. extraDocks.removeAt(i);
  6830. }
  6831. }
  6832. if (extraDocks.size()) {
  6833. QMessageBox::StandardButton button = QMessageBox::question(
  6834. this, QTStr("ResetUIWarning.Title"),
  6835. QTStr("ResetUIWarning.Text"));
  6836. if (button == QMessageBox::No)
  6837. return;
  6838. }
  6839. /* undock/hide/center extra docks */
  6840. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6841. if (extraDocks[i]) {
  6842. extraDocks[i]->setVisible(true);
  6843. extraDocks[i]->setFloating(true);
  6844. extraDocks[i]->move(frameGeometry().topLeft() +
  6845. rect().center() -
  6846. extraDocks[i]->rect().center());
  6847. extraDocks[i]->setVisible(false);
  6848. }
  6849. }
  6850. restoreState(startingDockLayout);
  6851. int cx = width();
  6852. int cy = height();
  6853. int cx22_5 = cx * 225 / 1000;
  6854. int cx5 = cx * 5 / 100;
  6855. cy = cy * 225 / 1000;
  6856. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  6857. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  6858. ui->mixerDock, ui->transitionsDock,
  6859. ui->controlsDock};
  6860. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  6861. ui->scenesDock->setVisible(true);
  6862. ui->sourcesDock->setVisible(true);
  6863. ui->mixerDock->setVisible(true);
  6864. ui->transitionsDock->setVisible(true);
  6865. ui->controlsDock->setVisible(true);
  6866. statsDock->setVisible(false);
  6867. statsDock->setFloating(true);
  6868. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  6869. resizeDocks(docks, sizes, Qt::Horizontal);
  6870. activateWindow();
  6871. }
  6872. void OBSBasic::on_lockUI_toggled(bool lock)
  6873. {
  6874. QDockWidget::DockWidgetFeatures features =
  6875. lock ? QDockWidget::NoDockWidgetFeatures
  6876. : (QDockWidget::DockWidgetClosable |
  6877. QDockWidget::DockWidgetMovable |
  6878. QDockWidget::DockWidgetFloatable);
  6879. QDockWidget::DockWidgetFeatures mainFeatures = features;
  6880. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  6881. ui->scenesDock->setFeatures(mainFeatures);
  6882. ui->sourcesDock->setFeatures(mainFeatures);
  6883. ui->mixerDock->setFeatures(mainFeatures);
  6884. ui->transitionsDock->setFeatures(mainFeatures);
  6885. ui->controlsDock->setFeatures(mainFeatures);
  6886. statsDock->setFeatures(features);
  6887. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6888. if (!extraDocks[i]) {
  6889. extraDocks.removeAt(i);
  6890. } else {
  6891. extraDocks[i]->setFeatures(features);
  6892. }
  6893. }
  6894. }
  6895. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  6896. {
  6897. ui->sourcesToolbar->setVisible(visible);
  6898. ui->scenesToolbar->setVisible(visible);
  6899. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  6900. "ShowListboxToolbars", visible);
  6901. }
  6902. void OBSBasic::ShowContextBar()
  6903. {
  6904. on_toggleContextBar_toggled(true);
  6905. }
  6906. void OBSBasic::HideContextBar()
  6907. {
  6908. on_toggleContextBar_toggled(false);
  6909. }
  6910. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  6911. {
  6912. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  6913. "ShowContextToolbars", visible);
  6914. this->ui->contextContainer->setVisible(visible);
  6915. UpdateContextBar(true);
  6916. }
  6917. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  6918. {
  6919. ui->statusbar->setVisible(visible);
  6920. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  6921. visible);
  6922. }
  6923. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  6924. {
  6925. ui->sources->SetIconsVisible(visible);
  6926. if (advAudioWindow != nullptr)
  6927. advAudioWindow->SetIconsVisible(visible);
  6928. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  6929. visible);
  6930. }
  6931. void OBSBasic::on_actionLockPreview_triggered()
  6932. {
  6933. ui->preview->ToggleLocked();
  6934. ui->actionLockPreview->setChecked(ui->preview->Locked());
  6935. }
  6936. void OBSBasic::on_scalingMenu_aboutToShow()
  6937. {
  6938. obs_video_info ovi;
  6939. obs_get_video_info(&ovi);
  6940. QAction *action = ui->actionScaleCanvas;
  6941. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  6942. text = text.arg(QString::number(ovi.base_width),
  6943. QString::number(ovi.base_height));
  6944. action->setText(text);
  6945. action = ui->actionScaleOutput;
  6946. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  6947. text = text.arg(QString::number(ovi.output_width),
  6948. QString::number(ovi.output_height));
  6949. action->setText(text);
  6950. action->setVisible(!(ovi.output_width == ovi.base_width &&
  6951. ovi.output_height == ovi.base_height));
  6952. UpdatePreviewScalingMenu();
  6953. }
  6954. void OBSBasic::on_actionScaleWindow_triggered()
  6955. {
  6956. ui->preview->SetFixedScaling(false);
  6957. ui->preview->ResetScrollingOffset();
  6958. emit ui->preview->DisplayResized();
  6959. }
  6960. void OBSBasic::on_actionScaleCanvas_triggered()
  6961. {
  6962. ui->preview->SetFixedScaling(true);
  6963. ui->preview->SetScalingLevel(0);
  6964. emit ui->preview->DisplayResized();
  6965. }
  6966. void OBSBasic::on_actionScaleOutput_triggered()
  6967. {
  6968. obs_video_info ovi;
  6969. obs_get_video_info(&ovi);
  6970. ui->preview->SetFixedScaling(true);
  6971. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  6972. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  6973. int32_t approxScalingLevel =
  6974. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  6975. ui->preview->SetScalingLevel(approxScalingLevel);
  6976. ui->preview->SetScalingAmount(scalingAmount);
  6977. emit ui->preview->DisplayResized();
  6978. }
  6979. void OBSBasic::SetShowing(bool showing)
  6980. {
  6981. if (!showing && isVisible()) {
  6982. config_set_string(App()->GlobalConfig(), "BasicWindow",
  6983. "geometry",
  6984. saveGeometry().toBase64().constData());
  6985. /* hide all visible child dialogs */
  6986. visDlgPositions.clear();
  6987. if (!visDialogs.isEmpty()) {
  6988. for (QDialog *dlg : visDialogs) {
  6989. visDlgPositions.append(dlg->pos());
  6990. dlg->hide();
  6991. }
  6992. }
  6993. if (showHide)
  6994. showHide->setText(QTStr("Basic.SystemTray.Show"));
  6995. QTimer::singleShot(250, this, SLOT(hide()));
  6996. setVisible(false);
  6997. #ifdef __APPLE__
  6998. EnableOSXDockIcon(false);
  6999. #endif
  7000. } else if (showing && !isVisible()) {
  7001. if (showHide)
  7002. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7003. QTimer::singleShot(250, this, SLOT(show()));
  7004. setVisible(true);
  7005. #ifdef __APPLE__
  7006. EnableOSXDockIcon(true);
  7007. #endif
  7008. /* raise and activate window to ensure it is on top */
  7009. raise();
  7010. activateWindow();
  7011. /* show all child dialogs that was visible earlier */
  7012. if (!visDialogs.isEmpty()) {
  7013. for (int i = 0; i < visDialogs.size(); ++i) {
  7014. QDialog *dlg = visDialogs[i];
  7015. dlg->move(visDlgPositions[i]);
  7016. dlg->show();
  7017. }
  7018. }
  7019. /* Unminimize window if it was hidden to tray instead of task
  7020. * bar. */
  7021. if (sysTrayMinimizeToTray()) {
  7022. Qt::WindowStates state;
  7023. state = windowState() & ~Qt::WindowMinimized;
  7024. state |= Qt::WindowActive;
  7025. setWindowState(state);
  7026. }
  7027. }
  7028. }
  7029. void OBSBasic::ToggleShowHide()
  7030. {
  7031. bool showing = isVisible();
  7032. if (showing) {
  7033. /* check for modal dialogs */
  7034. EnumDialogs();
  7035. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7036. return;
  7037. }
  7038. SetShowing(!showing);
  7039. }
  7040. void OBSBasic::SystemTrayInit()
  7041. {
  7042. #ifdef __APPLE__
  7043. QIcon trayIconFile = QIcon(":/res/images/obs_macos.png");
  7044. trayIconFile.setIsMask(true);
  7045. #else
  7046. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  7047. #endif
  7048. trayIcon.reset(new QSystemTrayIcon(
  7049. QIcon::fromTheme("obs-tray", trayIconFile), this));
  7050. trayIcon->setToolTip("OBS Studio");
  7051. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  7052. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  7053. trayIcon.data());
  7054. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  7055. trayIcon.data());
  7056. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  7057. trayIcon.data());
  7058. sysTrayVirtualCam = new QAction(QTStr("Basic.Main.StartVirtualCam"),
  7059. trayIcon.data());
  7060. exit = new QAction(QTStr("Exit"), trayIcon.data());
  7061. trayMenu = new QMenu;
  7062. previewProjector = new QMenu(QTStr("PreviewProjector"));
  7063. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  7064. AddProjectorMenuMonitors(previewProjector, this,
  7065. SLOT(OpenPreviewProjector()));
  7066. AddProjectorMenuMonitors(studioProgramProjector, this,
  7067. SLOT(OpenStudioProgramProjector()));
  7068. trayMenu->addAction(showHide);
  7069. trayMenu->addMenu(previewProjector);
  7070. trayMenu->addMenu(studioProgramProjector);
  7071. trayMenu->addAction(sysTrayStream);
  7072. trayMenu->addAction(sysTrayRecord);
  7073. trayMenu->addAction(sysTrayReplayBuffer);
  7074. trayMenu->addAction(sysTrayVirtualCam);
  7075. trayMenu->addAction(exit);
  7076. trayIcon->setContextMenu(trayMenu);
  7077. trayIcon->show();
  7078. if (outputHandler && !outputHandler->replayBuffer)
  7079. sysTrayReplayBuffer->setEnabled(false);
  7080. sysTrayVirtualCam->setEnabled(vcamEnabled);
  7081. connect(trayIcon.data(),
  7082. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  7083. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  7084. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  7085. connect(sysTrayStream, SIGNAL(triggered()), this,
  7086. SLOT(on_streamButton_clicked()));
  7087. connect(sysTrayRecord, SIGNAL(triggered()), this,
  7088. SLOT(on_recordButton_clicked()));
  7089. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  7090. &OBSBasic::ReplayBufferClicked);
  7091. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  7092. &OBSBasic::VCamButtonClicked);
  7093. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  7094. }
  7095. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  7096. {
  7097. // Refresh projector list
  7098. previewProjector->clear();
  7099. studioProgramProjector->clear();
  7100. AddProjectorMenuMonitors(previewProjector, this,
  7101. SLOT(OpenPreviewProjector()));
  7102. AddProjectorMenuMonitors(studioProgramProjector, this,
  7103. SLOT(OpenStudioProgramProjector()));
  7104. #ifdef __APPLE__
  7105. UNUSED_PARAMETER(reason);
  7106. #else
  7107. if (reason == QSystemTrayIcon::Trigger) {
  7108. EnablePreviewDisplay(previewEnabled && !isVisible());
  7109. ToggleShowHide();
  7110. }
  7111. #endif
  7112. }
  7113. void OBSBasic::SysTrayNotify(const QString &text,
  7114. QSystemTrayIcon::MessageIcon n)
  7115. {
  7116. if (trayIcon && trayIcon->isVisible() &&
  7117. QSystemTrayIcon::supportsMessages()) {
  7118. QSystemTrayIcon::MessageIcon icon =
  7119. QSystemTrayIcon::MessageIcon(n);
  7120. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  7121. }
  7122. }
  7123. void OBSBasic::SystemTray(bool firstStarted)
  7124. {
  7125. if (!QSystemTrayIcon::isSystemTrayAvailable())
  7126. return;
  7127. if (!trayIcon && !firstStarted)
  7128. return;
  7129. bool sysTrayWhenStarted = config_get_bool(
  7130. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  7131. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7132. "SysTrayEnabled");
  7133. if (firstStarted)
  7134. SystemTrayInit();
  7135. if (!sysTrayEnabled) {
  7136. trayIcon->hide();
  7137. } else {
  7138. trayIcon->show();
  7139. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  7140. QTimer::singleShot(50, this, SLOT(hide()));
  7141. EnablePreviewDisplay(false);
  7142. setVisible(false);
  7143. #ifdef __APPLE__
  7144. EnableOSXDockIcon(false);
  7145. #endif
  7146. opt_minimize_tray = false;
  7147. }
  7148. }
  7149. if (isVisible())
  7150. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7151. else
  7152. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7153. }
  7154. bool OBSBasic::sysTrayMinimizeToTray()
  7155. {
  7156. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  7157. "SysTrayMinimizeToTray");
  7158. }
  7159. void OBSBasic::on_actionMainUndo_triggered()
  7160. {
  7161. undo_s.undo();
  7162. }
  7163. void OBSBasic::on_actionMainRedo_triggered()
  7164. {
  7165. undo_s.redo();
  7166. }
  7167. void OBSBasic::on_actionCopySource_triggered()
  7168. {
  7169. copyStrings.clear();
  7170. bool allowPastingDuplicate = true;
  7171. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  7172. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  7173. if (!item)
  7174. continue;
  7175. on_actionCopyTransform_triggered();
  7176. OBSSource source = obs_sceneitem_get_source(item);
  7177. copyStrings.push_front(obs_source_get_name(source));
  7178. copyVisible = obs_sceneitem_visible(item);
  7179. uint32_t output_flags = obs_source_get_output_flags(source);
  7180. if (output_flags & OBS_SOURCE_DO_NOT_DUPLICATE)
  7181. allowPastingDuplicate = false;
  7182. }
  7183. ui->actionPasteRef->setEnabled(true);
  7184. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  7185. }
  7186. void OBSBasic::on_actionPasteRef_triggered()
  7187. {
  7188. OBSSource scene_source = GetCurrentSceneSource();
  7189. OBSData undo_data = BackupScene(scene_source);
  7190. undo_s.push_disabled();
  7191. for (auto &copyString : copyStrings) {
  7192. /* do not allow duplicate refs of the same group in the same scene */
  7193. OBSScene scene = GetCurrentScene();
  7194. if (!!obs_scene_get_group(scene, copyString))
  7195. continue;
  7196. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  7197. false);
  7198. on_actionPasteTransform_triggered();
  7199. }
  7200. undo_s.pop_disabled();
  7201. QString action_name = QTStr("Undo.PasteSourceRef");
  7202. const char *scene_name = obs_source_get_name(scene_source);
  7203. OBSData redo_data = BackupScene(scene_source);
  7204. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7205. redo_data);
  7206. }
  7207. void OBSBasic::on_actionPasteDup_triggered()
  7208. {
  7209. OBSSource scene_source = GetCurrentSceneSource();
  7210. OBSData undo_data = BackupScene(scene_source);
  7211. undo_s.push_disabled();
  7212. for (auto &copyString : copyStrings) {
  7213. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  7214. true);
  7215. on_actionPasteTransform_triggered();
  7216. }
  7217. undo_s.pop_disabled();
  7218. QString action_name = QTStr("Undo.PasteSource");
  7219. const char *scene_name = obs_source_get_name(scene_source);
  7220. OBSData redo_data = BackupScene(scene_source);
  7221. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7222. redo_data);
  7223. }
  7224. void OBSBasic::AudioMixerCopyFilters()
  7225. {
  7226. QAction *action = reinterpret_cast<QAction *>(sender());
  7227. VolControl *vol = action->property("volControl").value<VolControl *>();
  7228. obs_source_t *source = vol->GetSource();
  7229. copyFiltersString = obs_source_get_name(source);
  7230. }
  7231. void OBSBasic::AudioMixerPasteFilters()
  7232. {
  7233. QAction *action = reinterpret_cast<QAction *>(sender());
  7234. VolControl *vol = action->property("volControl").value<VolControl *>();
  7235. obs_source_t *dstSource = vol->GetSource();
  7236. OBSSource source = obs_get_source_by_name(copyFiltersString);
  7237. obs_source_release(source);
  7238. if (source == dstSource)
  7239. return;
  7240. obs_source_copy_filters(dstSource, source);
  7241. }
  7242. void OBSBasic::SceneCopyFilters()
  7243. {
  7244. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  7245. }
  7246. void OBSBasic::ScenePasteFilters()
  7247. {
  7248. OBSSource source = obs_get_source_by_name(copyFiltersString);
  7249. obs_source_release(source);
  7250. OBSSource dstSource = GetCurrentSceneSource();
  7251. if (source == dstSource)
  7252. return;
  7253. obs_source_copy_filters(dstSource, source);
  7254. }
  7255. void OBSBasic::on_actionCopyFilters_triggered()
  7256. {
  7257. OBSSceneItem item = GetCurrentSceneItem();
  7258. if (!item)
  7259. return;
  7260. OBSSource source = obs_sceneitem_get_source(item);
  7261. copyFiltersString = obs_source_get_name(source);
  7262. ui->actionPasteFilters->setEnabled(true);
  7263. }
  7264. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  7265. obs_source_t *source,
  7266. obs_data_array_t *undo_array,
  7267. obs_data_array_t *redo_array)
  7268. {
  7269. auto undo_redo = [this](const std::string &json) {
  7270. obs_data_t *data = obs_data_create_from_json(json.c_str());
  7271. obs_data_array_t *array = obs_data_get_array(data, "array");
  7272. const char *name = obs_data_get_string(data, "name");
  7273. obs_source_t *source = obs_get_source_by_name(name);
  7274. obs_source_restore_filters(source, array);
  7275. obs_source_release(source);
  7276. obs_data_array_release(array);
  7277. obs_data_release(data);
  7278. if (filters)
  7279. filters->UpdateSource(source);
  7280. };
  7281. const char *name = obs_source_get_name(source);
  7282. obs_data_t *undo_data = obs_data_create();
  7283. obs_data_t *redo_data = obs_data_create();
  7284. obs_data_set_array(undo_data, "array", undo_array);
  7285. obs_data_set_array(redo_data, "array", redo_array);
  7286. obs_data_set_string(undo_data, "name", name);
  7287. obs_data_set_string(redo_data, "name", name);
  7288. undo_s.add_action(text, undo_redo, undo_redo,
  7289. obs_data_get_json(undo_data),
  7290. obs_data_get_json(redo_data));
  7291. obs_data_release(undo_data);
  7292. obs_data_release(redo_data);
  7293. }
  7294. void OBSBasic::on_actionPasteFilters_triggered()
  7295. {
  7296. OBSSource source = obs_get_source_by_name(copyFiltersString);
  7297. obs_source_release(source);
  7298. OBSSceneItem sceneItem = GetCurrentSceneItem();
  7299. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  7300. if (source == dstSource)
  7301. return;
  7302. obs_data_array_t *undo_array = obs_source_backup_filters(dstSource);
  7303. obs_source_copy_filters(dstSource, source);
  7304. obs_data_array_t *redo_array = obs_source_backup_filters(dstSource);
  7305. const char *srcName = obs_source_get_name(source);
  7306. const char *dstName = obs_source_get_name(dstSource);
  7307. QString text =
  7308. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  7309. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  7310. redo_array);
  7311. obs_data_array_release(undo_array);
  7312. obs_data_array_release(redo_array);
  7313. }
  7314. static void ConfirmColor(SourceTree *sources, const QColor &color,
  7315. QModelIndexList selectedItems)
  7316. {
  7317. for (int x = 0; x < selectedItems.count(); x++) {
  7318. SourceTreeItem *treeItem =
  7319. sources->GetItemWidget(selectedItems[x].row());
  7320. treeItem->setStyleSheet("background: " +
  7321. color.name(QColor::HexArgb));
  7322. treeItem->style()->unpolish(treeItem);
  7323. treeItem->style()->polish(treeItem);
  7324. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  7325. obs_data_t *privData =
  7326. obs_sceneitem_get_private_settings(sceneItem);
  7327. obs_data_set_int(privData, "color-preset", 1);
  7328. obs_data_set_string(privData, "color",
  7329. QT_TO_UTF8(color.name(QColor::HexArgb)));
  7330. obs_data_release(privData);
  7331. }
  7332. }
  7333. void OBSBasic::ColorChange()
  7334. {
  7335. QModelIndexList selectedItems =
  7336. ui->sources->selectionModel()->selectedIndexes();
  7337. QAction *action = qobject_cast<QAction *>(sender());
  7338. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  7339. if (selectedItems.count() == 0)
  7340. return;
  7341. if (colorButton) {
  7342. int preset = colorButton->property("bgColor").value<int>();
  7343. for (int x = 0; x < selectedItems.count(); x++) {
  7344. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  7345. selectedItems[x].row());
  7346. treeItem->setStyleSheet("");
  7347. treeItem->setProperty("bgColor", preset);
  7348. treeItem->style()->unpolish(treeItem);
  7349. treeItem->style()->polish(treeItem);
  7350. OBSSceneItem sceneItem =
  7351. ui->sources->Get(selectedItems[x].row());
  7352. obs_data_t *privData =
  7353. obs_sceneitem_get_private_settings(sceneItem);
  7354. obs_data_set_int(privData, "color-preset", preset + 1);
  7355. obs_data_set_string(privData, "color", "");
  7356. obs_data_release(privData);
  7357. }
  7358. for (int i = 1; i < 9; i++) {
  7359. stringstream button;
  7360. button << "preset" << i;
  7361. QPushButton *cButton =
  7362. colorButton->parentWidget()
  7363. ->findChild<QPushButton *>(
  7364. button.str().c_str());
  7365. cButton->setStyleSheet("border: 1px solid black");
  7366. }
  7367. colorButton->setStyleSheet("border: 2px solid black");
  7368. } else if (action) {
  7369. int preset = action->property("bgColor").value<int>();
  7370. if (preset == 1) {
  7371. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  7372. SourceTreeItem *curTreeItem =
  7373. GetItemWidgetFromSceneItem(curSceneItem);
  7374. obs_data_t *curPrivData =
  7375. obs_sceneitem_get_private_settings(
  7376. curSceneItem);
  7377. int oldPreset =
  7378. obs_data_get_int(curPrivData, "color-preset");
  7379. const QString oldSheet = curTreeItem->styleSheet();
  7380. auto liveChangeColor = [=](const QColor &color) {
  7381. if (color.isValid()) {
  7382. curTreeItem->setStyleSheet(
  7383. "background: " +
  7384. color.name(QColor::HexArgb));
  7385. }
  7386. };
  7387. auto changedColor = [=](const QColor &color) {
  7388. if (color.isValid()) {
  7389. ConfirmColor(ui->sources, color,
  7390. selectedItems);
  7391. }
  7392. };
  7393. auto rejected = [=]() {
  7394. if (oldPreset == 1) {
  7395. curTreeItem->setStyleSheet(oldSheet);
  7396. curTreeItem->setProperty("bgColor", 0);
  7397. } else if (oldPreset == 0) {
  7398. curTreeItem->setStyleSheet(
  7399. "background: none");
  7400. curTreeItem->setProperty("bgColor", 0);
  7401. } else {
  7402. curTreeItem->setStyleSheet("");
  7403. curTreeItem->setProperty("bgColor",
  7404. oldPreset - 1);
  7405. }
  7406. curTreeItem->style()->unpolish(curTreeItem);
  7407. curTreeItem->style()->polish(curTreeItem);
  7408. };
  7409. QColorDialog::ColorDialogOptions options =
  7410. QColorDialog::ShowAlphaChannel;
  7411. const char *oldColor =
  7412. obs_data_get_string(curPrivData, "color");
  7413. const char *customColor = *oldColor != 0 ? oldColor
  7414. : "#55FF0000";
  7415. #ifndef _WIN32
  7416. options |= QColorDialog::DontUseNativeDialog;
  7417. #endif
  7418. QColorDialog *colorDialog = new QColorDialog(this);
  7419. colorDialog->setOptions(options);
  7420. colorDialog->setCurrentColor(QColor(customColor));
  7421. connect(colorDialog, &QColorDialog::currentColorChanged,
  7422. liveChangeColor);
  7423. connect(colorDialog, &QColorDialog::colorSelected,
  7424. changedColor);
  7425. connect(colorDialog, &QColorDialog::rejected, rejected);
  7426. colorDialog->open();
  7427. obs_data_release(curPrivData);
  7428. } else {
  7429. for (int x = 0; x < selectedItems.count(); x++) {
  7430. SourceTreeItem *treeItem =
  7431. ui->sources->GetItemWidget(
  7432. selectedItems[x].row());
  7433. treeItem->setStyleSheet("background: none");
  7434. treeItem->setProperty("bgColor", preset);
  7435. treeItem->style()->unpolish(treeItem);
  7436. treeItem->style()->polish(treeItem);
  7437. OBSSceneItem sceneItem = ui->sources->Get(
  7438. selectedItems[x].row());
  7439. obs_data_t *privData =
  7440. obs_sceneitem_get_private_settings(
  7441. sceneItem);
  7442. obs_data_set_int(privData, "color-preset",
  7443. preset);
  7444. obs_data_set_string(privData, "color", "");
  7445. obs_data_release(privData);
  7446. }
  7447. }
  7448. }
  7449. }
  7450. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  7451. {
  7452. int i = 0;
  7453. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  7454. OBSSceneItem item = ui->sources->Get(i);
  7455. int64_t id = obs_sceneitem_get_id(sceneItem);
  7456. while (treeItem && obs_sceneitem_get_id(item) != id) {
  7457. i++;
  7458. treeItem = ui->sources->GetItemWidget(i);
  7459. item = ui->sources->Get(i);
  7460. }
  7461. if (treeItem)
  7462. return treeItem;
  7463. return nullptr;
  7464. }
  7465. void OBSBasic::on_autoConfigure_triggered()
  7466. {
  7467. AutoConfig test(this);
  7468. test.setModal(true);
  7469. test.show();
  7470. test.exec();
  7471. }
  7472. void OBSBasic::on_stats_triggered()
  7473. {
  7474. if (!stats.isNull()) {
  7475. stats->show();
  7476. stats->raise();
  7477. return;
  7478. }
  7479. OBSBasicStats *statsDlg;
  7480. statsDlg = new OBSBasicStats(nullptr);
  7481. statsDlg->show();
  7482. stats = statsDlg;
  7483. }
  7484. void OBSBasic::on_actionShowAbout_triggered()
  7485. {
  7486. if (about)
  7487. about->close();
  7488. about = new OBSAbout(this);
  7489. about->show();
  7490. about->setAttribute(Qt::WA_DeleteOnClose, true);
  7491. }
  7492. void OBSBasic::ResizeOutputSizeOfSource()
  7493. {
  7494. if (obs_video_active())
  7495. return;
  7496. QMessageBox resize_output(this);
  7497. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  7498. QTStr("ResizeOutputSizeOfSource.Continue"));
  7499. QAbstractButton *Yes =
  7500. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  7501. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  7502. resize_output.setIcon(QMessageBox::Warning);
  7503. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  7504. resize_output.exec();
  7505. if (resize_output.clickedButton() != Yes)
  7506. return;
  7507. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  7508. int width = obs_source_get_width(source);
  7509. int height = obs_source_get_height(source);
  7510. config_set_uint(basicConfig, "Video", "BaseCX", width);
  7511. config_set_uint(basicConfig, "Video", "BaseCY", height);
  7512. config_set_uint(basicConfig, "Video", "OutputCX", width);
  7513. config_set_uint(basicConfig, "Video", "OutputCY", height);
  7514. ResetVideo();
  7515. ResetOutputs();
  7516. config_save_safe(basicConfig, "tmp", nullptr);
  7517. on_actionFitToScreen_triggered();
  7518. }
  7519. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  7520. {
  7521. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  7522. action->setCheckable(true);
  7523. assignDockToggle(dock, action);
  7524. extraDocks.push_back(dock);
  7525. bool lock = ui->lockUI->isChecked();
  7526. QDockWidget::DockWidgetFeatures features =
  7527. lock ? QDockWidget::NoDockWidgetFeatures
  7528. : (QDockWidget::DockWidgetClosable |
  7529. QDockWidget::DockWidgetMovable |
  7530. QDockWidget::DockWidgetFloatable);
  7531. dock->setFeatures(features);
  7532. /* prune deleted docks */
  7533. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7534. if (!extraDocks[i]) {
  7535. extraDocks.removeAt(i);
  7536. }
  7537. }
  7538. return action;
  7539. }
  7540. OBSBasic *OBSBasic::Get()
  7541. {
  7542. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  7543. }
  7544. bool OBSBasic::StreamingActive()
  7545. {
  7546. if (!outputHandler)
  7547. return false;
  7548. return outputHandler->StreamingActive();
  7549. }
  7550. bool OBSBasic::RecordingActive()
  7551. {
  7552. if (!outputHandler)
  7553. return false;
  7554. return outputHandler->RecordingActive();
  7555. }
  7556. bool OBSBasic::ReplayBufferActive()
  7557. {
  7558. if (!outputHandler)
  7559. return false;
  7560. return outputHandler->ReplayBufferActive();
  7561. }
  7562. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  7563. : QStyledItemDelegate(parent)
  7564. {
  7565. }
  7566. void SceneRenameDelegate::setEditorData(QWidget *editor,
  7567. const QModelIndex &index) const
  7568. {
  7569. QStyledItemDelegate::setEditorData(editor, index);
  7570. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7571. if (lineEdit)
  7572. lineEdit->selectAll();
  7573. }
  7574. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  7575. {
  7576. if (event->type() == QEvent::KeyPress) {
  7577. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  7578. if (keyEvent->key() == Qt::Key_Escape) {
  7579. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7580. if (lineEdit)
  7581. lineEdit->undo();
  7582. }
  7583. }
  7584. return QStyledItemDelegate::eventFilter(editor, event);
  7585. }
  7586. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  7587. {
  7588. if (!error.isEmpty())
  7589. return;
  7590. patronJson = QT_TO_UTF8(text);
  7591. }
  7592. void OBSBasic::PauseRecording()
  7593. {
  7594. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7595. os_atomic_load_bool(&recording_paused))
  7596. return;
  7597. obs_output_t *output = outputHandler->fileOutput;
  7598. if (obs_output_pause(output, true)) {
  7599. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  7600. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  7601. pause->blockSignals(true);
  7602. pause->setChecked(true);
  7603. pause->blockSignals(false);
  7604. ui->statusbar->RecordingPaused();
  7605. if (trayIcon && trayIcon->isVisible()) {
  7606. #ifdef __APPLE__
  7607. QIcon trayIconFile =
  7608. QIcon(":/res/images/obs_paused_macos.png");
  7609. trayIconFile.setIsMask(true);
  7610. #else
  7611. QIcon trayIconFile =
  7612. QIcon(":/res/images/obs_paused.png");
  7613. #endif
  7614. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  7615. trayIconFile));
  7616. }
  7617. os_atomic_set_bool(&recording_paused, true);
  7618. if (api)
  7619. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  7620. if (os_atomic_load_bool(&replaybuf_active))
  7621. ShowReplayBufferPauseWarning();
  7622. }
  7623. }
  7624. void OBSBasic::UnpauseRecording()
  7625. {
  7626. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7627. !os_atomic_load_bool(&recording_paused))
  7628. return;
  7629. obs_output_t *output = outputHandler->fileOutput;
  7630. if (obs_output_pause(output, false)) {
  7631. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  7632. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  7633. pause->blockSignals(true);
  7634. pause->setChecked(false);
  7635. pause->blockSignals(false);
  7636. ui->statusbar->RecordingUnpaused();
  7637. if (trayIcon && trayIcon->isVisible()) {
  7638. #ifdef __APPLE__
  7639. QIcon trayIconFile =
  7640. QIcon(":/res/images/tray_active_macos.png");
  7641. trayIconFile.setIsMask(true);
  7642. #else
  7643. QIcon trayIconFile =
  7644. QIcon(":/res/images/tray_active.png");
  7645. #endif
  7646. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  7647. trayIconFile));
  7648. }
  7649. os_atomic_set_bool(&recording_paused, false);
  7650. if (api)
  7651. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  7652. }
  7653. }
  7654. void OBSBasic::PauseToggled()
  7655. {
  7656. if (!pause || !outputHandler || !outputHandler->fileOutput)
  7657. return;
  7658. obs_output_t *output = outputHandler->fileOutput;
  7659. bool enable = !obs_output_paused(output);
  7660. if (enable)
  7661. PauseRecording();
  7662. else
  7663. UnpauseRecording();
  7664. }
  7665. void OBSBasic::UpdatePause(bool activate)
  7666. {
  7667. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  7668. pause.reset();
  7669. return;
  7670. }
  7671. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  7672. bool adv = astrcmpi(mode, "Advanced") == 0;
  7673. bool shared;
  7674. if (adv) {
  7675. const char *recType =
  7676. config_get_string(basicConfig, "AdvOut", "RecType");
  7677. if (astrcmpi(recType, "FFmpeg") == 0) {
  7678. shared = config_get_bool(basicConfig, "AdvOut",
  7679. "FFOutputToFile");
  7680. } else {
  7681. const char *recordEncoder = config_get_string(
  7682. basicConfig, "AdvOut", "RecEncoder");
  7683. shared = astrcmpi(recordEncoder, "none") == 0;
  7684. }
  7685. } else {
  7686. const char *quality = config_get_string(
  7687. basicConfig, "SimpleOutput", "RecQuality");
  7688. shared = strcmp(quality, "Stream") == 0;
  7689. }
  7690. if (!shared) {
  7691. pause.reset(new QPushButton());
  7692. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  7693. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  7694. pause->setCheckable(true);
  7695. pause->setChecked(false);
  7696. pause->setProperty("themeID",
  7697. QVariant(QStringLiteral("pauseIconSmall")));
  7698. QSizePolicy sp;
  7699. sp.setHeightForWidth(true);
  7700. pause->setSizePolicy(sp);
  7701. connect(pause.data(), &QAbstractButton::clicked, this,
  7702. &OBSBasic::PauseToggled);
  7703. ui->recordingLayout->addWidget(pause.data());
  7704. } else {
  7705. pause.reset();
  7706. }
  7707. }
  7708. void OBSBasic::UpdateReplayBuffer(bool activate)
  7709. {
  7710. if (!activate || !outputHandler ||
  7711. !outputHandler->ReplayBufferActive()) {
  7712. replay.reset();
  7713. return;
  7714. }
  7715. replay.reset(new QPushButton());
  7716. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  7717. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  7718. replay->setChecked(false);
  7719. replay->setProperty("themeID",
  7720. QVariant(QStringLiteral("replayIconSmall")));
  7721. QSizePolicy sp;
  7722. sp.setHeightForWidth(true);
  7723. replay->setSizePolicy(sp);
  7724. connect(replay.data(), &QAbstractButton::clicked, this,
  7725. &OBSBasic::ReplayBufferSave);
  7726. replayLayout->addWidget(replay.data());
  7727. setTabOrder(replayLayout->itemAt(0)->widget(),
  7728. replayLayout->itemAt(1)->widget());
  7729. setTabOrder(replayLayout->itemAt(1)->widget(),
  7730. ui->buttonsVLayout->itemAt(3)->widget());
  7731. }
  7732. #define MBYTE (1024ULL * 1024ULL)
  7733. #define MBYTES_LEFT_STOP_REC 50ULL
  7734. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  7735. const char *OBSBasic::GetCurrentOutputPath()
  7736. {
  7737. const char *path = nullptr;
  7738. const char *mode = config_get_string(Config(), "Output", "Mode");
  7739. if (strcmp(mode, "Advanced") == 0) {
  7740. const char *advanced_mode =
  7741. config_get_string(Config(), "AdvOut", "RecType");
  7742. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  7743. path = config_get_string(Config(), "AdvOut",
  7744. "FFFilePath");
  7745. } else {
  7746. path = config_get_string(Config(), "AdvOut",
  7747. "RecFilePath");
  7748. }
  7749. } else {
  7750. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  7751. }
  7752. return path;
  7753. }
  7754. void OBSBasic::OutputPathInvalidMessage()
  7755. {
  7756. blog(LOG_ERROR, "Recording stopped because of bad output path");
  7757. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  7758. QTStr("Output.BadPath.Text"));
  7759. }
  7760. bool OBSBasic::OutputPathValid()
  7761. {
  7762. const char *mode = config_get_string(Config(), "Output", "Mode");
  7763. if (strcmp(mode, "Advanced") == 0) {
  7764. const char *advanced_mode =
  7765. config_get_string(Config(), "AdvOut", "RecType");
  7766. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  7767. bool is_local = config_get_bool(Config(), "AdvOut",
  7768. "FFOutputToFile");
  7769. if (!is_local)
  7770. return true;
  7771. }
  7772. }
  7773. const char *path = GetCurrentOutputPath();
  7774. return path && *path && QDir(path).exists();
  7775. }
  7776. void OBSBasic::DiskSpaceMessage()
  7777. {
  7778. blog(LOG_ERROR, "Recording stopped because of low disk space");
  7779. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  7780. QTStr("Output.RecordNoSpace.Msg"));
  7781. }
  7782. bool OBSBasic::LowDiskSpace()
  7783. {
  7784. const char *path;
  7785. path = GetCurrentOutputPath();
  7786. if (!path)
  7787. return false;
  7788. uint64_t num_bytes = os_get_free_disk_space(path);
  7789. if (num_bytes < (MAX_BYTES_LEFT))
  7790. return true;
  7791. else
  7792. return false;
  7793. }
  7794. void OBSBasic::CheckDiskSpaceRemaining()
  7795. {
  7796. if (LowDiskSpace()) {
  7797. StopRecording();
  7798. StopReplayBuffer();
  7799. DiskSpaceMessage();
  7800. }
  7801. }
  7802. void OBSBasic::ScenesReordered()
  7803. {
  7804. OBSProjector::UpdateMultiviewProjectors();
  7805. }
  7806. void OBSBasic::ResetStatsHotkey()
  7807. {
  7808. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  7809. foreach(OBSBasicStats * s, list) s->Reset();
  7810. }
  7811. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  7812. {
  7813. QWidget *widget = childAt(pos);
  7814. const char *className = nullptr;
  7815. if (widget != nullptr)
  7816. className = widget->metaObject()->className();
  7817. if (!className || strstr(className, "Dock") != nullptr)
  7818. ui->viewMenuDocks->exec(mapToGlobal(pos));
  7819. }
  7820. void OBSBasic::UpdateProjectorHideCursor()
  7821. {
  7822. for (size_t i = 0; i < projectors.size(); i++)
  7823. projectors[i]->SetHideCursor();
  7824. }
  7825. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  7826. {
  7827. for (size_t i = 0; i < projectors.size(); i++)
  7828. SetAlwaysOnTop(projectors[i], top);
  7829. }
  7830. void OBSBasic::ResetProjectors()
  7831. {
  7832. obs_data_array_t *savedProjectorList = SaveProjectors();
  7833. ClearProjectors();
  7834. LoadSavedProjectors(savedProjectorList);
  7835. OpenSavedProjectors();
  7836. obs_data_array_release(savedProjectorList);
  7837. }
  7838. void OBSBasic::on_sourcePropertiesButton_clicked()
  7839. {
  7840. on_actionSourceProperties_triggered();
  7841. }
  7842. void OBSBasic::on_sourceFiltersButton_clicked()
  7843. {
  7844. OpenFilters();
  7845. }
  7846. void OBSBasic::on_sourceInteractButton_clicked()
  7847. {
  7848. on_actionInteract_triggered();
  7849. }
  7850. void OBSBasic::ShowStatusBarMessage(const QString &message)
  7851. {
  7852. ui->statusbar->clearMessage();
  7853. ui->statusbar->showMessage(message, 10000);
  7854. }
  7855. void OBSBasic::UpdatePreviewSafeAreas()
  7856. {
  7857. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  7858. "ShowSafeAreas");
  7859. }