1
0

window-basic-main.cpp 244 KB

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