window-basic-main.cpp 184 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029
  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 <ctime>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QScreen>
  25. #include <QColorDialog>
  26. #include <QSizePolicy>
  27. #include <util/dstr.h>
  28. #include <util/util.hpp>
  29. #include <util/platform.h>
  30. #include <util/profiler.hpp>
  31. #include <util/dstr.hpp>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-log-reply.hpp"
  44. #include "window-projector.hpp"
  45. #include "window-remux.hpp"
  46. #include "qt-wrappers.hpp"
  47. #include "display-helpers.hpp"
  48. #include "volume-control.hpp"
  49. #include "remote-text.hpp"
  50. #include <fstream>
  51. #include <sstream>
  52. #ifdef _WIN32
  53. #include "win-update/win-update.hpp"
  54. #endif
  55. #include "ui_OBSBasic.h"
  56. #include "ui_ColorSelect.h"
  57. #include <fstream>
  58. #include <sstream>
  59. #include <QScreen>
  60. #include <QWindow>
  61. #include <json11.hpp>
  62. using namespace json11;
  63. using namespace std;
  64. #ifdef BROWSER_AVAILABLE
  65. #include <browser-panel.hpp>
  66. #endif
  67. #include "ui-config.h"
  68. struct QCef;
  69. struct QCefCookieManager;
  70. QCef *cef = nullptr;
  71. QCefCookieManager *panel_cookies = nullptr;
  72. void DestroyPanelCookieManager();
  73. namespace {
  74. template <typename OBSRef>
  75. struct SignalContainer {
  76. OBSRef ref;
  77. vector<shared_ptr<OBSSignal>> handlers;
  78. };
  79. }
  80. Q_DECLARE_METATYPE(OBSScene);
  81. Q_DECLARE_METATYPE(OBSSceneItem);
  82. Q_DECLARE_METATYPE(OBSSource);
  83. Q_DECLARE_METATYPE(obs_order_movement);
  84. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  85. template <typename T>
  86. static T GetOBSRef(QListWidgetItem *item)
  87. {
  88. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  89. }
  90. template <typename T>
  91. static void SetOBSRef(QListWidgetItem *item, T &&val)
  92. {
  93. item->setData(static_cast<int>(QtDataRole::OBSRef),
  94. QVariant::fromValue(val));
  95. }
  96. static void AddExtraModulePaths()
  97. {
  98. char base_module_dir[512];
  99. #if defined(_WIN32) || defined(__APPLE__)
  100. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  101. "obs-studio/plugins/%module%");
  102. #else
  103. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  104. "obs-studio/plugins/%module%");
  105. #endif
  106. if (ret <= 0)
  107. return;
  108. string path = (char*)base_module_dir;
  109. #if defined(__APPLE__)
  110. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  111. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  112. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  113. obs_add_module_path(config_bin, config_data);
  114. #elif ARCH_BITS == 64
  115. obs_add_module_path((path + "/bin/64bit").c_str(),
  116. (path + "/data").c_str());
  117. #else
  118. obs_add_module_path((path + "/bin/32bit").c_str(),
  119. (path + "/data").c_str());
  120. #endif
  121. }
  122. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  123. static int CountVideoSources()
  124. {
  125. int count = 0;
  126. auto countSources = [] (void *param, obs_source_t *source)
  127. {
  128. if (!source)
  129. return true;
  130. uint32_t flags = obs_source_get_output_flags(source);
  131. if ((flags & OBS_SOURCE_VIDEO) != 0)
  132. (*reinterpret_cast<int*>(param))++;
  133. return true;
  134. };
  135. obs_enum_sources(countSources, &count);
  136. return count;
  137. }
  138. void assignDockToggle(QDockWidget *dock, QAction *action)
  139. {
  140. auto handleWindowToggle = [action] (bool vis)
  141. {
  142. action->blockSignals(true);
  143. action->setChecked(vis);
  144. action->blockSignals(false);
  145. };
  146. auto handleMenuToggle = [dock] (bool check)
  147. {
  148. dock->blockSignals(true);
  149. dock->setVisible(check);
  150. dock->blockSignals(false);
  151. };
  152. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  153. handleWindowToggle);
  154. dock->connect(action, &QAction::toggled,
  155. handleMenuToggle);
  156. }
  157. extern void RegisterTwitchAuth();
  158. extern void RegisterMixerAuth();
  159. OBSBasic::OBSBasic(QWidget *parent)
  160. : OBSMainWindow (parent),
  161. ui (new Ui::OBSBasic)
  162. {
  163. setAttribute(Qt::WA_NativeWindow);
  164. #if TWITCH_ENABLED
  165. RegisterTwitchAuth();
  166. #endif
  167. #if MIXER_ENABLED
  168. RegisterMixerAuth();
  169. #endif
  170. setAcceptDrops(true);
  171. api = InitializeAPIInterface(this);
  172. ui->setupUi(this);
  173. ui->previewDisabledLabel->setVisible(false);
  174. startingDockLayout = saveState();
  175. statsDock = new QDockWidget();
  176. statsDock->setObjectName(QStringLiteral("statsDock"));
  177. statsDock->setFeatures(QDockWidget::AllDockWidgetFeatures);
  178. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  179. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  180. statsDock->setVisible(false);
  181. statsDock->setFloating(true);
  182. statsDock->resize(700, 200);
  183. copyActionsDynamicProperties();
  184. char styleSheetPath[512];
  185. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  186. "stylesheet.qss");
  187. if (ret > 0) {
  188. if (QFile::exists(styleSheetPath)) {
  189. QString path = QString("file:///") +
  190. QT_UTF8(styleSheetPath);
  191. App()->setStyleSheet(path);
  192. }
  193. }
  194. qRegisterMetaType<OBSScene> ("OBSScene");
  195. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  196. qRegisterMetaType<OBSSource> ("OBSSource");
  197. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  198. qRegisterMetaTypeStreamOperators<
  199. std::vector<std::shared_ptr<OBSSignal>>>(
  200. "std::vector<std::shared_ptr<OBSSignal>>");
  201. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  202. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  203. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  204. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  205. auto displayResize = [this]() {
  206. struct obs_video_info ovi;
  207. if (obs_get_video_info(&ovi))
  208. ResizePreview(ovi.base_width, ovi.base_height);
  209. };
  210. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  211. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  212. delete shortcutFilter;
  213. shortcutFilter = CreateShortcutFilter();
  214. installEventFilter(shortcutFilter);
  215. stringstream name;
  216. name << "OBS " << App()->GetVersionString();
  217. blog(LOG_INFO, "%s", name.str().c_str());
  218. blog(LOG_INFO, "---------------------------------");
  219. UpdateTitleBar();
  220. connect(ui->scenes->itemDelegate(),
  221. SIGNAL(closeEditor(QWidget*,
  222. QAbstractItemDelegate::EndEditHint)),
  223. this,
  224. SLOT(SceneNameEdited(QWidget*,
  225. QAbstractItemDelegate::EndEditHint)));
  226. cpuUsageInfo = os_cpu_usage_info_start();
  227. cpuUsageTimer = new QTimer(this);
  228. connect(cpuUsageTimer.data(), SIGNAL(timeout()),
  229. ui->statusbar, SLOT(UpdateCPUUsage()));
  230. cpuUsageTimer->start(3000);
  231. QAction *renameScene = new QAction(ui->scenesDock);
  232. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  233. connect(renameScene, SIGNAL(triggered()), this, SLOT(EditSceneName()));
  234. ui->scenesDock->addAction(renameScene);
  235. QAction *renameSource = new QAction(ui->sourcesDock);
  236. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  237. connect(renameSource, SIGNAL(triggered()), this,
  238. SLOT(EditSceneItemName()));
  239. ui->sourcesDock->addAction(renameSource);
  240. #ifdef __APPLE__
  241. renameScene->setShortcut({Qt::Key_Return});
  242. renameSource->setShortcut({Qt::Key_Return});
  243. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  244. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  245. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  246. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  247. #else
  248. renameScene->setShortcut({Qt::Key_F2});
  249. renameSource->setShortcut({Qt::Key_F2});
  250. #endif
  251. auto addNudge = [this](const QKeySequence &seq, const char *s)
  252. {
  253. QAction *nudge = new QAction(ui->preview);
  254. nudge->setShortcut(seq);
  255. nudge->setShortcutContext(Qt::WidgetShortcut);
  256. ui->preview->addAction(nudge);
  257. connect(nudge, SIGNAL(triggered()), this, s);
  258. };
  259. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  260. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  261. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  262. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  263. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  264. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  265. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  266. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  267. assignDockToggle(ui->controlsDock, ui->toggleControls);
  268. assignDockToggle(statsDock, ui->toggleStats);
  269. //hide all docking panes
  270. ui->toggleScenes->setChecked(false);
  271. ui->toggleSources->setChecked(false);
  272. ui->toggleMixer->setChecked(false);
  273. ui->toggleTransitions->setChecked(false);
  274. ui->toggleControls->setChecked(false);
  275. ui->toggleStats->setChecked(false);
  276. QPoint curPos;
  277. //restore parent window geometry
  278. const char *geometry = config_get_string(App()->GlobalConfig(),
  279. "BasicWindow", "geometry");
  280. if (geometry != NULL) {
  281. QByteArray byteArray = QByteArray::fromBase64(
  282. QByteArray(geometry));
  283. restoreGeometry(byteArray);
  284. QRect windowGeometry = normalGeometry();
  285. if (!WindowPositionValid(windowGeometry)) {
  286. QRect rect = App()->desktop()->geometry();
  287. setGeometry(QStyle::alignedRect(
  288. Qt::LeftToRight,
  289. Qt::AlignCenter,
  290. size(), rect));
  291. }
  292. curPos = pos();
  293. } else {
  294. QRect desktopRect = QGuiApplication::primaryScreen()->geometry();
  295. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  296. curPos = QPoint(adjSize.width(), adjSize.height());
  297. }
  298. QPoint curSize(width(), height());
  299. QPoint statsDockSize(statsDock->width(), statsDock->height());
  300. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  301. QPoint newPos = curPos + statsDockPos;
  302. statsDock->move(newPos);
  303. }
  304. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  305. vector<OBSSource> &audioSources)
  306. {
  307. obs_source_t *source = obs_get_output_source(channel);
  308. if (!source)
  309. return;
  310. audioSources.push_back(source);
  311. obs_data_t *data = obs_save_source(source);
  312. obs_data_set_obj(parent, name, data);
  313. obs_data_release(data);
  314. obs_source_release(source);
  315. }
  316. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  317. obs_data_array_t *quickTransitionData, int transitionDuration,
  318. obs_data_array_t *transitions,
  319. OBSScene &scene, OBSSource &curProgramScene,
  320. obs_data_array_t *savedProjectorList)
  321. {
  322. obs_data_t *saveData = obs_data_create();
  323. vector<OBSSource> audioSources;
  324. audioSources.reserve(5);
  325. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  326. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  327. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  328. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  329. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  330. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  331. /* -------------------------------- */
  332. /* save non-group sources */
  333. auto FilterAudioSources = [&](obs_source_t *source)
  334. {
  335. if (obs_source_is_group(source))
  336. return false;
  337. return find(begin(audioSources), end(audioSources), source) ==
  338. end(audioSources);
  339. };
  340. using FilterAudioSources_t = decltype(FilterAudioSources);
  341. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  342. [](void *data, obs_source_t *source)
  343. {
  344. return (*static_cast<FilterAudioSources_t*>(data))(source);
  345. }, static_cast<void*>(&FilterAudioSources));
  346. /* -------------------------------- */
  347. /* save group sources separately */
  348. /* saving separately ensures they won't be loaded in older versions */
  349. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  350. [](void*, obs_source_t *source)
  351. {
  352. return obs_source_is_group(source);
  353. }, nullptr);
  354. /* -------------------------------- */
  355. obs_source_t *transition = obs_get_output_source(0);
  356. obs_source_t *currentScene = obs_scene_get_source(scene);
  357. const char *sceneName = obs_source_get_name(currentScene);
  358. const char *programName = obs_source_get_name(curProgramScene);
  359. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  360. "Basic", "SceneCollection");
  361. obs_data_set_string(saveData, "current_scene", sceneName);
  362. obs_data_set_string(saveData, "current_program_scene", programName);
  363. obs_data_set_array(saveData, "scene_order", sceneOrder);
  364. obs_data_set_string(saveData, "name", sceneCollection);
  365. obs_data_set_array(saveData, "sources", sourcesArray);
  366. obs_data_set_array(saveData, "groups", groupsArray);
  367. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  368. obs_data_set_array(saveData, "transitions", transitions);
  369. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  370. obs_data_array_release(sourcesArray);
  371. obs_data_array_release(groupsArray);
  372. obs_data_set_string(saveData, "current_transition",
  373. obs_source_get_name(transition));
  374. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  375. obs_source_release(transition);
  376. return saveData;
  377. }
  378. void OBSBasic::copyActionsDynamicProperties()
  379. {
  380. // Themes need the QAction dynamic properties
  381. for (QAction *x : ui->scenesToolbar->actions()) {
  382. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  383. for (QByteArray &y : x->dynamicPropertyNames()) {
  384. temp->setProperty(y, x->property(y));
  385. }
  386. }
  387. for (QAction *x : ui->sourcesToolbar->actions()) {
  388. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  389. for (QByteArray &y : x->dynamicPropertyNames()) {
  390. temp->setProperty(y, x->property(y));
  391. }
  392. }
  393. }
  394. void OBSBasic::UpdateVolumeControlsDecayRate()
  395. {
  396. double meterDecayRate = config_get_double(basicConfig, "Audio",
  397. "MeterDecayRate");
  398. for (size_t i = 0; i < volumes.size(); i++) {
  399. volumes[i]->SetMeterDecayRate(meterDecayRate);
  400. }
  401. }
  402. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  403. {
  404. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  405. "PeakMeterType");
  406. enum obs_peak_meter_type peakMeterType;
  407. switch (peakMeterTypeIdx) {
  408. case 0:
  409. peakMeterType = SAMPLE_PEAK_METER;
  410. break;
  411. case 1:
  412. peakMeterType = TRUE_PEAK_METER;
  413. break;
  414. default:
  415. peakMeterType = SAMPLE_PEAK_METER;
  416. break;
  417. }
  418. for (size_t i = 0; i < volumes.size(); i++) {
  419. volumes[i]->setPeakMeterType(peakMeterType);
  420. }
  421. }
  422. void OBSBasic::ClearVolumeControls()
  423. {
  424. for (VolControl *vol : volumes)
  425. delete vol;
  426. volumes.clear();
  427. }
  428. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  429. {
  430. obs_data_array_t *sceneOrder = obs_data_array_create();
  431. for (int i = 0; i < ui->scenes->count(); i++) {
  432. obs_data_t *data = obs_data_create();
  433. obs_data_set_string(data, "name",
  434. QT_TO_UTF8(ui->scenes->item(i)->text()));
  435. obs_data_array_push_back(sceneOrder, data);
  436. obs_data_release(data);
  437. }
  438. return sceneOrder;
  439. }
  440. obs_data_array_t *OBSBasic::SaveProjectors()
  441. {
  442. obs_data_array_t *savedProjectors = obs_data_array_create();
  443. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  444. if (!projector)
  445. return;
  446. obs_data_t *data = obs_data_create();
  447. ProjectorType type = projector->GetProjectorType();
  448. switch (type) {
  449. case ProjectorType::Scene:
  450. case ProjectorType::Source: {
  451. obs_source_t *source = projector->GetSource();
  452. const char *name = obs_source_get_name(source);
  453. obs_data_set_string(data, "name", name);
  454. break;
  455. }
  456. default:
  457. break;
  458. }
  459. obs_data_set_int(data, "monitor", projector->GetMonitor());
  460. obs_data_set_int(data, "type", static_cast<int>(type));
  461. obs_data_set_string(data, "geometry",
  462. projector->saveGeometry().toBase64()
  463. .constData());
  464. obs_data_array_push_back(savedProjectors, data);
  465. obs_data_release(data);
  466. };
  467. for (QPointer<QWidget> &proj : projectors)
  468. saveProjector(static_cast<OBSProjector *>(proj.data()));
  469. for (QPointer<QWidget> &proj : windowProjectors)
  470. saveProjector(static_cast<OBSProjector *>(proj.data()));
  471. return savedProjectors;
  472. }
  473. void OBSBasic::Save(const char *file)
  474. {
  475. OBSScene scene = GetCurrentScene();
  476. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  477. if (!curProgramScene)
  478. curProgramScene = obs_scene_get_source(scene);
  479. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  480. obs_data_array_t *transitions = SaveTransitions();
  481. obs_data_array_t *quickTrData = SaveQuickTransitions();
  482. obs_data_array_t *savedProjectorList = SaveProjectors();
  483. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  484. ui->transitionDuration->value(), transitions,
  485. scene, curProgramScene, savedProjectorList);
  486. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  487. obs_data_set_bool(saveData, "scaling_enabled",
  488. ui->preview->IsFixedScaling());
  489. obs_data_set_int(saveData, "scaling_level",
  490. ui->preview->GetScalingLevel());
  491. obs_data_set_double(saveData, "scaling_off_x",
  492. ui->preview->GetScrollX());
  493. obs_data_set_double(saveData, "scaling_off_y",
  494. ui->preview->GetScrollY());
  495. if (api) {
  496. obs_data_t *moduleObj = obs_data_create();
  497. api->on_save(moduleObj);
  498. obs_data_set_obj(saveData, "modules", moduleObj);
  499. obs_data_release(moduleObj);
  500. }
  501. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  502. blog(LOG_ERROR, "Could not save scene data to %s", file);
  503. obs_data_release(saveData);
  504. obs_data_array_release(sceneOrder);
  505. obs_data_array_release(quickTrData);
  506. obs_data_array_release(transitions);
  507. obs_data_array_release(savedProjectorList);
  508. }
  509. void OBSBasic::DeferSaveBegin()
  510. {
  511. os_atomic_inc_long(&disableSaving);
  512. }
  513. void OBSBasic::DeferSaveEnd()
  514. {
  515. long result = os_atomic_dec_long(&disableSaving);
  516. if (result == 0) {
  517. SaveProject();
  518. }
  519. }
  520. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  521. {
  522. obs_data_t *data = obs_data_get_obj(parent, name);
  523. if (!data)
  524. return;
  525. obs_source_t *source = obs_load_source(data);
  526. if (source) {
  527. obs_set_output_source(channel, source);
  528. obs_source_release(source);
  529. }
  530. obs_data_release(data);
  531. }
  532. static inline bool HasAudioDevices(const char *source_id)
  533. {
  534. const char *output_id = source_id;
  535. obs_properties_t *props = obs_get_source_properties(output_id);
  536. size_t count = 0;
  537. if (!props)
  538. return false;
  539. obs_property_t *devices = obs_properties_get(props, "device_id");
  540. if (devices)
  541. count = obs_property_list_item_count(devices);
  542. obs_properties_destroy(props);
  543. return count != 0;
  544. }
  545. void OBSBasic::CreateFirstRunSources()
  546. {
  547. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  548. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  549. if (hasDesktopAudio)
  550. ResetAudioDevice(App()->OutputAudioSource(), "default",
  551. Str("Basic.DesktopDevice1"), 1);
  552. if (hasInputAudio)
  553. ResetAudioDevice(App()->InputAudioSource(), "default",
  554. Str("Basic.AuxDevice1"), 3);
  555. }
  556. void OBSBasic::CreateDefaultScene(bool firstStart)
  557. {
  558. disableSaving++;
  559. ClearSceneData();
  560. InitDefaultTransitions();
  561. CreateDefaultQuickTransitions();
  562. ui->transitionDuration->setValue(300);
  563. SetTransition(fadeTransition);
  564. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  565. if (firstStart)
  566. CreateFirstRunSources();
  567. SetCurrentScene(scene, true);
  568. obs_scene_release(scene);
  569. disableSaving--;
  570. }
  571. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  572. {
  573. for (int i = 0; i < lw->count(); i++) {
  574. QListWidgetItem *item = lw->item(i);
  575. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  576. if (newIndex != i) {
  577. item = lw->takeItem(i);
  578. lw->insertItem(newIndex, item);
  579. }
  580. break;
  581. }
  582. }
  583. }
  584. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  585. {
  586. size_t num = obs_data_array_count(array);
  587. for (size_t i = 0; i < num; i++) {
  588. obs_data_t *data = obs_data_array_item(array, i);
  589. const char *name = obs_data_get_string(data, "name");
  590. ReorderItemByName(ui->scenes, name, (int)i);
  591. obs_data_release(data);
  592. }
  593. }
  594. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  595. {
  596. for (SavedProjectorInfo *info : savedProjectorsArray) {
  597. delete info;
  598. }
  599. savedProjectorsArray.clear();
  600. size_t num = obs_data_array_count(array);
  601. for (size_t i = 0; i < num; i++) {
  602. obs_data_t *data = obs_data_array_item(array, i);
  603. SavedProjectorInfo *info = new SavedProjectorInfo();
  604. info->monitor = obs_data_get_int(data, "monitor");
  605. info->type = static_cast<ProjectorType>(obs_data_get_int(data,
  606. "type"));
  607. info->geometry = std::string(
  608. obs_data_get_string(data, "geometry"));
  609. info->name = std::string(obs_data_get_string(data, "name"));
  610. savedProjectorsArray.emplace_back(info);
  611. obs_data_release(data);
  612. }
  613. }
  614. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  615. {
  616. const char *name = obs_source_get_name(filter);
  617. const char *id = obs_source_get_id(filter);
  618. int val = (int)(intptr_t)v_val;
  619. string indent;
  620. for (int i = 0; i < val; i++)
  621. indent += " ";
  622. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  623. }
  624. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  625. {
  626. obs_source_t *source = obs_sceneitem_get_source(item);
  627. const char *name = obs_source_get_name(source);
  628. const char *id = obs_source_get_id(source);
  629. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  630. obs_monitoring_type monitoring_type =
  631. obs_source_get_monitoring_type(source);
  632. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  633. const char *type =
  634. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  635. ? "monitor only"
  636. : "monitor and output";
  637. blog(LOG_INFO, " - monitoring: %s", type);
  638. }
  639. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  640. return true;
  641. }
  642. void OBSBasic::LogScenes()
  643. {
  644. blog(LOG_INFO, "------------------------------------------------");
  645. blog(LOG_INFO, "Loaded scenes:");
  646. for (int i = 0; i < ui->scenes->count(); i++) {
  647. QListWidgetItem *item = ui->scenes->item(i);
  648. OBSScene scene = GetOBSRef<OBSScene>(item);
  649. obs_source_t *source = obs_scene_get_source(scene);
  650. const char *name = obs_source_get_name(source);
  651. blog(LOG_INFO, "- scene '%s':", name);
  652. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  653. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  654. }
  655. blog(LOG_INFO, "------------------------------------------------");
  656. }
  657. void OBSBasic::Load(const char *file)
  658. {
  659. disableSaving++;
  660. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  661. if (!data) {
  662. disableSaving--;
  663. blog(LOG_INFO, "No scene file found, creating default scene");
  664. CreateDefaultScene(true);
  665. SaveProject();
  666. return;
  667. }
  668. ClearSceneData();
  669. InitDefaultTransitions();
  670. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  671. if (api)
  672. api->on_preload(modulesObj);
  673. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  674. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  675. obs_data_array_t *groups = obs_data_get_array(data, "groups");
  676. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  677. const char *sceneName = obs_data_get_string(data,
  678. "current_scene");
  679. const char *programSceneName = obs_data_get_string(data,
  680. "current_program_scene");
  681. const char *transitionName = obs_data_get_string(data,
  682. "current_transition");
  683. if (!opt_starting_scene.empty()) {
  684. programSceneName = opt_starting_scene.c_str();
  685. if (!IsPreviewProgramMode())
  686. sceneName = opt_starting_scene.c_str();
  687. }
  688. int newDuration = obs_data_get_int(data, "transition_duration");
  689. if (!newDuration)
  690. newDuration = 300;
  691. if (!transitionName)
  692. transitionName = obs_source_get_name(fadeTransition);
  693. const char *curSceneCollection = config_get_string(
  694. App()->GlobalConfig(), "Basic", "SceneCollection");
  695. obs_data_set_default_string(data, "name", curSceneCollection);
  696. const char *name = obs_data_get_string(data, "name");
  697. obs_source_t *curScene;
  698. obs_source_t *curProgramScene;
  699. obs_source_t *curTransition;
  700. if (!name || !*name)
  701. name = curSceneCollection;
  702. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  703. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  704. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  705. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  706. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  707. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  708. if (!sources) {
  709. sources = groups;
  710. groups = nullptr;
  711. } else {
  712. obs_data_array_push_back_array(sources, groups);
  713. }
  714. obs_load_sources(sources, nullptr, nullptr);
  715. if (transitions)
  716. LoadTransitions(transitions);
  717. if (sceneOrder)
  718. LoadSceneListOrder(sceneOrder);
  719. obs_data_array_release(transitions);
  720. curTransition = FindTransition(transitionName);
  721. if (!curTransition)
  722. curTransition = fadeTransition;
  723. ui->transitionDuration->setValue(newDuration);
  724. SetTransition(curTransition);
  725. retryScene:
  726. curScene = obs_get_source_by_name(sceneName);
  727. curProgramScene = obs_get_source_by_name(programSceneName);
  728. /* if the starting scene command line parameter is bad at all,
  729. * fall back to original settings */
  730. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  731. sceneName = obs_data_get_string(data, "current_scene");
  732. programSceneName = obs_data_get_string(data,
  733. "current_program_scene");
  734. obs_source_release(curScene);
  735. obs_source_release(curProgramScene);
  736. opt_starting_scene.clear();
  737. goto retryScene;
  738. }
  739. if (!curProgramScene) {
  740. curProgramScene = curScene;
  741. obs_source_addref(curScene);
  742. }
  743. SetCurrentScene(curScene, true);
  744. if (IsPreviewProgramMode())
  745. TransitionToScene(curProgramScene, true);
  746. obs_source_release(curScene);
  747. obs_source_release(curProgramScene);
  748. obs_data_array_release(sources);
  749. obs_data_array_release(groups);
  750. obs_data_array_release(sceneOrder);
  751. /* ------------------- */
  752. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  753. "SaveProjectors");
  754. if (projectorSave) {
  755. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  756. "saved_projectors");
  757. if (savedProjectors) {
  758. LoadSavedProjectors(savedProjectors);
  759. OpenSavedProjectors();
  760. activateWindow();
  761. }
  762. obs_data_array_release(savedProjectors);
  763. }
  764. /* ------------------- */
  765. std::string file_base = strrchr(file, '/') + 1;
  766. file_base.erase(file_base.size() - 5, 5);
  767. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  768. name);
  769. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  770. file_base.c_str());
  771. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  772. "quick_transitions");
  773. LoadQuickTransitions(quickTransitionData);
  774. obs_data_array_release(quickTransitionData);
  775. RefreshQuickTransitions();
  776. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  777. ui->preview->SetLocked(previewLocked);
  778. ui->actionLockPreview->setChecked(previewLocked);
  779. /* ---------------------- */
  780. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  781. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  782. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  783. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  784. if (fixedScaling) {
  785. ui->preview->SetScalingLevel(scalingLevel);
  786. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  787. }
  788. ui->preview->SetFixedScaling(fixedScaling);
  789. /* ---------------------- */
  790. if (api)
  791. api->on_load(modulesObj);
  792. obs_data_release(modulesObj);
  793. obs_data_release(data);
  794. if (!opt_starting_scene.empty())
  795. opt_starting_scene.clear();
  796. if (opt_start_streaming) {
  797. blog(LOG_INFO, "Starting stream due to command line parameter");
  798. QMetaObject::invokeMethod(this, "StartStreaming",
  799. Qt::QueuedConnection);
  800. opt_start_streaming = false;
  801. }
  802. if (opt_start_recording) {
  803. blog(LOG_INFO, "Starting recording due to command line parameter");
  804. QMetaObject::invokeMethod(this, "StartRecording",
  805. Qt::QueuedConnection);
  806. opt_start_recording = false;
  807. }
  808. if (opt_start_replaybuffer) {
  809. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  810. Qt::QueuedConnection);
  811. opt_start_replaybuffer = false;
  812. }
  813. LogScenes();
  814. disableSaving--;
  815. if (api) {
  816. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  817. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  818. }
  819. }
  820. #define SERVICE_PATH "service.json"
  821. void OBSBasic::SaveService()
  822. {
  823. if (!service)
  824. return;
  825. char serviceJsonPath[512];
  826. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  827. SERVICE_PATH);
  828. if (ret <= 0)
  829. return;
  830. obs_data_t *data = obs_data_create();
  831. obs_data_t *settings = obs_service_get_settings(service);
  832. obs_data_set_string(data, "type", obs_service_get_type(service));
  833. obs_data_set_obj(data, "settings", settings);
  834. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  835. blog(LOG_WARNING, "Failed to save service");
  836. obs_data_release(settings);
  837. obs_data_release(data);
  838. }
  839. bool OBSBasic::LoadService()
  840. {
  841. const char *type;
  842. char serviceJsonPath[512];
  843. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  844. SERVICE_PATH);
  845. if (ret <= 0)
  846. return false;
  847. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  848. "bak");
  849. obs_data_set_default_string(data, "type", "rtmp_common");
  850. type = obs_data_get_string(data, "type");
  851. obs_data_t *settings = obs_data_get_obj(data, "settings");
  852. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  853. service = obs_service_create(type, "default_service", settings,
  854. hotkey_data);
  855. obs_service_release(service);
  856. obs_data_release(hotkey_data);
  857. obs_data_release(settings);
  858. obs_data_release(data);
  859. return !!service;
  860. }
  861. bool OBSBasic::InitService()
  862. {
  863. ProfileScope("OBSBasic::InitService");
  864. if (LoadService())
  865. return true;
  866. service = obs_service_create("rtmp_common", "default_service", nullptr,
  867. nullptr);
  868. if (!service)
  869. return false;
  870. obs_service_release(service);
  871. return true;
  872. }
  873. static const double scaled_vals[] =
  874. {
  875. 1.0,
  876. 1.25,
  877. (1.0/0.75),
  878. 1.5,
  879. (1.0/0.6),
  880. 1.75,
  881. 2.0,
  882. 2.25,
  883. 2.5,
  884. 2.75,
  885. 3.0,
  886. 0.0
  887. };
  888. extern void CheckExistingCookieId();
  889. bool OBSBasic::InitBasicConfigDefaults()
  890. {
  891. QList<QScreen*> screens = QGuiApplication::screens();
  892. if (!screens.size()) {
  893. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  894. "technically shouldn't be possible.");
  895. return false;
  896. }
  897. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  898. uint32_t cx = primaryScreen->size().width();
  899. uint32_t cy = primaryScreen->size().height();
  900. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  901. "General", "Pre19Defaults");
  902. /* use 1920x1080 for new default base res if main monitor is above
  903. * 1920x1080, but don't apply for people from older builds -- only to
  904. * new users */
  905. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  906. cx = 1920;
  907. cy = 1080;
  908. }
  909. bool changed = false;
  910. /* ----------------------------------------------------- */
  911. /* move over old FFmpeg track settings */
  912. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  913. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  914. int track = (int)config_get_int(basicConfig, "AdvOut",
  915. "FFAudioTrack");
  916. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  917. 1LL << (track - 1));
  918. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  919. changed = true;
  920. }
  921. /* ----------------------------------------------------- */
  922. /* move over mixer values in advanced if older config */
  923. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  924. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  925. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  926. "RecTrackIndex");
  927. track = 1ULL << (track - 1);
  928. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  929. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  930. changed = true;
  931. }
  932. /* ----------------------------------------------------- */
  933. if (changed)
  934. config_save_safe(basicConfig, "tmp", nullptr);
  935. /* ----------------------------------------------------- */
  936. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  937. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  938. GetDefaultVideoSavePath().c_str());
  939. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  940. "flv");
  941. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  942. 2500);
  943. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  944. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  945. false);
  946. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  947. true);
  948. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  949. "veryfast");
  950. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset",
  951. "hq");
  952. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  953. "Stream");
  954. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  955. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  956. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  957. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  958. "Replay");
  959. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  960. true);
  961. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  962. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  963. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  964. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  965. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  966. GetDefaultVideoSavePath().c_str());
  967. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  968. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  969. false);
  970. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  971. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  972. "none");
  973. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  974. true);
  975. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  976. GetDefaultVideoSavePath().c_str());
  977. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  978. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  979. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  980. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  981. false);
  982. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  983. false);
  984. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  985. config_set_default_uint (basicConfig, "AdvOut", "FFAudioMixes", 1);
  986. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  987. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  988. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  989. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  990. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  991. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  992. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  993. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  994. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  995. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  996. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  997. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  998. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  999. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1000. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1001. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1002. config_save_safe(basicConfig, "tmp", nullptr);
  1003. }
  1004. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1005. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1006. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  1007. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  1008. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  1009. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  1010. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  1011. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  1012. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1013. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  1014. false);
  1015. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  1016. false);
  1017. int i = 0;
  1018. uint32_t scale_cx = cx;
  1019. uint32_t scale_cy = cy;
  1020. /* use a default scaled resolution that has a pixel count no higher
  1021. * than 1280x720 */
  1022. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1023. double scale = scaled_vals[i++];
  1024. scale_cx = uint32_t(double(cx) / scale);
  1025. scale_cy = uint32_t(double(cy) / scale);
  1026. }
  1027. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  1028. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  1029. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1030. * changing */
  1031. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1032. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1033. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1034. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1035. config_save_safe(basicConfig, "tmp", nullptr);
  1036. }
  1037. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  1038. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1039. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  1040. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  1041. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  1042. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1043. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1044. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  1045. config_set_default_string(basicConfig, "Video", "ColorRange",
  1046. "Partial");
  1047. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1048. "default");
  1049. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  1050. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1051. ".Default"));
  1052. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  1053. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1054. "Stereo");
  1055. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1056. VOLUME_METER_DECAY_FAST);
  1057. config_set_default_uint (basicConfig, "Audio", "PeakMeterType", 0);
  1058. CheckExistingCookieId();
  1059. return true;
  1060. }
  1061. extern bool EncoderAvailable(const char *encoder);
  1062. void OBSBasic::InitBasicConfigDefaults2()
  1063. {
  1064. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(),
  1065. "General", "Pre23Defaults");
  1066. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1067. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1068. useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264);
  1069. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1070. useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264);
  1071. }
  1072. bool OBSBasic::InitBasicConfig()
  1073. {
  1074. ProfileScope("OBSBasic::InitBasicConfig");
  1075. char configPath[512];
  1076. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1077. if (ret <= 0) {
  1078. OBSErrorBox(nullptr, "Failed to get profile path");
  1079. return false;
  1080. }
  1081. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1082. OBSErrorBox(nullptr, "Failed to create profile path");
  1083. return false;
  1084. }
  1085. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1086. if (ret <= 0) {
  1087. OBSErrorBox(nullptr, "Failed to get base.ini path");
  1088. return false;
  1089. }
  1090. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1091. if (code != CONFIG_SUCCESS) {
  1092. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1093. return false;
  1094. }
  1095. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1096. const char *curName = config_get_string(App()->GlobalConfig(),
  1097. "Basic", "Profile");
  1098. config_set_string(basicConfig, "General", "Name", curName);
  1099. basicConfig.SaveSafe("tmp");
  1100. }
  1101. return InitBasicConfigDefaults();
  1102. }
  1103. void OBSBasic::InitOBSCallbacks()
  1104. {
  1105. ProfileScope("OBSBasic::InitOBSCallbacks");
  1106. signalHandlers.reserve(signalHandlers.size() + 6);
  1107. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1108. OBSBasic::SourceCreated, this);
  1109. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1110. OBSBasic::SourceRemoved, this);
  1111. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1112. OBSBasic::SourceActivated, this);
  1113. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  1114. OBSBasic::SourceDeactivated, this);
  1115. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1116. OBSBasic::SourceRenamed, this);
  1117. }
  1118. void OBSBasic::InitPrimitives()
  1119. {
  1120. ProfileScope("OBSBasic::InitPrimitives");
  1121. obs_enter_graphics();
  1122. gs_render_start(true);
  1123. gs_vertex2f(0.0f, 0.0f);
  1124. gs_vertex2f(0.0f, 1.0f);
  1125. gs_vertex2f(1.0f, 1.0f);
  1126. gs_vertex2f(1.0f, 0.0f);
  1127. gs_vertex2f(0.0f, 0.0f);
  1128. box = gs_render_save();
  1129. gs_render_start(true);
  1130. gs_vertex2f(0.0f, 0.0f);
  1131. gs_vertex2f(0.0f, 1.0f);
  1132. boxLeft = gs_render_save();
  1133. gs_render_start(true);
  1134. gs_vertex2f(0.0f, 0.0f);
  1135. gs_vertex2f(1.0f, 0.0f);
  1136. boxTop = gs_render_save();
  1137. gs_render_start(true);
  1138. gs_vertex2f(1.0f, 0.0f);
  1139. gs_vertex2f(1.0f, 1.0f);
  1140. boxRight = gs_render_save();
  1141. gs_render_start(true);
  1142. gs_vertex2f(0.0f, 1.0f);
  1143. gs_vertex2f(1.0f, 1.0f);
  1144. boxBottom = gs_render_save();
  1145. gs_render_start(true);
  1146. for (int i = 0; i <= 360; i += (360/20)) {
  1147. float pos = RAD(float(i));
  1148. gs_vertex2f(cosf(pos), sinf(pos));
  1149. }
  1150. circle = gs_render_save();
  1151. obs_leave_graphics();
  1152. }
  1153. void OBSBasic::ReplayBufferClicked()
  1154. {
  1155. if (outputHandler->ReplayBufferActive())
  1156. StopReplayBuffer();
  1157. else
  1158. StartReplayBuffer();
  1159. };
  1160. void OBSBasic::ResetOutputs()
  1161. {
  1162. ProfileScope("OBSBasic::ResetOutputs");
  1163. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1164. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1165. if (!outputHandler || !outputHandler->Active()) {
  1166. outputHandler.reset();
  1167. outputHandler.reset(advOut ?
  1168. CreateAdvancedOutputHandler(this) :
  1169. CreateSimpleOutputHandler(this));
  1170. delete replayBufferButton;
  1171. if (outputHandler->replayBuffer) {
  1172. replayBufferButton = new QPushButton(
  1173. QTStr("Basic.Main.StartReplayBuffer"),
  1174. this);
  1175. replayBufferButton->setCheckable(true);
  1176. connect(replayBufferButton.data(),
  1177. &QPushButton::clicked,
  1178. this,
  1179. &OBSBasic::ReplayBufferClicked);
  1180. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1181. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1182. }
  1183. if (sysTrayReplayBuffer)
  1184. sysTrayReplayBuffer->setEnabled(
  1185. !!outputHandler->replayBuffer);
  1186. } else {
  1187. outputHandler->Update();
  1188. }
  1189. }
  1190. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1191. const char *slot);
  1192. #define STARTUP_SEPARATOR \
  1193. "==== Startup complete ==============================================="
  1194. #define SHUTDOWN_SEPARATOR \
  1195. "==== Shutting down =================================================="
  1196. #define UNSUPPORTED_ERROR \
  1197. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1198. "not found. Your GPU may not be supported."
  1199. #define UNKNOWN_ERROR \
  1200. "Failed to initialize video. Your GPU may not be supported, " \
  1201. "or your graphics drivers may need to be updated."
  1202. void OBSBasic::OBSInit()
  1203. {
  1204. ProfileScope("OBSBasic::OBSInit");
  1205. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1206. "Basic", "SceneCollectionFile");
  1207. char savePath[512];
  1208. char fileName[512];
  1209. int ret;
  1210. if (!sceneCollection)
  1211. throw "Failed to get scene collection name";
  1212. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1213. sceneCollection);
  1214. if (ret <= 0)
  1215. throw "Failed to create scene collection file name";
  1216. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1217. if (ret <= 0)
  1218. throw "Failed to get scene collection json file path";
  1219. if (!InitBasicConfig())
  1220. throw "Failed to load basic.ini";
  1221. if (!ResetAudio())
  1222. throw "Failed to initialize audio";
  1223. ret = ResetVideo();
  1224. switch (ret) {
  1225. case OBS_VIDEO_MODULE_NOT_FOUND:
  1226. throw "Failed to initialize video: Graphics module not found";
  1227. case OBS_VIDEO_NOT_SUPPORTED:
  1228. throw UNSUPPORTED_ERROR;
  1229. case OBS_VIDEO_INVALID_PARAM:
  1230. throw "Failed to initialize video: Invalid parameters";
  1231. default:
  1232. if (ret != OBS_VIDEO_SUCCESS)
  1233. throw UNKNOWN_ERROR;
  1234. }
  1235. /* load audio monitoring */
  1236. #if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
  1237. const char *device_name = config_get_string(basicConfig, "Audio",
  1238. "MonitoringDeviceName");
  1239. const char *device_id = config_get_string(basicConfig, "Audio",
  1240. "MonitoringDeviceId");
  1241. obs_set_audio_monitoring_device(device_name, device_id);
  1242. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1243. device_name, device_id);
  1244. #endif
  1245. InitOBSCallbacks();
  1246. InitHotkeys();
  1247. AddExtraModulePaths();
  1248. blog(LOG_INFO, "---------------------------------");
  1249. obs_load_all_modules();
  1250. blog(LOG_INFO, "---------------------------------");
  1251. obs_log_loaded_modules();
  1252. blog(LOG_INFO, "---------------------------------");
  1253. obs_post_load_modules();
  1254. #ifdef BROWSER_AVAILABLE
  1255. cef = obs_browser_init_panel();
  1256. #endif
  1257. InitBasicConfigDefaults2();
  1258. CheckForSimpleModeX264Fallback();
  1259. blog(LOG_INFO, STARTUP_SEPARATOR);
  1260. ResetOutputs();
  1261. CreateHotkeys();
  1262. if (!InitService())
  1263. throw "Failed to initialize service";
  1264. InitPrimitives();
  1265. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1266. "BasicWindow", "SceneDuplicationMode");
  1267. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1268. "BasicWindow", "SwapScenesMode");
  1269. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1270. "BasicWindow", "EditPropertiesMode");
  1271. if (!opt_studio_mode) {
  1272. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1273. "BasicWindow", "PreviewProgramMode"));
  1274. } else {
  1275. SetPreviewProgramMode(true);
  1276. opt_studio_mode = false;
  1277. }
  1278. #define SET_VISIBILITY(name, control) \
  1279. do { \
  1280. if (config_has_user_value(App()->GlobalConfig(), \
  1281. "BasicWindow", name)) { \
  1282. bool visible = config_get_bool(App()->GlobalConfig(), \
  1283. "BasicWindow", name); \
  1284. ui->control->setChecked(visible); \
  1285. } \
  1286. } while (false)
  1287. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1288. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1289. #undef SET_VISIBILITY
  1290. #ifndef __APPLE__
  1291. {
  1292. ProfileScope("OBSBasic::Load");
  1293. disableSaving--;
  1294. Load(savePath);
  1295. disableSaving++;
  1296. }
  1297. #endif
  1298. TimedCheckForUpdates();
  1299. loaded = true;
  1300. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1301. "BasicWindow", "PreviewEnabled");
  1302. if (!previewEnabled && !IsPreviewProgramMode())
  1303. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1304. Qt::QueuedConnection,
  1305. Q_ARG(bool, previewEnabled));
  1306. #ifdef _WIN32
  1307. uint32_t winVer = GetWindowsVersion();
  1308. if (winVer > 0 && winVer < 0x602) {
  1309. bool disableAero = config_get_bool(basicConfig, "Video",
  1310. "DisableAero");
  1311. SetAeroEnabled(!disableAero);
  1312. }
  1313. #endif
  1314. #ifndef __APPLE__
  1315. RefreshSceneCollections();
  1316. #endif
  1317. RefreshProfiles();
  1318. disableSaving--;
  1319. auto addDisplay = [this] (OBSQTDisplay *window)
  1320. {
  1321. obs_display_add_draw_callback(window->GetDisplay(),
  1322. OBSBasic::RenderMain, this);
  1323. struct obs_video_info ovi;
  1324. if (obs_get_video_info(&ovi))
  1325. ResizePreview(ovi.base_width, ovi.base_height);
  1326. };
  1327. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1328. #ifdef _WIN32
  1329. SetWin32DropStyle(this);
  1330. show();
  1331. #endif
  1332. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1333. "AlwaysOnTop");
  1334. if (alwaysOnTop || opt_always_on_top) {
  1335. SetAlwaysOnTop(this, true);
  1336. ui->actionAlwaysOnTop->setChecked(true);
  1337. }
  1338. #ifndef _WIN32
  1339. show();
  1340. #endif
  1341. /* setup stats dock */
  1342. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1343. statsDock->setWidget(statsDlg);
  1344. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1345. "BasicWindow", "DockState");
  1346. if (!dockStateStr) {
  1347. on_resetUI_triggered();
  1348. } else {
  1349. QByteArray dockState =
  1350. QByteArray::fromBase64(QByteArray(dockStateStr));
  1351. if (!restoreState(dockState))
  1352. on_resetUI_triggered();
  1353. }
  1354. bool pre23Defaults = config_get_bool(App()->GlobalConfig(),
  1355. "General", "Pre23Defaults");
  1356. if (pre23Defaults) {
  1357. bool resetDockLock23 = config_get_bool(App()->GlobalConfig(),
  1358. "General", "ResetDockLock23");
  1359. if (!resetDockLock23) {
  1360. config_set_bool(App()->GlobalConfig(),
  1361. "General", "ResetDockLock23", true);
  1362. config_remove_value(App()->GlobalConfig(),
  1363. "BasicWindow", "DocksLocked");
  1364. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1365. }
  1366. }
  1367. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1368. "BasicWindow", "DocksLocked");
  1369. on_lockUI_toggled(docksLocked);
  1370. ui->lockUI->blockSignals(true);
  1371. ui->lockUI->setChecked(docksLocked);
  1372. ui->lockUI->blockSignals(false);
  1373. #ifndef __APPLE__
  1374. SystemTray(true);
  1375. #endif
  1376. if (windowState().testFlag(Qt::WindowFullScreen))
  1377. fullscreenInterface = true;
  1378. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1379. "General", "LastVersion");
  1380. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1381. "FirstRun");
  1382. if (!first_run) {
  1383. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1384. true);
  1385. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1386. }
  1387. if (!first_run && !has_last_version && !Active()) {
  1388. QString msg;
  1389. msg = QTStr("Basic.FirstStartup.RunWizard");
  1390. QMessageBox::StandardButton button =
  1391. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1392. msg);
  1393. if (button == QMessageBox::Yes) {
  1394. on_autoConfigure_triggered();
  1395. } else {
  1396. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1397. OBSMessageBox::information(this,
  1398. QTStr("Basic.AutoConfig"), msg);
  1399. }
  1400. }
  1401. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1402. "VerticalVolControl"));
  1403. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1404. on_stats_triggered();
  1405. OBSBasicStats::InitializeValues();
  1406. /* ----------------------- */
  1407. /* Add multiview menu */
  1408. ui->viewMenu->addSeparator();
  1409. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1410. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1411. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1412. SLOT(OpenMultiviewProjector()));
  1413. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1414. &OBSBasic::UpdateMultiviewProjectorMenu);
  1415. ui->viewMenu->addAction(QTStr("MultiviewWindowed"),
  1416. this, SLOT(OpenMultiviewWindow()));
  1417. #if !defined(_WIN32) && !defined(__APPLE__)
  1418. delete ui->actionShowCrashLogs;
  1419. delete ui->actionUploadLastCrashLog;
  1420. delete ui->menuCrashLogs;
  1421. delete ui->actionCheckForUpdates;
  1422. ui->actionShowCrashLogs = nullptr;
  1423. ui->actionUploadLastCrashLog = nullptr;
  1424. ui->menuCrashLogs = nullptr;
  1425. ui->actionCheckForUpdates = nullptr;
  1426. #endif
  1427. #ifdef __APPLE__
  1428. /* This is an incredibly unpleasant hack for macOS to isolate CEF
  1429. * initialization until after all tasks related to Qt startup and main
  1430. * window initialization have completed. There is a macOS-specific bug
  1431. * within either CEF and/or Qt that can cause a crash if both Qt and
  1432. * CEF are loading at the same time.
  1433. *
  1434. * CEF will typically load fine after about two iterations from this
  1435. * point, and all Qt tasks are typically fully completed after about
  1436. * four or five iterations, but to be "ultra" safe, an arbitrarily
  1437. * large number such as 10 is used. This hack is extremely unpleasant,
  1438. * but is worth doing instead of being forced to isolate the entire
  1439. * browser plugin in to a separate process as before.
  1440. *
  1441. * Again, this hack is specific to macOS only. Fortunately, on other
  1442. * operating systems, such issues do not occur. */
  1443. QMetaObject::invokeMethod(this, "DeferredLoad",
  1444. Qt::QueuedConnection,
  1445. Q_ARG(QString, QT_UTF8(savePath)),
  1446. Q_ARG(int, 10));
  1447. #else
  1448. OnFirstLoad();
  1449. #endif
  1450. }
  1451. void OBSBasic::OnFirstLoad()
  1452. {
  1453. if (api)
  1454. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1455. #ifdef BROWSER_AVAILABLE
  1456. /* Attempt to load init screen if available */
  1457. if (cef) {
  1458. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1459. if (wnit) {
  1460. connect(wnit, &WhatsNewInfoThread::Result,
  1461. this, &OBSBasic::ReceivedIntroJson);
  1462. }
  1463. if (wnit) {
  1464. introCheckThread.reset(wnit);
  1465. introCheckThread->start();
  1466. }
  1467. }
  1468. #endif
  1469. Auth::Load();
  1470. }
  1471. void OBSBasic::DeferredLoad(const QString &file, int requeueCount)
  1472. {
  1473. if (--requeueCount > 0) {
  1474. QMetaObject::invokeMethod(this, "DeferredLoad",
  1475. Qt::QueuedConnection,
  1476. Q_ARG(QString, file),
  1477. Q_ARG(int, requeueCount));
  1478. return;
  1479. }
  1480. Load(QT_TO_UTF8(file));
  1481. RefreshSceneCollections();
  1482. OnFirstLoad();
  1483. /* Minimizng to tray on initial startup does not work on mac
  1484. * unless it is done in the deferred load */
  1485. SystemTray(true);
  1486. }
  1487. /* shows a "what's new" page on startup of new versions using CEF */
  1488. void OBSBasic::ReceivedIntroJson(const QString &text)
  1489. {
  1490. #ifdef BROWSER_AVAILABLE
  1491. #ifdef _WIN32
  1492. std::string err;
  1493. Json json = Json::parse(QT_TO_UTF8(text), err);
  1494. if (!err.empty())
  1495. return;
  1496. std::string info_url;
  1497. int info_increment = -1;
  1498. /* check to see if there's an info page for this version */
  1499. const Json::array &items = json.array_items();
  1500. for (const Json &item : items) {
  1501. const std::string &version = item["version"].string_value();
  1502. const std::string &url = item["url"].string_value();
  1503. int increment = item["increment"].int_value();
  1504. int rc = item["RC"].int_value();
  1505. int major = 0;
  1506. int minor = 0;
  1507. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1508. #if OBS_RELEASE_CANDIDATE > 0
  1509. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1510. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1511. rc == OBS_RELEASE_CANDIDATE) {
  1512. #else
  1513. if (major == LIBOBS_API_MAJOR_VER &&
  1514. minor == LIBOBS_API_MINOR_VER &&
  1515. rc == 0) {
  1516. #endif
  1517. info_url = url;
  1518. info_increment = increment;
  1519. }
  1520. }
  1521. /* this version was not found, or no info for this version */
  1522. if (info_increment == -1) {
  1523. return;
  1524. }
  1525. #if OBS_RELEASE_CANDIDATE > 0
  1526. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1527. "LastRCVersion");
  1528. #else
  1529. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1530. "LastVersion");
  1531. #endif
  1532. int current_version_increment = -1;
  1533. #if OBS_RELEASE_CANDIDATE > 0
  1534. if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
  1535. #else
  1536. if (lastVersion < LIBOBS_API_VER) {
  1537. #endif
  1538. config_set_int(App()->GlobalConfig(), "General",
  1539. "InfoIncrement", -1);
  1540. } else {
  1541. current_version_increment = config_get_int(
  1542. App()->GlobalConfig(), "General",
  1543. "InfoIncrement");
  1544. }
  1545. if (info_increment <= current_version_increment) {
  1546. return;
  1547. }
  1548. cef->init_browser();
  1549. ExecuteFuncSafeBlock([] {cef->wait_for_browser_init();});
  1550. config_set_int(App()->GlobalConfig(), "General",
  1551. "InfoIncrement", info_increment);
  1552. QDialog *dlg = new QDialog(this);
  1553. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1554. dlg->setWindowTitle("What's New");
  1555. dlg->resize(700, 600);
  1556. Qt::WindowFlags flags = dlg->windowFlags();
  1557. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1558. dlg->setWindowFlags(flags & (~helpFlag));
  1559. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1560. if (!cefWidget) {
  1561. return;
  1562. }
  1563. connect(cefWidget, SIGNAL(titleChanged(const QString &)),
  1564. dlg, SLOT(setWindowTitle(const QString &)));
  1565. QPushButton *close = new QPushButton(QTStr("Close"));
  1566. connect(close, &QAbstractButton::clicked,
  1567. dlg, &QDialog::accept);
  1568. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1569. bottomLayout->addStretch();
  1570. bottomLayout->addWidget(close);
  1571. bottomLayout->addStretch();
  1572. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1573. topLayout->addWidget(cefWidget);
  1574. topLayout->addLayout(bottomLayout);
  1575. dlg->show();
  1576. #else
  1577. UNUSED_PARAMETER(text);
  1578. #endif
  1579. #else
  1580. UNUSED_PARAMETER(text);
  1581. #endif
  1582. }
  1583. void OBSBasic::UpdateMultiviewProjectorMenu()
  1584. {
  1585. multiviewProjectorMenu->clear();
  1586. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1587. SLOT(OpenMultiviewProjector()));
  1588. }
  1589. void OBSBasic::InitHotkeys()
  1590. {
  1591. ProfileScope("OBSBasic::InitHotkeys");
  1592. struct obs_hotkeys_translations t = {};
  1593. t.insert = Str("Hotkeys.Insert");
  1594. t.del = Str("Hotkeys.Delete");
  1595. t.home = Str("Hotkeys.Home");
  1596. t.end = Str("Hotkeys.End");
  1597. t.page_up = Str("Hotkeys.PageUp");
  1598. t.page_down = Str("Hotkeys.PageDown");
  1599. t.num_lock = Str("Hotkeys.NumLock");
  1600. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1601. t.caps_lock = Str("Hotkeys.CapsLock");
  1602. t.backspace = Str("Hotkeys.Backspace");
  1603. t.tab = Str("Hotkeys.Tab");
  1604. t.print = Str("Hotkeys.Print");
  1605. t.pause = Str("Hotkeys.Pause");
  1606. t.left = Str("Hotkeys.Left");
  1607. t.right = Str("Hotkeys.Right");
  1608. t.up = Str("Hotkeys.Up");
  1609. t.down = Str("Hotkeys.Down");
  1610. #ifdef _WIN32
  1611. t.meta = Str("Hotkeys.Windows");
  1612. #else
  1613. t.meta = Str("Hotkeys.Super");
  1614. #endif
  1615. t.menu = Str("Hotkeys.Menu");
  1616. t.space = Str("Hotkeys.Space");
  1617. t.numpad_num = Str("Hotkeys.NumpadNum");
  1618. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1619. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1620. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1621. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1622. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1623. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1624. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1625. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1626. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1627. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1628. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1629. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1630. t.mouse_num = Str("Hotkeys.MouseButton");
  1631. obs_hotkeys_set_translations(&t);
  1632. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1633. Str("Push-to-mute"), Str("Push-to-talk"));
  1634. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1635. Str("SceneItemShow"), Str("SceneItemHide"));
  1636. obs_hotkey_enable_callback_rerouting(true);
  1637. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1638. }
  1639. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1640. {
  1641. obs_hotkey_trigger_routed_callback(id, pressed);
  1642. }
  1643. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1644. {
  1645. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1646. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1647. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1648. }
  1649. void OBSBasic::CreateHotkeys()
  1650. {
  1651. ProfileScope("OBSBasic::CreateHotkeys");
  1652. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1653. {
  1654. const char *info = config_get_string(basicConfig,
  1655. "Hotkeys", name);
  1656. if (!info)
  1657. return {};
  1658. obs_data_t *data = obs_data_create_from_json(info);
  1659. if (!data)
  1660. return {};
  1661. OBSData res = data;
  1662. obs_data_release(data);
  1663. return res;
  1664. };
  1665. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1666. {
  1667. obs_data_array_t *array =
  1668. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1669. obs_hotkey_load(id, array);
  1670. obs_data_array_release(array);
  1671. };
  1672. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1673. const char *name1)
  1674. {
  1675. obs_data_array_t *array0 =
  1676. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1677. obs_data_array_t *array1 =
  1678. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1679. obs_hotkey_pair_load(id, array0, array1);
  1680. obs_data_array_release(array0);
  1681. obs_data_array_release(array1);
  1682. };
  1683. #define MAKE_CALLBACK(pred, method, log_action) \
  1684. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1685. { \
  1686. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1687. if ((pred) && pressed) { \
  1688. blog(LOG_INFO, log_action " due to hotkey"); \
  1689. method(); \
  1690. return true; \
  1691. } \
  1692. return false; \
  1693. }
  1694. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1695. "OBSBasic.StartStreaming",
  1696. Str("Basic.Main.StartStreaming"),
  1697. "OBSBasic.StopStreaming",
  1698. Str("Basic.Main.StopStreaming"),
  1699. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1700. basic.ui->streamButton->isEnabled(),
  1701. basic.StartStreaming, "Starting stream"),
  1702. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1703. basic.ui->streamButton->isEnabled(),
  1704. basic.StopStreaming, "Stopping stream"),
  1705. this, this);
  1706. LoadHotkeyPair(streamingHotkeys,
  1707. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1708. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1709. {
  1710. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1711. if (basic.outputHandler->StreamingActive() && pressed) {
  1712. basic.ForceStopStreaming();
  1713. }
  1714. };
  1715. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1716. "OBSBasic.ForceStopStreaming",
  1717. Str("Basic.Main.ForceStopStreaming"),
  1718. cb, this);
  1719. LoadHotkey(forceStreamingStopHotkey,
  1720. "OBSBasic.ForceStopStreaming");
  1721. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1722. "OBSBasic.StartRecording",
  1723. Str("Basic.Main.StartRecording"),
  1724. "OBSBasic.StopRecording",
  1725. Str("Basic.Main.StopRecording"),
  1726. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1727. !basic.ui->recordButton->isChecked(),
  1728. basic.StartRecording, "Starting recording"),
  1729. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1730. basic.ui->recordButton->isChecked(),
  1731. basic.StopRecording, "Stopping recording"),
  1732. this, this);
  1733. LoadHotkeyPair(recordingHotkeys,
  1734. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1735. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1736. "OBSBasic.StartReplayBuffer",
  1737. Str("Basic.Main.StartReplayBuffer"),
  1738. "OBSBasic.StopReplayBuffer",
  1739. Str("Basic.Main.StopReplayBuffer"),
  1740. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1741. basic.StartReplayBuffer, "Starting replay buffer"),
  1742. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1743. basic.StopReplayBuffer, "Stopping replay buffer"),
  1744. this, this);
  1745. LoadHotkeyPair(replayBufHotkeys,
  1746. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1747. #undef MAKE_CALLBACK
  1748. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1749. obs_hotkey_t*, bool pressed)
  1750. {
  1751. if (pressed)
  1752. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1753. "on_modeSwitch_clicked",
  1754. Qt::QueuedConnection);
  1755. };
  1756. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1757. "OBSBasic.TogglePreviewProgram",
  1758. Str("Basic.TogglePreviewProgramMode"),
  1759. togglePreviewProgram, this);
  1760. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1761. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1762. bool pressed)
  1763. {
  1764. if (pressed)
  1765. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1766. "TransitionClicked",
  1767. Qt::QueuedConnection);
  1768. };
  1769. transitionHotkey = obs_hotkey_register_frontend(
  1770. "OBSBasic.Transition",
  1771. Str("Transition"), transition, this);
  1772. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1773. }
  1774. void OBSBasic::ClearHotkeys()
  1775. {
  1776. obs_hotkey_pair_unregister(streamingHotkeys);
  1777. obs_hotkey_pair_unregister(recordingHotkeys);
  1778. obs_hotkey_pair_unregister(replayBufHotkeys);
  1779. obs_hotkey_unregister(forceStreamingStopHotkey);
  1780. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1781. obs_hotkey_unregister(transitionHotkey);
  1782. }
  1783. OBSBasic::~OBSBasic()
  1784. {
  1785. if (updateCheckThread && updateCheckThread->isRunning())
  1786. updateCheckThread->wait();
  1787. delete multiviewProjectorMenu;
  1788. delete previewProjector;
  1789. delete studioProgramProjector;
  1790. delete previewProjectorSource;
  1791. delete previewProjectorMain;
  1792. delete sourceProjector;
  1793. delete sceneProjectorMenu;
  1794. delete scaleFilteringMenu;
  1795. delete colorMenu;
  1796. delete colorWidgetAction;
  1797. delete colorSelect;
  1798. delete deinterlaceMenu;
  1799. delete perSceneTransitionMenu;
  1800. delete shortcutFilter;
  1801. delete trayMenu;
  1802. delete programOptions;
  1803. delete program;
  1804. /* XXX: any obs data must be released before calling obs_shutdown.
  1805. * currently, we can't automate this with C++ RAII because of the
  1806. * delicate nature of obs_shutdown needing to be freed before the UI
  1807. * can be freed, and we have no control over the destruction order of
  1808. * the Qt UI stuff, so we have to manually clear any references to
  1809. * libobs. */
  1810. delete cpuUsageTimer;
  1811. os_cpu_usage_info_destroy(cpuUsageInfo);
  1812. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1813. ClearHotkeys();
  1814. service = nullptr;
  1815. outputHandler.reset();
  1816. if (interaction)
  1817. delete interaction;
  1818. if (properties)
  1819. delete properties;
  1820. if (filters)
  1821. delete filters;
  1822. if (transformWindow)
  1823. delete transformWindow;
  1824. if (advAudioWindow)
  1825. delete advAudioWindow;
  1826. if (about)
  1827. delete about;
  1828. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1829. OBSBasic::RenderMain, this);
  1830. obs_enter_graphics();
  1831. gs_vertexbuffer_destroy(box);
  1832. gs_vertexbuffer_destroy(boxLeft);
  1833. gs_vertexbuffer_destroy(boxTop);
  1834. gs_vertexbuffer_destroy(boxRight);
  1835. gs_vertexbuffer_destroy(boxBottom);
  1836. gs_vertexbuffer_destroy(circle);
  1837. obs_leave_graphics();
  1838. /* When shutting down, sometimes source references can get in to the
  1839. * event queue, and if we don't forcibly process those events they
  1840. * won't get processed until after obs_shutdown has been called. I
  1841. * really wish there were a more elegant way to deal with this via C++,
  1842. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1843. * normal C++ behavior for your data to be freed in the order that you
  1844. * expect or want it to. */
  1845. QApplication::sendPostedEvents(this);
  1846. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1847. LIBOBS_API_VER);
  1848. #if OBS_RELEASE_CANDIDATE > 0
  1849. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  1850. OBS_RELEASE_CANDIDATE_VER);
  1851. #endif
  1852. bool alwaysOnTop = IsAlwaysOnTop(this);
  1853. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1854. previewEnabled);
  1855. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1856. alwaysOnTop);
  1857. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1858. "SceneDuplicationMode", sceneDuplicationMode);
  1859. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1860. "SwapScenesMode", swapScenesMode);
  1861. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1862. "EditPropertiesMode", editPropertiesMode);
  1863. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1864. "PreviewProgramMode", IsPreviewProgramMode());
  1865. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1866. "DocksLocked", ui->lockUI->isChecked());
  1867. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1868. #ifdef _WIN32
  1869. uint32_t winVer = GetWindowsVersion();
  1870. if (winVer > 0 && winVer < 0x602) {
  1871. bool disableAero = config_get_bool(basicConfig, "Video",
  1872. "DisableAero");
  1873. if (disableAero) {
  1874. SetAeroEnabled(true);
  1875. }
  1876. }
  1877. #endif
  1878. #ifdef BROWSER_AVAILABLE
  1879. DestroyPanelCookieManager();
  1880. delete cef;
  1881. cef = nullptr;
  1882. #endif
  1883. }
  1884. void OBSBasic::SaveProjectNow()
  1885. {
  1886. if (disableSaving)
  1887. return;
  1888. projectChanged = true;
  1889. SaveProjectDeferred();
  1890. }
  1891. void OBSBasic::SaveProject()
  1892. {
  1893. if (disableSaving)
  1894. return;
  1895. projectChanged = true;
  1896. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1897. Qt::QueuedConnection);
  1898. }
  1899. void OBSBasic::SaveProjectDeferred()
  1900. {
  1901. if (disableSaving)
  1902. return;
  1903. if (!projectChanged)
  1904. return;
  1905. projectChanged = false;
  1906. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1907. "Basic", "SceneCollectionFile");
  1908. char savePath[512];
  1909. char fileName[512];
  1910. int ret;
  1911. if (!sceneCollection)
  1912. return;
  1913. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1914. sceneCollection);
  1915. if (ret <= 0)
  1916. return;
  1917. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1918. if (ret <= 0)
  1919. return;
  1920. Save(savePath);
  1921. }
  1922. OBSSource OBSBasic::GetProgramSource()
  1923. {
  1924. return OBSGetStrongRef(programScene);
  1925. }
  1926. OBSScene OBSBasic::GetCurrentScene()
  1927. {
  1928. QListWidgetItem *item = ui->scenes->currentItem();
  1929. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1930. }
  1931. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1932. {
  1933. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1934. }
  1935. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1936. {
  1937. return ui->sources->Get(GetTopSelectedSourceItem());
  1938. }
  1939. void OBSBasic::UpdatePreviewScalingMenu()
  1940. {
  1941. bool fixedScaling = ui->preview->IsFixedScaling();
  1942. float scalingAmount = ui->preview->GetScalingAmount();
  1943. if (!fixedScaling) {
  1944. ui->actionScaleWindow->setChecked(true);
  1945. ui->actionScaleCanvas->setChecked(false);
  1946. ui->actionScaleOutput->setChecked(false);
  1947. return;
  1948. }
  1949. obs_video_info ovi;
  1950. obs_get_video_info(&ovi);
  1951. ui->actionScaleWindow->setChecked(false);
  1952. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1953. ui->actionScaleOutput->setChecked(
  1954. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1955. }
  1956. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1957. {
  1958. if (interaction)
  1959. interaction->close();
  1960. interaction = new OBSBasicInteraction(this, source);
  1961. interaction->Init();
  1962. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1963. }
  1964. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1965. {
  1966. if (properties)
  1967. properties->close();
  1968. properties = new OBSBasicProperties(this, source);
  1969. properties->Init();
  1970. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1971. }
  1972. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1973. {
  1974. if (filters)
  1975. filters->close();
  1976. filters = new OBSBasicFilters(this, source);
  1977. filters->Init();
  1978. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1979. }
  1980. /* Qt callbacks for invokeMethod */
  1981. void OBSBasic::AddScene(OBSSource source)
  1982. {
  1983. const char *name = obs_source_get_name(source);
  1984. obs_scene_t *scene = obs_scene_from_source(source);
  1985. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1986. SetOBSRef(item, OBSScene(scene));
  1987. ui->scenes->addItem(item);
  1988. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1989. Str("Basic.Hotkeys.SelectScene"),
  1990. [](void *data,
  1991. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1992. {
  1993. OBSBasic *main =
  1994. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1995. auto potential_source = static_cast<obs_source_t*>(data);
  1996. auto source = obs_source_get_ref(potential_source);
  1997. if (source && pressed)
  1998. main->SetCurrentScene(source);
  1999. obs_source_release(source);
  2000. }, static_cast<obs_source_t*>(source));
  2001. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2002. SignalContainer<OBSScene> container;
  2003. container.ref = scene;
  2004. container.handlers.assign({
  2005. std::make_shared<OBSSignal>(handler, "item_add",
  2006. OBSBasic::SceneItemAdded, this),
  2007. std::make_shared<OBSSignal>(handler, "item_select",
  2008. OBSBasic::SceneItemSelected, this),
  2009. std::make_shared<OBSSignal>(handler, "item_deselect",
  2010. OBSBasic::SceneItemDeselected, this),
  2011. std::make_shared<OBSSignal>(handler, "reorder",
  2012. OBSBasic::SceneReordered, this),
  2013. });
  2014. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2015. QVariant::fromValue(container));
  2016. /* if the scene already has items (a duplicated scene) add them */
  2017. auto addSceneItem = [this] (obs_sceneitem_t *item)
  2018. {
  2019. AddSceneItem(item);
  2020. };
  2021. using addSceneItem_t = decltype(addSceneItem);
  2022. obs_scene_enum_items(scene,
  2023. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  2024. {
  2025. addSceneItem_t *func;
  2026. func = reinterpret_cast<addSceneItem_t*>(param);
  2027. (*func)(item);
  2028. return true;
  2029. }, &addSceneItem);
  2030. SaveProject();
  2031. if (!disableSaving) {
  2032. obs_source_t *source = obs_scene_get_source(scene);
  2033. blog(LOG_INFO, "User added scene '%s'",
  2034. obs_source_get_name(source));
  2035. OBSProjector::UpdateMultiviewProjectors();
  2036. }
  2037. if (api)
  2038. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2039. }
  2040. void OBSBasic::RemoveScene(OBSSource source)
  2041. {
  2042. obs_scene_t *scene = obs_scene_from_source(source);
  2043. QListWidgetItem *sel = nullptr;
  2044. int count = ui->scenes->count();
  2045. for (int i = 0; i < count; i++) {
  2046. auto item = ui->scenes->item(i);
  2047. auto cur_scene = GetOBSRef<OBSScene>(item);
  2048. if (cur_scene != scene)
  2049. continue;
  2050. sel = item;
  2051. break;
  2052. }
  2053. if (sel != nullptr) {
  2054. if (sel == ui->scenes->currentItem())
  2055. ui->sources->Clear();
  2056. delete sel;
  2057. }
  2058. SaveProject();
  2059. if (!disableSaving) {
  2060. blog(LOG_INFO, "User Removed scene '%s'",
  2061. obs_source_get_name(source));
  2062. OBSProjector::UpdateMultiviewProjectors();
  2063. }
  2064. if (api)
  2065. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2066. }
  2067. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2068. {
  2069. obs_sceneitem_t *selectedItem =
  2070. reinterpret_cast<obs_sceneitem_t*>(param);
  2071. if (obs_sceneitem_is_group(item))
  2072. obs_sceneitem_group_enum_items(item, select_one, param);
  2073. obs_sceneitem_select(item, (selectedItem == item));
  2074. UNUSED_PARAMETER(scene);
  2075. return true;
  2076. }
  2077. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2078. {
  2079. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2080. if (GetCurrentScene() == scene)
  2081. ui->sources->Add(item);
  2082. SaveProject();
  2083. if (!disableSaving) {
  2084. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2085. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2086. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2087. obs_source_get_name(itemSource),
  2088. obs_source_get_id(itemSource),
  2089. obs_source_get_name(sceneSource));
  2090. obs_scene_enum_items(scene, select_one, (obs_sceneitem_t*)item);
  2091. }
  2092. }
  2093. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2094. {
  2095. if (source) {
  2096. obs_scene_t *scene = obs_scene_from_source(source);
  2097. const char *name = obs_source_get_name(source);
  2098. if (!scene)
  2099. return;
  2100. QList<QListWidgetItem*> items =
  2101. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2102. if (items.count()) {
  2103. sceneChanging = true;
  2104. ui->scenes->setCurrentItem(items.first());
  2105. sceneChanging = false;
  2106. OBSScene curScene =
  2107. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2108. if (api && scene != curScene)
  2109. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2110. }
  2111. }
  2112. }
  2113. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2114. const QString &prevName)
  2115. {
  2116. QList<QListWidgetItem*> items =
  2117. listWidget->findItems(prevName, Qt::MatchExactly);
  2118. for (int i = 0; i < items.count(); i++)
  2119. items[i]->setText(newName);
  2120. }
  2121. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2122. QString prevName)
  2123. {
  2124. RenameListValues(ui->scenes, newName, prevName);
  2125. for (size_t i = 0; i < volumes.size(); i++) {
  2126. if (volumes[i]->GetName().compare(prevName) == 0)
  2127. volumes[i]->SetName(newName);
  2128. }
  2129. OBSProjector::RenameProjector(prevName, newName);
  2130. SaveProject();
  2131. obs_scene_t *scene = obs_scene_from_source(source);
  2132. if (scene)
  2133. OBSProjector::UpdateMultiviewProjectors();
  2134. }
  2135. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  2136. {
  2137. SignalBlocker sourcesSignalBlocker(ui->sources);
  2138. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  2139. return;
  2140. ui->sources->SelectItem(item, select);
  2141. }
  2142. static inline bool SourceMixerHidden(obs_source_t *source)
  2143. {
  2144. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2145. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2146. obs_data_release(priv_settings);
  2147. return hidden;
  2148. }
  2149. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2150. {
  2151. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2152. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2153. obs_data_release(priv_settings);
  2154. }
  2155. void OBSBasic::GetAudioSourceFilters()
  2156. {
  2157. QAction *action = reinterpret_cast<QAction*>(sender());
  2158. VolControl *vol = action->property("volControl").value<VolControl*>();
  2159. obs_source_t *source = vol->GetSource();
  2160. CreateFiltersWindow(source);
  2161. }
  2162. void OBSBasic::GetAudioSourceProperties()
  2163. {
  2164. QAction *action = reinterpret_cast<QAction*>(sender());
  2165. VolControl *vol = action->property("volControl").value<VolControl*>();
  2166. obs_source_t *source = vol->GetSource();
  2167. CreatePropertiesWindow(source);
  2168. }
  2169. void OBSBasic::HideAudioControl()
  2170. {
  2171. QAction *action = reinterpret_cast<QAction*>(sender());
  2172. VolControl *vol = action->property("volControl").value<VolControl*>();
  2173. obs_source_t *source = vol->GetSource();
  2174. if (!SourceMixerHidden(source)) {
  2175. SetSourceMixerHidden(source, true);
  2176. DeactivateAudioSource(source);
  2177. }
  2178. }
  2179. void OBSBasic::UnhideAllAudioControls()
  2180. {
  2181. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  2182. {
  2183. if (!obs_source_active(source))
  2184. return true;
  2185. if (!SourceMixerHidden(source))
  2186. return true;
  2187. SetSourceMixerHidden(source, false);
  2188. ActivateAudioSource(source);
  2189. return true;
  2190. };
  2191. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2192. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  2193. {
  2194. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2195. };
  2196. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2197. }
  2198. void OBSBasic::ToggleHideMixer()
  2199. {
  2200. OBSSceneItem item = GetCurrentSceneItem();
  2201. OBSSource source = obs_sceneitem_get_source(item);
  2202. if (!SourceMixerHidden(source)) {
  2203. SetSourceMixerHidden(source, true);
  2204. DeactivateAudioSource(source);
  2205. } else {
  2206. SetSourceMixerHidden(source, false);
  2207. ActivateAudioSource(source);
  2208. }
  2209. }
  2210. void OBSBasic::MixerRenameSource()
  2211. {
  2212. QAction *action = reinterpret_cast<QAction*>(sender());
  2213. VolControl *vol = action->property("volControl").value<VolControl*>();
  2214. OBSSource source = vol->GetSource();
  2215. const char *prevName = obs_source_get_name(source);
  2216. for (;;) {
  2217. string name;
  2218. bool accepted = NameDialog::AskForName(this,
  2219. QTStr("Basic.Main.MixerRename.Title"),
  2220. QTStr("Basic.Main.MixerRename.Text"),
  2221. name,
  2222. QT_UTF8(prevName));
  2223. if (!accepted)
  2224. return;
  2225. if (name.empty()) {
  2226. OBSMessageBox::information(this,
  2227. QTStr("NoNameEntered.Title"),
  2228. QTStr("NoNameEntered.Text"));
  2229. continue;
  2230. }
  2231. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2232. obs_source_release(sourceTest);
  2233. if (sourceTest) {
  2234. OBSMessageBox::information(this,
  2235. QTStr("NameExists.Title"),
  2236. QTStr("NameExists.Text"));
  2237. continue;
  2238. }
  2239. obs_source_set_name(source, name.c_str());
  2240. break;
  2241. }
  2242. }
  2243. void OBSBasic::VolControlContextMenu()
  2244. {
  2245. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  2246. /* ------------------- */
  2247. QAction hideAction(QTStr("Hide"), this);
  2248. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2249. QAction mixerRenameAction(QTStr("Rename"), this);
  2250. QAction filtersAction(QTStr("Filters"), this);
  2251. QAction propertiesAction(QTStr("Properties"), this);
  2252. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2253. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2254. toggleControlLayoutAction.setCheckable(true);
  2255. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2256. "BasicWindow", "VerticalVolControl"));
  2257. /* ------------------- */
  2258. connect(&hideAction, &QAction::triggered,
  2259. this, &OBSBasic::HideAudioControl,
  2260. Qt::DirectConnection);
  2261. connect(&unhideAllAction, &QAction::triggered,
  2262. this, &OBSBasic::UnhideAllAudioControls,
  2263. Qt::DirectConnection);
  2264. connect(&mixerRenameAction, &QAction::triggered,
  2265. this, &OBSBasic::MixerRenameSource,
  2266. Qt::DirectConnection);
  2267. connect(&filtersAction, &QAction::triggered,
  2268. this, &OBSBasic::GetAudioSourceFilters,
  2269. Qt::DirectConnection);
  2270. connect(&propertiesAction, &QAction::triggered,
  2271. this, &OBSBasic::GetAudioSourceProperties,
  2272. Qt::DirectConnection);
  2273. connect(&advPropAction, &QAction::triggered,
  2274. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2275. Qt::DirectConnection);
  2276. /* ------------------- */
  2277. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2278. &OBSBasic::ToggleVolControlLayout,
  2279. Qt::DirectConnection);
  2280. /* ------------------- */
  2281. hideAction.setProperty("volControl",
  2282. QVariant::fromValue<VolControl*>(vol));
  2283. mixerRenameAction.setProperty("volControl",
  2284. QVariant::fromValue<VolControl*>(vol));
  2285. filtersAction.setProperty("volControl",
  2286. QVariant::fromValue<VolControl*>(vol));
  2287. propertiesAction.setProperty("volControl",
  2288. QVariant::fromValue<VolControl*>(vol));
  2289. /* ------------------- */
  2290. QMenu popup;
  2291. popup.addAction(&unhideAllAction);
  2292. popup.addAction(&hideAction);
  2293. popup.addAction(&mixerRenameAction);
  2294. popup.addSeparator();
  2295. popup.addAction(&toggleControlLayoutAction);
  2296. popup.addSeparator();
  2297. popup.addAction(&filtersAction);
  2298. popup.addAction(&propertiesAction);
  2299. popup.addAction(&advPropAction);
  2300. popup.exec(QCursor::pos());
  2301. }
  2302. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2303. {
  2304. StackedMixerAreaContextMenuRequested();
  2305. }
  2306. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2307. {
  2308. StackedMixerAreaContextMenuRequested();
  2309. }
  2310. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2311. {
  2312. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2313. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2314. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2315. toggleControlLayoutAction.setCheckable(true);
  2316. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2317. "BasicWindow", "VerticalVolControl"));
  2318. /* ------------------- */
  2319. connect(&unhideAllAction, &QAction::triggered,
  2320. this, &OBSBasic::UnhideAllAudioControls,
  2321. Qt::DirectConnection);
  2322. connect(&advPropAction, &QAction::triggered,
  2323. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2324. Qt::DirectConnection);
  2325. /* ------------------- */
  2326. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2327. &OBSBasic::ToggleVolControlLayout,
  2328. Qt::DirectConnection);
  2329. /* ------------------- */
  2330. QMenu popup;
  2331. popup.addAction(&unhideAllAction);
  2332. popup.addSeparator();
  2333. popup.addAction(&toggleControlLayoutAction);
  2334. popup.addSeparator();
  2335. popup.addAction(&advPropAction);
  2336. popup.exec(QCursor::pos());
  2337. }
  2338. void OBSBasic::ToggleMixerLayout(bool vertical)
  2339. {
  2340. if (vertical) {
  2341. ui->stackedMixerArea->setMinimumSize(180, 220);
  2342. ui->stackedMixerArea->setCurrentIndex(1);
  2343. } else {
  2344. ui->stackedMixerArea->setMinimumSize(220, 0);
  2345. ui->stackedMixerArea->setCurrentIndex(0);
  2346. }
  2347. }
  2348. void OBSBasic::ToggleVolControlLayout()
  2349. {
  2350. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2351. "VerticalVolControl");
  2352. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2353. vertical);
  2354. ToggleMixerLayout(vertical);
  2355. // We need to store it so we can delete current and then add
  2356. // at the right order
  2357. vector<OBSSource> sources;
  2358. for (size_t i = 0; i != volumes.size(); i++)
  2359. sources.emplace_back(volumes[i]->GetSource());
  2360. ClearVolumeControls();
  2361. for (const auto &source : sources)
  2362. ActivateAudioSource(source);
  2363. }
  2364. void OBSBasic::ActivateAudioSource(OBSSource source)
  2365. {
  2366. if (SourceMixerHidden(source))
  2367. return;
  2368. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2369. "VerticalVolControl");
  2370. VolControl *vol = new VolControl(source, true, vertical);
  2371. double meterDecayRate = config_get_double(basicConfig, "Audio",
  2372. "MeterDecayRate");
  2373. vol->SetMeterDecayRate(meterDecayRate);
  2374. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  2375. "PeakMeterType");
  2376. enum obs_peak_meter_type peakMeterType;
  2377. switch (peakMeterTypeIdx) {
  2378. case 0:
  2379. peakMeterType = SAMPLE_PEAK_METER;
  2380. break;
  2381. case 1:
  2382. peakMeterType = TRUE_PEAK_METER;
  2383. break;
  2384. default:
  2385. peakMeterType = SAMPLE_PEAK_METER;
  2386. break;
  2387. }
  2388. vol->setPeakMeterType(peakMeterType);
  2389. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2390. connect(vol, &QWidget::customContextMenuRequested,
  2391. this, &OBSBasic::VolControlContextMenu);
  2392. connect(vol, &VolControl::ConfigClicked,
  2393. this, &OBSBasic::VolControlContextMenu);
  2394. InsertQObjectByName(volumes, vol);
  2395. for (auto volume : volumes) {
  2396. if (vertical)
  2397. ui->vVolControlLayout->addWidget(volume);
  2398. else
  2399. ui->hVolControlLayout->addWidget(volume);
  2400. }
  2401. }
  2402. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2403. {
  2404. for (size_t i = 0; i < volumes.size(); i++) {
  2405. if (volumes[i]->GetSource() == source) {
  2406. delete volumes[i];
  2407. volumes.erase(volumes.begin() + i);
  2408. break;
  2409. }
  2410. }
  2411. }
  2412. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2413. {
  2414. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2415. !obs_source_is_group(source)) {
  2416. int count = ui->scenes->count();
  2417. if (count == 1) {
  2418. OBSMessageBox::information(this,
  2419. QTStr("FinalScene.Title"),
  2420. QTStr("FinalScene.Text"));
  2421. return false;
  2422. }
  2423. }
  2424. const char *name = obs_source_get_name(source);
  2425. QString text = QTStr("ConfirmRemove.Text");
  2426. text.replace("$1", QT_UTF8(name));
  2427. QMessageBox remove_source(this);
  2428. remove_source.setText(text);
  2429. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  2430. QMessageBox::YesRole);
  2431. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2432. remove_source.setIcon(QMessageBox::Question);
  2433. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2434. remove_source.exec();
  2435. return Yes == remove_source.clickedButton();
  2436. }
  2437. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  2438. #ifdef UPDATE_SPARKLE
  2439. void init_sparkle_updater(bool update_to_undeployed);
  2440. void trigger_sparkle_update();
  2441. #endif
  2442. void OBSBasic::TimedCheckForUpdates()
  2443. {
  2444. if (!config_get_bool(App()->GlobalConfig(), "General",
  2445. "EnableAutoUpdates"))
  2446. return;
  2447. #ifdef UPDATE_SPARKLE
  2448. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2449. "UpdateToUndeployed"));
  2450. #elif _WIN32
  2451. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2452. "LastUpdateCheck");
  2453. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  2454. "LastVersion");
  2455. if (lastVersion < LIBOBS_API_VER) {
  2456. lastUpdate = 0;
  2457. config_set_int(App()->GlobalConfig(), "General",
  2458. "LastUpdateCheck", 0);
  2459. }
  2460. long long t = (long long)time(nullptr);
  2461. long long secs = t - lastUpdate;
  2462. if (secs > UPDATE_CHECK_INTERVAL)
  2463. CheckForUpdates(false);
  2464. #endif
  2465. }
  2466. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2467. {
  2468. #ifdef UPDATE_SPARKLE
  2469. trigger_sparkle_update();
  2470. #elif _WIN32
  2471. ui->actionCheckForUpdates->setEnabled(false);
  2472. if (updateCheckThread && updateCheckThread->isRunning())
  2473. return;
  2474. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2475. updateCheckThread->start();
  2476. #endif
  2477. UNUSED_PARAMETER(manualUpdate);
  2478. }
  2479. void OBSBasic::updateCheckFinished()
  2480. {
  2481. ui->actionCheckForUpdates->setEnabled(true);
  2482. }
  2483. void OBSBasic::DuplicateSelectedScene()
  2484. {
  2485. OBSScene curScene = GetCurrentScene();
  2486. if (!curScene)
  2487. return;
  2488. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2489. QString format{obs_source_get_name(curSceneSource)};
  2490. format += " %1";
  2491. int i = 2;
  2492. QString placeHolderText = format.arg(i);
  2493. obs_source_t *source = nullptr;
  2494. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2495. obs_source_release(source);
  2496. placeHolderText = format.arg(++i);
  2497. }
  2498. for (;;) {
  2499. string name;
  2500. bool accepted = NameDialog::AskForName(this,
  2501. QTStr("Basic.Main.AddSceneDlg.Title"),
  2502. QTStr("Basic.Main.AddSceneDlg.Text"),
  2503. name,
  2504. placeHolderText);
  2505. if (!accepted)
  2506. return;
  2507. if (name.empty()) {
  2508. OBSMessageBox::information(this,
  2509. QTStr("NoNameEntered.Title"),
  2510. QTStr("NoNameEntered.Text"));
  2511. continue;
  2512. }
  2513. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2514. if (source) {
  2515. OBSMessageBox::information(this,
  2516. QTStr("NameExists.Title"),
  2517. QTStr("NameExists.Text"));
  2518. obs_source_release(source);
  2519. continue;
  2520. }
  2521. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2522. name.c_str(), OBS_SCENE_DUP_REFS);
  2523. source = obs_scene_get_source(scene);
  2524. SetCurrentScene(source, true);
  2525. obs_scene_release(scene);
  2526. break;
  2527. }
  2528. }
  2529. void OBSBasic::RemoveSelectedScene()
  2530. {
  2531. OBSScene scene = GetCurrentScene();
  2532. if (scene) {
  2533. obs_source_t *source = obs_scene_get_source(scene);
  2534. if (QueryRemoveSource(source)) {
  2535. obs_source_remove(source);
  2536. if (api)
  2537. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2538. }
  2539. }
  2540. }
  2541. void OBSBasic::RemoveSelectedSceneItem()
  2542. {
  2543. OBSSceneItem item = GetCurrentSceneItem();
  2544. if (item) {
  2545. obs_source_t *source = obs_sceneitem_get_source(item);
  2546. if (QueryRemoveSource(source))
  2547. obs_sceneitem_remove(item);
  2548. }
  2549. }
  2550. void OBSBasic::ReorderSources(OBSScene scene)
  2551. {
  2552. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2553. return;
  2554. ui->sources->ReorderItems();
  2555. SaveProject();
  2556. }
  2557. /* OBS Callbacks */
  2558. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2559. {
  2560. OBSBasic *window = static_cast<OBSBasic*>(data);
  2561. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2562. QMetaObject::invokeMethod(window, "ReorderSources",
  2563. Q_ARG(OBSScene, OBSScene(scene)));
  2564. }
  2565. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2566. {
  2567. OBSBasic *window = static_cast<OBSBasic*>(data);
  2568. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2569. QMetaObject::invokeMethod(window, "AddSceneItem",
  2570. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2571. }
  2572. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2573. {
  2574. OBSBasic *window = static_cast<OBSBasic*>(data);
  2575. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2576. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2577. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2578. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2579. Q_ARG(bool, true));
  2580. }
  2581. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2582. {
  2583. OBSBasic *window = static_cast<OBSBasic*>(data);
  2584. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2585. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2586. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2587. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2588. Q_ARG(bool, false));
  2589. }
  2590. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2591. {
  2592. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2593. if (obs_scene_from_source(source) != NULL)
  2594. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2595. "AddScene", WaitConnection(),
  2596. Q_ARG(OBSSource, OBSSource(source)));
  2597. }
  2598. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2599. {
  2600. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2601. if (obs_scene_from_source(source) != NULL)
  2602. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2603. "RemoveScene",
  2604. Q_ARG(OBSSource, OBSSource(source)));
  2605. }
  2606. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2607. {
  2608. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2609. uint32_t flags = obs_source_get_output_flags(source);
  2610. if (flags & OBS_SOURCE_AUDIO)
  2611. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2612. "ActivateAudioSource",
  2613. Q_ARG(OBSSource, OBSSource(source)));
  2614. }
  2615. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2616. {
  2617. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2618. uint32_t flags = obs_source_get_output_flags(source);
  2619. if (flags & OBS_SOURCE_AUDIO)
  2620. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2621. "DeactivateAudioSource",
  2622. Q_ARG(OBSSource, OBSSource(source)));
  2623. }
  2624. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2625. {
  2626. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2627. const char *newName = calldata_string(params, "new_name");
  2628. const char *prevName = calldata_string(params, "prev_name");
  2629. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2630. "RenameSources",
  2631. Q_ARG(OBSSource, source),
  2632. Q_ARG(QString, QT_UTF8(newName)),
  2633. Q_ARG(QString, QT_UTF8(prevName)));
  2634. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2635. }
  2636. void OBSBasic::DrawBackdrop(float cx, float cy)
  2637. {
  2638. if (!box)
  2639. return;
  2640. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2641. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2642. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2643. vec4 colorVal;
  2644. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2645. gs_effect_set_vec4(color, &colorVal);
  2646. gs_technique_begin(tech);
  2647. gs_technique_begin_pass(tech, 0);
  2648. gs_matrix_push();
  2649. gs_matrix_identity();
  2650. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2651. gs_load_vertexbuffer(box);
  2652. gs_draw(GS_TRISTRIP, 0, 0);
  2653. gs_matrix_pop();
  2654. gs_technique_end_pass(tech);
  2655. gs_technique_end(tech);
  2656. gs_load_vertexbuffer(nullptr);
  2657. }
  2658. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2659. {
  2660. OBSBasic *window = static_cast<OBSBasic*>(data);
  2661. obs_video_info ovi;
  2662. obs_get_video_info(&ovi);
  2663. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2664. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2665. gs_viewport_push();
  2666. gs_projection_push();
  2667. QSize previewSize = GetPixelSize(window->ui->preview);
  2668. float right = float(previewSize.width()) - window->previewX;
  2669. float bottom = float(previewSize.height()) - window->previewY;
  2670. gs_ortho(-window->previewX, right,
  2671. -window->previewY, bottom,
  2672. -100.0f, 100.0f);
  2673. window->ui->preview->DrawOverflow();
  2674. /* --------------------------------------- */
  2675. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2676. -100.0f, 100.0f);
  2677. gs_set_viewport(window->previewX, window->previewY,
  2678. window->previewCX, window->previewCY);
  2679. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2680. if (window->IsPreviewProgramMode()) {
  2681. OBSScene scene = window->GetCurrentScene();
  2682. obs_source_t *source = obs_scene_get_source(scene);
  2683. if (source)
  2684. obs_source_video_render(source);
  2685. } else {
  2686. obs_render_main_texture();
  2687. }
  2688. gs_load_vertexbuffer(nullptr);
  2689. /* --------------------------------------- */
  2690. gs_ortho(-window->previewX, right,
  2691. -window->previewY, bottom,
  2692. -100.0f, 100.0f);
  2693. gs_reset_viewport();
  2694. window->ui->preview->DrawSceneEditing();
  2695. /* --------------------------------------- */
  2696. gs_projection_pop();
  2697. gs_viewport_pop();
  2698. UNUSED_PARAMETER(cx);
  2699. UNUSED_PARAMETER(cy);
  2700. }
  2701. /* Main class functions */
  2702. obs_service_t *OBSBasic::GetService()
  2703. {
  2704. if (!service) {
  2705. service = obs_service_create("rtmp_common", NULL, NULL,
  2706. nullptr);
  2707. obs_service_release(service);
  2708. }
  2709. return service;
  2710. }
  2711. void OBSBasic::SetService(obs_service_t *newService)
  2712. {
  2713. if (newService)
  2714. service = newService;
  2715. }
  2716. bool OBSBasic::StreamingActive() const
  2717. {
  2718. if (!outputHandler)
  2719. return false;
  2720. return outputHandler->StreamingActive();
  2721. }
  2722. bool OBSBasic::Active() const
  2723. {
  2724. if (!outputHandler)
  2725. return false;
  2726. return outputHandler->Active();
  2727. }
  2728. #ifdef _WIN32
  2729. #define IS_WIN32 1
  2730. #else
  2731. #define IS_WIN32 0
  2732. #endif
  2733. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2734. {
  2735. return obs_reset_video(ovi);
  2736. }
  2737. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2738. {
  2739. const char *scaleTypeStr = config_get_string(basicConfig,
  2740. "Video", "ScaleType");
  2741. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2742. return OBS_SCALE_BILINEAR;
  2743. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2744. return OBS_SCALE_LANCZOS;
  2745. else
  2746. return OBS_SCALE_BICUBIC;
  2747. }
  2748. static inline enum video_format GetVideoFormatFromName(const char *name)
  2749. {
  2750. if (astrcmpi(name, "I420") == 0)
  2751. return VIDEO_FORMAT_I420;
  2752. else if (astrcmpi(name, "NV12") == 0)
  2753. return VIDEO_FORMAT_NV12;
  2754. else if (astrcmpi(name, "I444") == 0)
  2755. return VIDEO_FORMAT_I444;
  2756. #if 0 //currently unsupported
  2757. else if (astrcmpi(name, "YVYU") == 0)
  2758. return VIDEO_FORMAT_YVYU;
  2759. else if (astrcmpi(name, "YUY2") == 0)
  2760. return VIDEO_FORMAT_YUY2;
  2761. else if (astrcmpi(name, "UYVY") == 0)
  2762. return VIDEO_FORMAT_UYVY;
  2763. #endif
  2764. else
  2765. return VIDEO_FORMAT_RGBA;
  2766. }
  2767. void OBSBasic::ResetUI()
  2768. {
  2769. bool studioPortraitLayout = config_get_bool(GetGlobalConfig(),
  2770. "BasicWindow", "StudioPortraitLayout");
  2771. if (studioPortraitLayout)
  2772. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2773. else
  2774. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2775. }
  2776. int OBSBasic::ResetVideo()
  2777. {
  2778. if (outputHandler && outputHandler->Active())
  2779. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2780. ProfileScope("OBSBasic::ResetVideo");
  2781. struct obs_video_info ovi;
  2782. int ret;
  2783. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2784. const char *colorFormat = config_get_string(basicConfig, "Video",
  2785. "ColorFormat");
  2786. const char *colorSpace = config_get_string(basicConfig, "Video",
  2787. "ColorSpace");
  2788. const char *colorRange = config_get_string(basicConfig, "Video",
  2789. "ColorRange");
  2790. ovi.graphics_module = App()->GetRenderModule();
  2791. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2792. "Video", "BaseCX");
  2793. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2794. "Video", "BaseCY");
  2795. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2796. "Video", "OutputCX");
  2797. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2798. "Video", "OutputCY");
  2799. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2800. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2801. VIDEO_CS_601 : VIDEO_CS_709;
  2802. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2803. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2804. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2805. "Video", "AdapterIdx");
  2806. ovi.gpu_conversion = true;
  2807. ovi.scale_type = GetScaleType(basicConfig);
  2808. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2809. ovi.base_width = 1920;
  2810. ovi.base_height = 1080;
  2811. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2812. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2813. }
  2814. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2815. ovi.output_width = ovi.base_width;
  2816. ovi.output_height = ovi.base_height;
  2817. config_set_uint(basicConfig, "Video", "OutputCX",
  2818. ovi.base_width);
  2819. config_set_uint(basicConfig, "Video", "OutputCY",
  2820. ovi.base_height);
  2821. }
  2822. ret = AttemptToResetVideo(&ovi);
  2823. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2824. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2825. blog(LOG_WARNING, "Tried to reset when "
  2826. "already active");
  2827. return ret;
  2828. }
  2829. /* Try OpenGL if DirectX fails on windows */
  2830. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2831. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2832. "with graphics_module='%s', retrying "
  2833. "with graphics_module='%s'",
  2834. ret, ovi.graphics_module,
  2835. DL_OPENGL);
  2836. ovi.graphics_module = DL_OPENGL;
  2837. ret = AttemptToResetVideo(&ovi);
  2838. }
  2839. } else if (ret == OBS_VIDEO_SUCCESS) {
  2840. ResizePreview(ovi.base_width, ovi.base_height);
  2841. if (program)
  2842. ResizeProgram(ovi.base_width, ovi.base_height);
  2843. }
  2844. if (ret == OBS_VIDEO_SUCCESS) {
  2845. OBSBasicStats::InitializeValues();
  2846. OBSProjector::UpdateMultiviewProjectors();
  2847. }
  2848. return ret;
  2849. }
  2850. bool OBSBasic::ResetAudio()
  2851. {
  2852. ProfileScope("OBSBasic::ResetAudio");
  2853. struct obs_audio_info ai;
  2854. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2855. "SampleRate");
  2856. const char *channelSetupStr = config_get_string(basicConfig,
  2857. "Audio", "ChannelSetup");
  2858. if (strcmp(channelSetupStr, "Mono") == 0)
  2859. ai.speakers = SPEAKERS_MONO;
  2860. else if (strcmp(channelSetupStr, "2.1") == 0)
  2861. ai.speakers = SPEAKERS_2POINT1;
  2862. else if (strcmp(channelSetupStr, "4.0") == 0)
  2863. ai.speakers = SPEAKERS_4POINT0;
  2864. else if (strcmp(channelSetupStr, "4.1") == 0)
  2865. ai.speakers = SPEAKERS_4POINT1;
  2866. else if (strcmp(channelSetupStr, "5.1") == 0)
  2867. ai.speakers = SPEAKERS_5POINT1;
  2868. else if (strcmp(channelSetupStr, "7.1") == 0)
  2869. ai.speakers = SPEAKERS_7POINT1;
  2870. else
  2871. ai.speakers = SPEAKERS_STEREO;
  2872. return obs_reset_audio(&ai);
  2873. }
  2874. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2875. const char *deviceDesc, int channel)
  2876. {
  2877. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2878. obs_source_t *source;
  2879. obs_data_t *settings;
  2880. source = obs_get_output_source(channel);
  2881. if (source) {
  2882. if (disable) {
  2883. obs_set_output_source(channel, nullptr);
  2884. } else {
  2885. settings = obs_source_get_settings(source);
  2886. const char *oldId = obs_data_get_string(settings,
  2887. "device_id");
  2888. if (strcmp(oldId, deviceId) != 0) {
  2889. obs_data_set_string(settings, "device_id",
  2890. deviceId);
  2891. obs_source_update(source, settings);
  2892. }
  2893. obs_data_release(settings);
  2894. }
  2895. obs_source_release(source);
  2896. } else if (!disable) {
  2897. settings = obs_data_create();
  2898. obs_data_set_string(settings, "device_id", deviceId);
  2899. source = obs_source_create(sourceId, deviceDesc, settings,
  2900. nullptr);
  2901. obs_data_release(settings);
  2902. obs_set_output_source(channel, source);
  2903. obs_source_release(source);
  2904. }
  2905. }
  2906. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2907. {
  2908. QSize targetSize;
  2909. bool isFixedScaling;
  2910. obs_video_info ovi;
  2911. /* resize preview panel to fix to the top section of the window */
  2912. targetSize = GetPixelSize(ui->preview);
  2913. isFixedScaling = ui->preview->IsFixedScaling();
  2914. obs_get_video_info(&ovi);
  2915. if (isFixedScaling) {
  2916. previewScale = ui->preview->GetScalingAmount();
  2917. GetCenterPosFromFixedScale(int(cx), int(cy),
  2918. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2919. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2920. previewX, previewY, previewScale);
  2921. previewX += ui->preview->GetScrollX();
  2922. previewY += ui->preview->GetScrollY();
  2923. } else {
  2924. GetScaleAndCenterPos(int(cx), int(cy),
  2925. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2926. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2927. previewX, previewY, previewScale);
  2928. }
  2929. previewX += float(PREVIEW_EDGE_SIZE);
  2930. previewY += float(PREVIEW_EDGE_SIZE);
  2931. }
  2932. void OBSBasic::CloseDialogs()
  2933. {
  2934. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2935. if (!childDialogs.isEmpty()) {
  2936. for (int i = 0; i < childDialogs.size(); ++i) {
  2937. childDialogs.at(i)->close();
  2938. }
  2939. }
  2940. for (QPointer<QWidget> &projector : windowProjectors) {
  2941. delete projector;
  2942. projector.clear();
  2943. }
  2944. for (QPointer<QWidget> &projector : projectors) {
  2945. delete projector;
  2946. projector.clear();
  2947. }
  2948. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2949. if (!remux.isNull()) remux->close();
  2950. }
  2951. void OBSBasic::EnumDialogs()
  2952. {
  2953. visDialogs.clear();
  2954. modalDialogs.clear();
  2955. visMsgBoxes.clear();
  2956. /* fill list of Visible dialogs and Modal dialogs */
  2957. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2958. for (QDialog *dialog : dialogs) {
  2959. if (dialog->isVisible())
  2960. visDialogs.append(dialog);
  2961. if (dialog->isModal())
  2962. modalDialogs.append(dialog);
  2963. }
  2964. /* fill list of Visible message boxes */
  2965. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2966. for (QMessageBox *msgbox : msgBoxes) {
  2967. if (msgbox->isVisible())
  2968. visMsgBoxes.append(msgbox);
  2969. }
  2970. }
  2971. void OBSBasic::ClearSceneData()
  2972. {
  2973. disableSaving++;
  2974. CloseDialogs();
  2975. ClearVolumeControls();
  2976. ClearListItems(ui->scenes);
  2977. ui->sources->Clear();
  2978. ClearQuickTransitions();
  2979. ui->transitions->clear();
  2980. obs_set_output_source(0, nullptr);
  2981. obs_set_output_source(1, nullptr);
  2982. obs_set_output_source(2, nullptr);
  2983. obs_set_output_source(3, nullptr);
  2984. obs_set_output_source(4, nullptr);
  2985. obs_set_output_source(5, nullptr);
  2986. lastScene = nullptr;
  2987. swapScene = nullptr;
  2988. programScene = nullptr;
  2989. auto cb = [](void *unused, obs_source_t *source)
  2990. {
  2991. obs_source_remove(source);
  2992. UNUSED_PARAMETER(unused);
  2993. return true;
  2994. };
  2995. obs_enum_sources(cb, nullptr);
  2996. if (api)
  2997. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  2998. disableSaving--;
  2999. blog(LOG_INFO, "All scene data cleared");
  3000. blog(LOG_INFO, "------------------------------------------------");
  3001. }
  3002. void OBSBasic::closeEvent(QCloseEvent *event)
  3003. {
  3004. if (isVisible())
  3005. config_set_string(App()->GlobalConfig(),
  3006. "BasicWindow", "geometry",
  3007. saveGeometry().toBase64().constData());
  3008. if (outputHandler && outputHandler->Active()) {
  3009. SetShowing(true);
  3010. QMessageBox::StandardButton button = OBSMessageBox::question(
  3011. this, QTStr("ConfirmExit.Title"),
  3012. QTStr("ConfirmExit.Text"));
  3013. if (button == QMessageBox::No) {
  3014. event->ignore();
  3015. return;
  3016. }
  3017. }
  3018. QWidget::closeEvent(event);
  3019. if (!event->isAccepted())
  3020. return;
  3021. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3022. if (introCheckThread)
  3023. introCheckThread->wait();
  3024. if (updateCheckThread)
  3025. updateCheckThread->wait();
  3026. if (logUploadThread)
  3027. logUploadThread->wait();
  3028. signalHandlers.clear();
  3029. Auth::Save();
  3030. SaveProjectNow();
  3031. auth.reset();
  3032. config_set_string(App()->GlobalConfig(),
  3033. "BasicWindow", "DockState",
  3034. saveState().toBase64().constData());
  3035. if (api)
  3036. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3037. disableSaving++;
  3038. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3039. * sources, etc) so that all references are released before shutdown */
  3040. ClearSceneData();
  3041. App()->quit();
  3042. }
  3043. void OBSBasic::changeEvent(QEvent *event)
  3044. {
  3045. if (event->type() == QEvent::WindowStateChange &&
  3046. isMinimized() &&
  3047. trayIcon &&
  3048. trayIcon->isVisible() &&
  3049. sysTrayMinimizeToTray()) {
  3050. ToggleShowHide();
  3051. }
  3052. }
  3053. void OBSBasic::on_actionShow_Recordings_triggered()
  3054. {
  3055. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3056. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3057. const char *adv_path = strcmp(type, "Standard") ?
  3058. config_get_string(basicConfig, "AdvOut", "FFFilePath") :
  3059. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3060. const char *path = strcmp(mode, "Advanced") ?
  3061. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3062. adv_path;
  3063. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3064. }
  3065. void OBSBasic::on_actionRemux_triggered()
  3066. {
  3067. if (!remux.isNull()) {
  3068. remux->show();
  3069. remux->raise();
  3070. return;
  3071. }
  3072. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3073. const char *path = strcmp(mode, "Advanced") ?
  3074. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3075. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3076. OBSRemux *remuxDlg;
  3077. remuxDlg = new OBSRemux(path, this);
  3078. remuxDlg->show();
  3079. remux = remuxDlg;
  3080. }
  3081. void OBSBasic::on_action_Settings_triggered()
  3082. {
  3083. OBSBasicSettings settings(this);
  3084. settings.exec();
  3085. SystemTray(false);
  3086. }
  3087. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3088. {
  3089. if (advAudioWindow != nullptr) {
  3090. advAudioWindow->raise();
  3091. return;
  3092. }
  3093. advAudioWindow = new OBSBasicAdvAudio(this);
  3094. advAudioWindow->show();
  3095. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3096. connect(advAudioWindow, SIGNAL(destroyed()),
  3097. this, SLOT(on_advAudioProps_destroyed()));
  3098. }
  3099. void OBSBasic::on_advAudioProps_clicked()
  3100. {
  3101. on_actionAdvAudioProperties_triggered();
  3102. }
  3103. void OBSBasic::on_advAudioProps_destroyed()
  3104. {
  3105. advAudioWindow = nullptr;
  3106. }
  3107. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3108. QListWidgetItem *prev)
  3109. {
  3110. obs_source_t *source = NULL;
  3111. if (sceneChanging)
  3112. return;
  3113. if (current) {
  3114. obs_scene_t *scene;
  3115. scene = GetOBSRef<OBSScene>(current);
  3116. source = obs_scene_get_source(scene);
  3117. }
  3118. SetCurrentScene(source);
  3119. if (api)
  3120. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3121. UNUSED_PARAMETER(prev);
  3122. }
  3123. void OBSBasic::EditSceneName()
  3124. {
  3125. QListWidgetItem *item = ui->scenes->currentItem();
  3126. Qt::ItemFlags flags = item->flags();
  3127. item->setFlags(flags | Qt::ItemIsEditable);
  3128. ui->scenes->editItem(item);
  3129. item->setFlags(flags);
  3130. }
  3131. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3132. const char *slot)
  3133. {
  3134. QAction *action;
  3135. QList<QScreen*> screens = QGuiApplication::screens();
  3136. for (int i = 0; i < screens.size(); i++) {
  3137. QRect screenGeometry = screens[i]->geometry();
  3138. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  3139. arg(QTStr("Display"),
  3140. QString::number(i + 1),
  3141. QString::number(screenGeometry.width()),
  3142. QString::number(screenGeometry.height()),
  3143. QString::number(screenGeometry.x()),
  3144. QString::number(screenGeometry.y()));
  3145. action = parent->addAction(str, target, slot);
  3146. action->setProperty("monitor", i);
  3147. }
  3148. }
  3149. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3150. {
  3151. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3152. QMenu popup(this);
  3153. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3154. popup.addAction(QTStr("Add"),
  3155. this, SLOT(on_actionAddScene_triggered()));
  3156. if (item) {
  3157. popup.addSeparator();
  3158. popup.addAction(QTStr("Duplicate"),
  3159. this, SLOT(DuplicateSelectedScene()));
  3160. popup.addAction(QTStr("Rename"),
  3161. this, SLOT(EditSceneName()));
  3162. popup.addAction(QTStr("Remove"),
  3163. this, SLOT(RemoveSelectedScene()));
  3164. popup.addSeparator();
  3165. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  3166. this, SLOT(on_actionSceneUp_triggered()));
  3167. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3168. this, SLOT(on_actionSceneDown_triggered()));
  3169. order.addSeparator();
  3170. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3171. this, SLOT(MoveSceneToTop()));
  3172. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3173. this, SLOT(MoveSceneToBottom()));
  3174. popup.addMenu(&order);
  3175. popup.addSeparator();
  3176. delete sceneProjectorMenu;
  3177. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3178. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3179. SLOT(OpenSceneProjector()));
  3180. popup.addMenu(sceneProjectorMenu);
  3181. QAction *sceneWindow = popup.addAction(
  3182. QTStr("SceneWindow"),
  3183. this, SLOT(OpenSceneWindow()));
  3184. popup.addAction(sceneWindow);
  3185. popup.addSeparator();
  3186. popup.addAction(QTStr("Filters"), this,
  3187. SLOT(OpenSceneFilters()));
  3188. popup.addSeparator();
  3189. delete perSceneTransitionMenu;
  3190. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3191. popup.addMenu(perSceneTransitionMenu);
  3192. /* ---------------------- */
  3193. QAction *multiviewAction = popup.addAction(
  3194. QTStr("ShowInMultiview"));
  3195. OBSSource source = GetCurrentSceneSource();
  3196. OBSData data = obs_source_get_private_settings(source);
  3197. obs_data_release(data);
  3198. obs_data_set_default_bool(data, "show_in_multiview",
  3199. true);
  3200. bool show = obs_data_get_bool(data, "show_in_multiview");
  3201. multiviewAction->setCheckable(true);
  3202. multiviewAction->setChecked(show);
  3203. auto showInMultiview = [] (OBSData data)
  3204. {
  3205. bool show = obs_data_get_bool(data,
  3206. "show_in_multiview");
  3207. obs_data_set_bool(data, "show_in_multiview",
  3208. !show);
  3209. OBSProjector::UpdateMultiviewProjectors();
  3210. };
  3211. connect(multiviewAction, &QAction::triggered,
  3212. std::bind(showInMultiview, data));
  3213. }
  3214. popup.exec(QCursor::pos());
  3215. }
  3216. void OBSBasic::on_actionAddScene_triggered()
  3217. {
  3218. string name;
  3219. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3220. int i = 2;
  3221. QString placeHolderText = format.arg(i);
  3222. obs_source_t *source = nullptr;
  3223. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3224. obs_source_release(source);
  3225. placeHolderText = format.arg(++i);
  3226. }
  3227. bool accepted = NameDialog::AskForName(this,
  3228. QTStr("Basic.Main.AddSceneDlg.Title"),
  3229. QTStr("Basic.Main.AddSceneDlg.Text"),
  3230. name,
  3231. placeHolderText);
  3232. if (accepted) {
  3233. if (name.empty()) {
  3234. OBSMessageBox::information(this,
  3235. QTStr("NoNameEntered.Title"),
  3236. QTStr("NoNameEntered.Text"));
  3237. on_actionAddScene_triggered();
  3238. return;
  3239. }
  3240. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3241. if (source) {
  3242. OBSMessageBox::information(this,
  3243. QTStr("NameExists.Title"),
  3244. QTStr("NameExists.Text"));
  3245. obs_source_release(source);
  3246. on_actionAddScene_triggered();
  3247. return;
  3248. }
  3249. obs_scene_t *scene = obs_scene_create(name.c_str());
  3250. source = obs_scene_get_source(scene);
  3251. SetCurrentScene(source);
  3252. obs_scene_release(scene);
  3253. }
  3254. }
  3255. void OBSBasic::on_actionRemoveScene_triggered()
  3256. {
  3257. OBSScene scene = GetCurrentScene();
  3258. obs_source_t *source = obs_scene_get_source(scene);
  3259. if (source && QueryRemoveSource(source))
  3260. obs_source_remove(source);
  3261. }
  3262. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3263. {
  3264. int idx = ui->scenes->currentRow();
  3265. if (idx == -1 || idx == invalidIdx)
  3266. return;
  3267. sceneChanging = true;
  3268. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3269. if (!relative)
  3270. idx = 0;
  3271. ui->scenes->insertItem(idx + offset, item);
  3272. ui->scenes->setCurrentRow(idx + offset);
  3273. item->setSelected(true);
  3274. sceneChanging = false;
  3275. OBSProjector::UpdateMultiviewProjectors();
  3276. }
  3277. void OBSBasic::on_actionSceneUp_triggered()
  3278. {
  3279. ChangeSceneIndex(true, -1, 0);
  3280. }
  3281. void OBSBasic::on_actionSceneDown_triggered()
  3282. {
  3283. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3284. }
  3285. void OBSBasic::MoveSceneToTop()
  3286. {
  3287. ChangeSceneIndex(false, 0, 0);
  3288. }
  3289. void OBSBasic::MoveSceneToBottom()
  3290. {
  3291. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3292. ui->scenes->count() - 1);
  3293. }
  3294. void OBSBasic::EditSceneItemName()
  3295. {
  3296. int idx = GetTopSelectedSourceItem();
  3297. ui->sources->Edit(idx);
  3298. }
  3299. void OBSBasic::SetDeinterlacingMode()
  3300. {
  3301. QAction *action = reinterpret_cast<QAction*>(sender());
  3302. obs_deinterlace_mode mode =
  3303. (obs_deinterlace_mode)action->property("mode").toInt();
  3304. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3305. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3306. obs_source_set_deinterlace_mode(source, mode);
  3307. }
  3308. void OBSBasic::SetDeinterlacingOrder()
  3309. {
  3310. QAction *action = reinterpret_cast<QAction*>(sender());
  3311. obs_deinterlace_field_order order =
  3312. (obs_deinterlace_field_order)action->property("order").toInt();
  3313. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3314. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3315. obs_source_set_deinterlace_field_order(source, order);
  3316. }
  3317. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3318. {
  3319. obs_deinterlace_mode deinterlaceMode =
  3320. obs_source_get_deinterlace_mode(source);
  3321. obs_deinterlace_field_order deinterlaceOrder =
  3322. obs_source_get_deinterlace_field_order(source);
  3323. QAction *action;
  3324. #define ADD_MODE(name, mode) \
  3325. action = menu->addAction(QTStr("" name), this, \
  3326. SLOT(SetDeinterlacingMode())); \
  3327. action->setProperty("mode", (int)mode); \
  3328. action->setCheckable(true); \
  3329. action->setChecked(deinterlaceMode == mode);
  3330. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3331. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3332. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3333. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3334. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3335. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3336. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3337. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3338. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3339. #undef ADD_MODE
  3340. menu->addSeparator();
  3341. #define ADD_ORDER(name, order) \
  3342. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3343. SLOT(SetDeinterlacingOrder())); \
  3344. action->setProperty("order", (int)order); \
  3345. action->setCheckable(true); \
  3346. action->setChecked(deinterlaceOrder == order);
  3347. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3348. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3349. #undef ADD_ORDER
  3350. return menu;
  3351. }
  3352. void OBSBasic::SetScaleFilter()
  3353. {
  3354. QAction *action = reinterpret_cast<QAction*>(sender());
  3355. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3356. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3357. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3358. }
  3359. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3360. {
  3361. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3362. QAction *action;
  3363. #define ADD_MODE(name, mode) \
  3364. action = menu->addAction(QTStr("" name), this, \
  3365. SLOT(SetScaleFilter())); \
  3366. action->setProperty("mode", (int)mode); \
  3367. action->setCheckable(true); \
  3368. action->setChecked(scaleFilter == mode);
  3369. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3370. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3371. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3372. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3373. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3374. #undef ADD_MODE
  3375. return menu;
  3376. }
  3377. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction,
  3378. ColorSelect *select, obs_sceneitem_t *item)
  3379. {
  3380. QAction *action;
  3381. menu->setStyleSheet(QString(
  3382. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" \
  3383. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" \
  3384. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" \
  3385. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" \
  3386. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" \
  3387. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" \
  3388. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" \
  3389. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3390. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3391. obs_data_release(privData);
  3392. obs_data_set_default_int(privData, "color-preset", 0);
  3393. int preset = obs_data_get_int(privData, "color-preset");
  3394. action = menu->addAction(QTStr("Clear"), this,
  3395. + SLOT(ColorChange()));
  3396. action->setCheckable(true);
  3397. action->setProperty("bgColor", 0);
  3398. action->setChecked(preset == 0);
  3399. action = menu->addAction(QTStr("CustomColor"), this,
  3400. + SLOT(ColorChange()));
  3401. action->setCheckable(true);
  3402. action->setProperty("bgColor", 1);
  3403. action->setChecked(preset == 1);
  3404. menu->addSeparator();
  3405. widgetAction->setDefaultWidget(select);
  3406. for (int i = 1; i < 9; i++) {
  3407. stringstream button;
  3408. button << "preset" << i;
  3409. QPushButton *colorButton = select->findChild<QPushButton *>(
  3410. button.str().c_str());
  3411. if (preset == i + 1)
  3412. colorButton->setStyleSheet("border: 2px solid black");
  3413. colorButton->setProperty("bgColor", i);
  3414. select->connect(colorButton, SIGNAL(released()), this,
  3415. SLOT(ColorChange()));
  3416. }
  3417. menu->addAction(widgetAction);
  3418. return menu;
  3419. }
  3420. ColorSelect::ColorSelect(QWidget *parent)
  3421. : QWidget(parent),
  3422. ui(new Ui::ColorSelect)
  3423. {
  3424. ui->setupUi(this);
  3425. }
  3426. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3427. {
  3428. QMenu popup(this);
  3429. delete previewProjectorSource;
  3430. delete sourceProjector;
  3431. delete scaleFilteringMenu;
  3432. delete colorMenu;
  3433. delete colorWidgetAction;
  3434. delete colorSelect;
  3435. delete deinterlaceMenu;
  3436. if (preview) {
  3437. QAction *action = popup.addAction(
  3438. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3439. this, SLOT(TogglePreview()));
  3440. action->setCheckable(true);
  3441. action->setChecked(
  3442. obs_display_enabled(ui->preview->GetDisplay()));
  3443. if (IsPreviewProgramMode())
  3444. action->setEnabled(false);
  3445. popup.addAction(ui->actionLockPreview);
  3446. popup.addMenu(ui->scalingMenu);
  3447. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3448. AddProjectorMenuMonitors(previewProjectorSource, this,
  3449. SLOT(OpenPreviewProjector()));
  3450. popup.addMenu(previewProjectorSource);
  3451. QAction *previewWindow = popup.addAction(
  3452. QTStr("PreviewWindow"),
  3453. this, SLOT(OpenPreviewWindow()));
  3454. popup.addAction(previewWindow);
  3455. popup.addSeparator();
  3456. }
  3457. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3458. if (addSourceMenu)
  3459. popup.addMenu(addSourceMenu);
  3460. ui->actionCopyFilters->setEnabled(false);
  3461. ui->actionCopySource->setEnabled(false);
  3462. if (ui->sources->MultipleBaseSelected()) {
  3463. popup.addSeparator();
  3464. popup.addAction(QTStr("Basic.Main.GroupItems"),
  3465. ui->sources, SLOT(GroupSelectedItems()));
  3466. } else if (ui->sources->GroupsSelected()) {
  3467. popup.addSeparator();
  3468. popup.addAction(QTStr("Basic.Main.Ungroup"),
  3469. ui->sources, SLOT(UngroupSelectedGroups()));
  3470. }
  3471. popup.addSeparator();
  3472. popup.addAction(ui->actionCopySource);
  3473. popup.addAction(ui->actionPasteRef);
  3474. popup.addAction(ui->actionPasteDup);
  3475. popup.addSeparator();
  3476. popup.addSeparator();
  3477. popup.addAction(ui->actionCopyFilters);
  3478. popup.addAction(ui->actionPasteFilters);
  3479. popup.addSeparator();
  3480. if (idx != -1) {
  3481. if (addSourceMenu)
  3482. popup.addSeparator();
  3483. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3484. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3485. uint32_t flags = obs_source_get_output_flags(source);
  3486. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3487. OBS_SOURCE_ASYNC_VIDEO;
  3488. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  3489. OBS_SOURCE_AUDIO;
  3490. QAction *action;
  3491. colorMenu = new QMenu(QTStr("ChangeBG"));
  3492. colorWidgetAction = new QWidgetAction(colorMenu);
  3493. colorSelect = new ColorSelect(colorMenu);
  3494. popup.addMenu(AddBackgroundColorMenu(colorMenu,
  3495. colorWidgetAction, colorSelect, sceneItem));
  3496. popup.addAction(QTStr("Rename"), this,
  3497. SLOT(EditSceneItemName()));
  3498. popup.addAction(QTStr("Remove"), this,
  3499. SLOT(on_actionRemoveSource_triggered()));
  3500. popup.addSeparator();
  3501. popup.addMenu(ui->orderMenu);
  3502. popup.addMenu(ui->transformMenu);
  3503. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3504. AddProjectorMenuMonitors(sourceProjector, this,
  3505. SLOT(OpenSourceProjector()));
  3506. QAction *sourceWindow = popup.addAction(
  3507. QTStr("SourceWindow"),
  3508. this, SLOT(OpenSourceWindow()));
  3509. popup.addAction(sourceWindow);
  3510. popup.addSeparator();
  3511. if (hasAudio) {
  3512. QAction *actionHideMixer = popup.addAction(
  3513. QTStr("HideMixer"),
  3514. this, SLOT(ToggleHideMixer()));
  3515. actionHideMixer->setCheckable(true);
  3516. actionHideMixer->setChecked(SourceMixerHidden(source));
  3517. }
  3518. if (isAsyncVideo) {
  3519. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3520. popup.addMenu(AddDeinterlacingMenu(deinterlaceMenu, source));
  3521. popup.addSeparator();
  3522. }
  3523. QAction *resizeOutput = popup.addAction(
  3524. QTStr("ResizeOutputSizeOfSource"), this,
  3525. SLOT(ResizeOutputSizeOfSource()));
  3526. int width = obs_source_get_width(source);
  3527. int height = obs_source_get_height(source);
  3528. resizeOutput->setEnabled(!(ui->streamButton->isChecked() ||
  3529. ui->recordButton->isChecked() ||
  3530. (replayBufferButton &&
  3531. replayBufferButton->isChecked())));
  3532. if (width == 0 || height == 0)
  3533. resizeOutput->setEnabled(false);
  3534. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3535. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3536. popup.addSeparator();
  3537. popup.addMenu(sourceProjector);
  3538. popup.addAction(sourceWindow);
  3539. popup.addSeparator();
  3540. action = popup.addAction(QTStr("Interact"), this,
  3541. SLOT(on_actionInteract_triggered()));
  3542. action->setEnabled(obs_source_get_output_flags(source) &
  3543. OBS_SOURCE_INTERACTION);
  3544. popup.addAction(QTStr("Filters"), this,
  3545. SLOT(OpenFilters()));
  3546. popup.addAction(QTStr("Properties"), this,
  3547. SLOT(on_actionSourceProperties_triggered()));
  3548. ui->actionCopyFilters->setEnabled(true);
  3549. ui->actionCopySource->setEnabled(true);
  3550. } else {
  3551. ui->actionPasteFilters->setEnabled(false);
  3552. }
  3553. popup.exec(QCursor::pos());
  3554. }
  3555. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3556. {
  3557. if (ui->scenes->count()) {
  3558. QModelIndex idx = ui->sources->indexAt(pos);
  3559. CreateSourcePopupMenu(idx.row(), false);
  3560. }
  3561. }
  3562. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3563. {
  3564. if (!witem)
  3565. return;
  3566. if (IsPreviewProgramMode()) {
  3567. bool doubleClickSwitch = config_get_bool(App()->GlobalConfig(),
  3568. "BasicWindow", "TransitionOnDoubleClick");
  3569. if (doubleClickSwitch) {
  3570. OBSScene scene = GetCurrentScene();
  3571. if (scene)
  3572. SetCurrentScene(scene, false, true);
  3573. }
  3574. }
  3575. }
  3576. void OBSBasic::AddSource(const char *id)
  3577. {
  3578. if (id && *id) {
  3579. OBSBasicSourceSelect sourceSelect(this, id);
  3580. sourceSelect.exec();
  3581. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3582. CreatePropertiesWindow(sourceSelect.newSource);
  3583. }
  3584. }
  3585. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3586. {
  3587. const char *type;
  3588. bool foundValues = false;
  3589. bool foundDeprecated = false;
  3590. size_t idx = 0;
  3591. QMenu *popup = new QMenu(QTStr("Add"), this);
  3592. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3593. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3594. {
  3595. QList<QAction*> actions = menu->actions();
  3596. for (QAction *menuAction : actions) {
  3597. if (menuAction->text().compare(name) >= 0)
  3598. return menuAction;
  3599. }
  3600. return (QAction*)nullptr;
  3601. };
  3602. auto addSource = [this, getActionAfter] (QMenu *popup,
  3603. const char *type, const char *name)
  3604. {
  3605. QString qname = QT_UTF8(name);
  3606. QAction *popupItem = new QAction(qname, this);
  3607. popupItem->setData(QT_UTF8(type));
  3608. connect(popupItem, SIGNAL(triggered(bool)),
  3609. this, SLOT(AddSourceFromAction()));
  3610. QAction *after = getActionAfter(popup, qname);
  3611. popup->insertAction(after, popupItem);
  3612. };
  3613. while (obs_enum_input_types(idx++, &type)) {
  3614. const char *name = obs_source_get_display_name(type);
  3615. uint32_t caps = obs_get_source_output_flags(type);
  3616. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3617. continue;
  3618. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3619. addSource(popup, type, name);
  3620. } else {
  3621. addSource(deprecated, type, name);
  3622. foundDeprecated = true;
  3623. }
  3624. foundValues = true;
  3625. }
  3626. addSource(popup, "scene", Str("Basic.Scene"));
  3627. popup->addSeparator();
  3628. QAction *addGroup = new QAction(QTStr("Group"), this);
  3629. addGroup->setData(QT_UTF8("group"));
  3630. connect(addGroup, SIGNAL(triggered(bool)),
  3631. this, SLOT(AddSourceFromAction()));
  3632. popup->addAction(addGroup);
  3633. if (!foundDeprecated) {
  3634. delete deprecated;
  3635. deprecated = nullptr;
  3636. }
  3637. if (!foundValues) {
  3638. delete popup;
  3639. popup = nullptr;
  3640. } else if (foundDeprecated) {
  3641. popup->addSeparator();
  3642. popup->addMenu(deprecated);
  3643. }
  3644. return popup;
  3645. }
  3646. void OBSBasic::AddSourceFromAction()
  3647. {
  3648. QAction *action = qobject_cast<QAction*>(sender());
  3649. if (!action)
  3650. return;
  3651. AddSource(QT_TO_UTF8(action->data().toString()));
  3652. }
  3653. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3654. {
  3655. if (!GetCurrentScene()) {
  3656. // Tell the user he needs a scene first (help beginners).
  3657. OBSMessageBox::information(this,
  3658. QTStr("Basic.Main.AddSourceHelp.Title"),
  3659. QTStr("Basic.Main.AddSourceHelp.Text"));
  3660. return;
  3661. }
  3662. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3663. if (popup)
  3664. popup->exec(pos);
  3665. }
  3666. void OBSBasic::on_actionAddSource_triggered()
  3667. {
  3668. AddSourcePopupMenu(QCursor::pos());
  3669. }
  3670. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3671. {
  3672. vector<OBSSceneItem> &items =
  3673. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3674. if (obs_sceneitem_selected(item)) {
  3675. items.emplace_back(item);
  3676. } else if (obs_sceneitem_is_group(item)) {
  3677. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3678. }
  3679. return true;
  3680. };
  3681. void OBSBasic::on_actionRemoveSource_triggered()
  3682. {
  3683. vector<OBSSceneItem> items;
  3684. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3685. if (!items.size())
  3686. return;
  3687. auto removeMultiple = [this] (size_t count)
  3688. {
  3689. QString text = QTStr("ConfirmRemove.TextMultiple")
  3690. .arg(QString::number(count));
  3691. QMessageBox remove_items(this);
  3692. remove_items.setText(text);
  3693. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3694. QMessageBox::YesRole);
  3695. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3696. remove_items.setIcon(QMessageBox::Question);
  3697. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3698. remove_items.exec();
  3699. return Yes == remove_items.clickedButton();
  3700. };
  3701. if (items.size() == 1) {
  3702. OBSSceneItem &item = items[0];
  3703. obs_source_t *source = obs_sceneitem_get_source(item);
  3704. if (source && QueryRemoveSource(source))
  3705. obs_sceneitem_remove(item);
  3706. } else {
  3707. if (removeMultiple(items.size())) {
  3708. for (auto &item : items)
  3709. obs_sceneitem_remove(item);
  3710. }
  3711. }
  3712. }
  3713. void OBSBasic::on_actionInteract_triggered()
  3714. {
  3715. OBSSceneItem item = GetCurrentSceneItem();
  3716. OBSSource source = obs_sceneitem_get_source(item);
  3717. if (source)
  3718. CreateInteractionWindow(source);
  3719. }
  3720. void OBSBasic::on_actionSourceProperties_triggered()
  3721. {
  3722. OBSSceneItem item = GetCurrentSceneItem();
  3723. OBSSource source = obs_sceneitem_get_source(item);
  3724. if (source)
  3725. CreatePropertiesWindow(source);
  3726. }
  3727. void OBSBasic::on_actionSourceUp_triggered()
  3728. {
  3729. OBSSceneItem item = GetCurrentSceneItem();
  3730. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3731. }
  3732. void OBSBasic::on_actionSourceDown_triggered()
  3733. {
  3734. OBSSceneItem item = GetCurrentSceneItem();
  3735. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3736. }
  3737. void OBSBasic::on_actionMoveUp_triggered()
  3738. {
  3739. OBSSceneItem item = GetCurrentSceneItem();
  3740. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3741. }
  3742. void OBSBasic::on_actionMoveDown_triggered()
  3743. {
  3744. OBSSceneItem item = GetCurrentSceneItem();
  3745. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3746. }
  3747. void OBSBasic::on_actionMoveToTop_triggered()
  3748. {
  3749. OBSSceneItem item = GetCurrentSceneItem();
  3750. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3751. }
  3752. void OBSBasic::on_actionMoveToBottom_triggered()
  3753. {
  3754. OBSSceneItem item = GetCurrentSceneItem();
  3755. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3756. }
  3757. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3758. {
  3759. char logDir[512];
  3760. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3761. return nullptr;
  3762. string path = (char*)logDir;
  3763. path += "/";
  3764. path += log;
  3765. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3766. if (!file)
  3767. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3768. return file;
  3769. }
  3770. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3771. {
  3772. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3773. if (!fileString)
  3774. return;
  3775. if (!*fileString)
  3776. return;
  3777. ui->menuLogFiles->setEnabled(false);
  3778. stringstream ss;
  3779. ss << "OBS " << App()->GetVersionString()
  3780. << " log file uploaded at " << CurrentDateTimeString()
  3781. << "\n\n" << fileString;
  3782. if (logUploadThread) {
  3783. logUploadThread->wait();
  3784. }
  3785. RemoteTextThread *thread = new RemoteTextThread(
  3786. "https://obsproject.com/logs/upload",
  3787. "text/plain", ss.str().c_str());
  3788. logUploadThread.reset(thread);
  3789. connect(thread, &RemoteTextThread::Result,
  3790. this, &OBSBasic::logUploadFinished);
  3791. logUploadThread->start();
  3792. }
  3793. void OBSBasic::on_actionShowLogs_triggered()
  3794. {
  3795. char logDir[512];
  3796. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3797. return;
  3798. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3799. QDesktopServices::openUrl(url);
  3800. }
  3801. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3802. {
  3803. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3804. }
  3805. void OBSBasic::on_actionUploadLastLog_triggered()
  3806. {
  3807. UploadLog("obs-studio/logs", App()->GetLastLog());
  3808. }
  3809. void OBSBasic::on_actionViewCurrentLog_triggered()
  3810. {
  3811. char logDir[512];
  3812. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3813. return;
  3814. const char* log = App()->GetCurrentLog();
  3815. string path = (char*)logDir;
  3816. path += "/";
  3817. path += log;
  3818. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3819. QDesktopServices::openUrl(url);
  3820. }
  3821. void OBSBasic::on_actionShowCrashLogs_triggered()
  3822. {
  3823. char logDir[512];
  3824. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  3825. return;
  3826. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3827. QDesktopServices::openUrl(url);
  3828. }
  3829. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  3830. {
  3831. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  3832. }
  3833. void OBSBasic::on_actionCheckForUpdates_triggered()
  3834. {
  3835. CheckForUpdates(true);
  3836. }
  3837. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3838. {
  3839. ui->menuLogFiles->setEnabled(true);
  3840. if (text.isEmpty()) {
  3841. OBSMessageBox::information(this,
  3842. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3843. error);
  3844. return;
  3845. }
  3846. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3847. string resURL = obs_data_get_string(returnData, "url");
  3848. QString logURL = resURL.c_str();
  3849. obs_data_release(returnData);
  3850. OBSLogReply logDialog(this, logURL);
  3851. logDialog.exec();
  3852. }
  3853. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3854. obs_source_t *source, const string &name)
  3855. {
  3856. const char *prevName = obs_source_get_name(source);
  3857. if (name == prevName)
  3858. return;
  3859. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3860. QListWidgetItem *listItem = listWidget->currentItem();
  3861. if (foundSource || name.empty()) {
  3862. listItem->setText(QT_UTF8(prevName));
  3863. if (foundSource) {
  3864. OBSMessageBox::information(parent,
  3865. QTStr("NameExists.Title"),
  3866. QTStr("NameExists.Text"));
  3867. } else if (name.empty()) {
  3868. OBSMessageBox::information(parent,
  3869. QTStr("NoNameEntered.Title"),
  3870. QTStr("NoNameEntered.Text"));
  3871. }
  3872. obs_source_release(foundSource);
  3873. } else {
  3874. listItem->setText(QT_UTF8(name.c_str()));
  3875. obs_source_set_name(source, name.c_str());
  3876. }
  3877. }
  3878. void OBSBasic::SceneNameEdited(QWidget *editor,
  3879. QAbstractItemDelegate::EndEditHint endHint)
  3880. {
  3881. OBSScene scene = GetCurrentScene();
  3882. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3883. string text = QT_TO_UTF8(edit->text().trimmed());
  3884. if (!scene)
  3885. return;
  3886. obs_source_t *source = obs_scene_get_source(scene);
  3887. RenameListItem(this, ui->scenes, source, text);
  3888. if (api)
  3889. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3890. UNUSED_PARAMETER(endHint);
  3891. }
  3892. void OBSBasic::OpenFilters()
  3893. {
  3894. OBSSceneItem item = GetCurrentSceneItem();
  3895. OBSSource source = obs_sceneitem_get_source(item);
  3896. CreateFiltersWindow(source);
  3897. }
  3898. void OBSBasic::OpenSceneFilters()
  3899. {
  3900. OBSScene scene = GetCurrentScene();
  3901. OBSSource source = obs_scene_get_source(scene);
  3902. CreateFiltersWindow(source);
  3903. }
  3904. #define RECORDING_START \
  3905. "==== Recording Start ==============================================="
  3906. #define RECORDING_STOP \
  3907. "==== Recording Stop ================================================"
  3908. #define REPLAY_BUFFER_START \
  3909. "==== Replay Buffer Start ==========================================="
  3910. #define REPLAY_BUFFER_STOP \
  3911. "==== Replay Buffer Stop ============================================"
  3912. #define STREAMING_START \
  3913. "==== Streaming Start ==============================================="
  3914. #define STREAMING_STOP \
  3915. "==== Streaming Stop ================================================"
  3916. void OBSBasic::StartStreaming()
  3917. {
  3918. if (outputHandler->StreamingActive())
  3919. return;
  3920. if (disableOutputsRef)
  3921. return;
  3922. if (api)
  3923. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3924. SaveProject();
  3925. ui->streamButton->setEnabled(false);
  3926. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3927. if (sysTrayStream) {
  3928. sysTrayStream->setEnabled(false);
  3929. sysTrayStream->setText(ui->streamButton->text());
  3930. }
  3931. if (!outputHandler->StartStreaming(service)) {
  3932. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3933. ui->streamButton->setEnabled(true);
  3934. ui->streamButton->setChecked(false);
  3935. if (sysTrayStream) {
  3936. sysTrayStream->setText(ui->streamButton->text());
  3937. sysTrayStream->setEnabled(true);
  3938. }
  3939. QMessageBox::critical(this,
  3940. QTStr("Output.StartStreamFailed"),
  3941. QTStr("Output.StartFailedGeneric"));
  3942. return;
  3943. }
  3944. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3945. "BasicWindow", "RecordWhenStreaming");
  3946. if (recordWhenStreaming)
  3947. StartRecording();
  3948. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3949. "BasicWindow", "ReplayBufferWhileStreaming");
  3950. if (replayBufferWhileStreaming)
  3951. StartReplayBuffer();
  3952. }
  3953. #ifdef _WIN32
  3954. static inline void UpdateProcessPriority()
  3955. {
  3956. const char *priority = config_get_string(App()->GlobalConfig(),
  3957. "General", "ProcessPriority");
  3958. if (priority && strcmp(priority, "Normal") != 0)
  3959. SetProcessPriority(priority);
  3960. }
  3961. static inline void ClearProcessPriority()
  3962. {
  3963. const char *priority = config_get_string(App()->GlobalConfig(),
  3964. "General", "ProcessPriority");
  3965. if (priority && strcmp(priority, "Normal") != 0)
  3966. SetProcessPriority("Normal");
  3967. }
  3968. #else
  3969. #define UpdateProcessPriority() do {} while(false)
  3970. #define ClearProcessPriority() do {} while(false)
  3971. #endif
  3972. inline void OBSBasic::OnActivate()
  3973. {
  3974. if (ui->profileMenu->isEnabled()) {
  3975. ui->profileMenu->setEnabled(false);
  3976. ui->autoConfigure->setEnabled(false);
  3977. App()->IncrementSleepInhibition();
  3978. UpdateProcessPriority();
  3979. if (trayIcon)
  3980. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3981. }
  3982. }
  3983. inline void OBSBasic::OnDeactivate()
  3984. {
  3985. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3986. ui->profileMenu->setEnabled(true);
  3987. ui->autoConfigure->setEnabled(true);
  3988. App()->DecrementSleepInhibition();
  3989. ClearProcessPriority();
  3990. if (trayIcon)
  3991. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3992. }
  3993. }
  3994. void OBSBasic::StopStreaming()
  3995. {
  3996. SaveProject();
  3997. if (outputHandler->StreamingActive())
  3998. outputHandler->StopStreaming(streamingStopping);
  3999. OnDeactivate();
  4000. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4001. "BasicWindow", "RecordWhenStreaming");
  4002. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4003. "BasicWindow", "KeepRecordingWhenStreamStops");
  4004. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4005. StopRecording();
  4006. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4007. "BasicWindow", "ReplayBufferWhileStreaming");
  4008. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4009. "BasicWindow", "KeepReplayBufferStreamStops");
  4010. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4011. StopReplayBuffer();
  4012. }
  4013. void OBSBasic::ForceStopStreaming()
  4014. {
  4015. SaveProject();
  4016. if (outputHandler->StreamingActive())
  4017. outputHandler->StopStreaming(true);
  4018. OnDeactivate();
  4019. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4020. "BasicWindow", "RecordWhenStreaming");
  4021. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4022. "BasicWindow", "KeepRecordingWhenStreamStops");
  4023. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4024. StopRecording();
  4025. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4026. "BasicWindow", "ReplayBufferWhileStreaming");
  4027. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4028. "BasicWindow", "KeepReplayBufferStreamStops");
  4029. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4030. StopReplayBuffer();
  4031. }
  4032. void OBSBasic::StreamDelayStarting(int sec)
  4033. {
  4034. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4035. ui->streamButton->setEnabled(true);
  4036. ui->streamButton->setChecked(true);
  4037. if (sysTrayStream) {
  4038. sysTrayStream->setText(ui->streamButton->text());
  4039. sysTrayStream->setEnabled(true);
  4040. }
  4041. if (!startStreamMenu.isNull())
  4042. startStreamMenu->deleteLater();
  4043. startStreamMenu = new QMenu();
  4044. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  4045. this, SLOT(StopStreaming()));
  4046. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4047. this, SLOT(ForceStopStreaming()));
  4048. ui->streamButton->setMenu(startStreamMenu);
  4049. ui->statusbar->StreamDelayStarting(sec);
  4050. OnActivate();
  4051. }
  4052. void OBSBasic::StreamDelayStopping(int sec)
  4053. {
  4054. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4055. ui->streamButton->setEnabled(true);
  4056. ui->streamButton->setChecked(false);
  4057. if (sysTrayStream) {
  4058. sysTrayStream->setText(ui->streamButton->text());
  4059. sysTrayStream->setEnabled(true);
  4060. }
  4061. if (!startStreamMenu.isNull())
  4062. startStreamMenu->deleteLater();
  4063. startStreamMenu = new QMenu();
  4064. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  4065. this, SLOT(StartStreaming()));
  4066. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4067. this, SLOT(ForceStopStreaming()));
  4068. ui->streamButton->setMenu(startStreamMenu);
  4069. ui->statusbar->StreamDelayStopping(sec);
  4070. if (api)
  4071. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4072. }
  4073. void OBSBasic::StreamingStart()
  4074. {
  4075. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4076. ui->streamButton->setEnabled(true);
  4077. ui->streamButton->setChecked(true);
  4078. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4079. if (sysTrayStream) {
  4080. sysTrayStream->setText(ui->streamButton->text());
  4081. sysTrayStream->setEnabled(true);
  4082. }
  4083. if (api)
  4084. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4085. OnActivate();
  4086. blog(LOG_INFO, STREAMING_START);
  4087. }
  4088. void OBSBasic::StreamStopping()
  4089. {
  4090. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4091. if (sysTrayStream)
  4092. sysTrayStream->setText(ui->streamButton->text());
  4093. streamingStopping = true;
  4094. if (api)
  4095. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4096. }
  4097. void OBSBasic::StreamingStop(int code, QString last_error)
  4098. {
  4099. const char *errorDescription;
  4100. DStr errorMessage;
  4101. bool use_last_error = false;
  4102. switch (code) {
  4103. case OBS_OUTPUT_BAD_PATH:
  4104. errorDescription = Str("Output.ConnectFail.BadPath");
  4105. break;
  4106. case OBS_OUTPUT_CONNECT_FAILED:
  4107. use_last_error = true;
  4108. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4109. break;
  4110. case OBS_OUTPUT_INVALID_STREAM:
  4111. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4112. break;
  4113. default:
  4114. case OBS_OUTPUT_ERROR:
  4115. use_last_error = true;
  4116. errorDescription = Str("Output.ConnectFail.Error");
  4117. break;
  4118. case OBS_OUTPUT_DISCONNECTED:
  4119. /* doesn't happen if output is set to reconnect. note that
  4120. * reconnects are handled in the output, not in the UI */
  4121. use_last_error = true;
  4122. errorDescription = Str("Output.ConnectFail.Disconnected");
  4123. }
  4124. if (use_last_error && !last_error.isEmpty())
  4125. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4126. QT_TO_UTF8(last_error));
  4127. else
  4128. dstr_copy(errorMessage, errorDescription);
  4129. ui->statusbar->StreamStopped();
  4130. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4131. ui->streamButton->setEnabled(true);
  4132. ui->streamButton->setChecked(false);
  4133. if (sysTrayStream) {
  4134. sysTrayStream->setText(ui->streamButton->text());
  4135. sysTrayStream->setEnabled(true);
  4136. }
  4137. streamingStopping = false;
  4138. if (api)
  4139. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4140. OnDeactivate();
  4141. blog(LOG_INFO, STREAMING_STOP);
  4142. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4143. OBSMessageBox::information(this,
  4144. QTStr("Output.ConnectFail.Title"),
  4145. QT_UTF8(errorMessage));
  4146. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4147. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  4148. }
  4149. if (!startStreamMenu.isNull()) {
  4150. ui->streamButton->setMenu(nullptr);
  4151. startStreamMenu->deleteLater();
  4152. startStreamMenu = nullptr;
  4153. }
  4154. }
  4155. void OBSBasic::AutoRemux()
  4156. {
  4157. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4158. const char *path = strcmp(mode, "Advanced") != 0
  4159. ? config_get_string(basicConfig, "SimpleOutput", "FilePath")
  4160. : config_get_string(basicConfig, "AdvOut", "RecFilePath");
  4161. QString input;
  4162. input += path;
  4163. input += "/";
  4164. input += remuxFilename.c_str();
  4165. QFileInfo fi(remuxFilename.c_str());
  4166. QString output;
  4167. output += path;
  4168. output += "/";
  4169. output += fi.completeBaseName();
  4170. output += ".mp4";
  4171. OBSRemux *remux = new OBSRemux(path, this, true);
  4172. remux->show();
  4173. remux->AutoRemux(input, output);
  4174. }
  4175. void OBSBasic::StartRecording()
  4176. {
  4177. if (outputHandler->RecordingActive())
  4178. return;
  4179. if (disableOutputsRef)
  4180. return;
  4181. if (api)
  4182. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4183. SaveProject();
  4184. if (!outputHandler->StartRecording())
  4185. ui->recordButton->setChecked(false);
  4186. }
  4187. void OBSBasic::RecordStopping()
  4188. {
  4189. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4190. if (sysTrayRecord)
  4191. sysTrayRecord->setText(ui->recordButton->text());
  4192. recordingStopping = true;
  4193. if (api)
  4194. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4195. }
  4196. void OBSBasic::StopRecording()
  4197. {
  4198. SaveProject();
  4199. if (outputHandler->RecordingActive())
  4200. outputHandler->StopRecording(recordingStopping);
  4201. OnDeactivate();
  4202. }
  4203. void OBSBasic::RecordingStart()
  4204. {
  4205. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4206. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4207. ui->recordButton->setChecked(true);
  4208. if (sysTrayRecord)
  4209. sysTrayRecord->setText(ui->recordButton->text());
  4210. recordingStopping = false;
  4211. if (api)
  4212. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4213. OnActivate();
  4214. blog(LOG_INFO, RECORDING_START);
  4215. }
  4216. void OBSBasic::RecordingStop(int code)
  4217. {
  4218. ui->statusbar->RecordingStopped();
  4219. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4220. ui->recordButton->setChecked(false);
  4221. if (sysTrayRecord)
  4222. sysTrayRecord->setText(ui->recordButton->text());
  4223. blog(LOG_INFO, RECORDING_STOP);
  4224. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4225. OBSMessageBox::information(this,
  4226. QTStr("Output.RecordFail.Title"),
  4227. QTStr("Output.RecordFail.Unsupported"));
  4228. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4229. OBSMessageBox::information(this,
  4230. QTStr("Output.RecordNoSpace.Title"),
  4231. QTStr("Output.RecordNoSpace.Msg"));
  4232. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4233. OBSMessageBox::information(this,
  4234. QTStr("Output.RecordError.Title"),
  4235. QTStr("Output.RecordError.Msg"));
  4236. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4237. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4238. QSystemTrayIcon::Warning);
  4239. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4240. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4241. QSystemTrayIcon::Warning);
  4242. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4243. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4244. QSystemTrayIcon::Warning);
  4245. }
  4246. if (api)
  4247. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4248. if (remuxAfterRecord)
  4249. AutoRemux();
  4250. OnDeactivate();
  4251. }
  4252. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4253. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4254. void OBSBasic::StartReplayBuffer()
  4255. {
  4256. if (!outputHandler || !outputHandler->replayBuffer)
  4257. return;
  4258. if (outputHandler->ReplayBufferActive())
  4259. return;
  4260. if (disableOutputsRef)
  4261. return;
  4262. if (!NoSourcesConfirmation()) {
  4263. replayBufferButton->setChecked(false);
  4264. return;
  4265. }
  4266. obs_output_t *output = outputHandler->replayBuffer;
  4267. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4268. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  4269. "ReplayBuffer.Save");
  4270. size_t count = obs_data_array_count(bindings);
  4271. obs_data_array_release(bindings);
  4272. obs_data_release(hotkeys);
  4273. if (!count) {
  4274. OBSMessageBox::information(this,
  4275. RP_NO_HOTKEY_TITLE,
  4276. RP_NO_HOTKEY_TEXT);
  4277. return;
  4278. }
  4279. if (api)
  4280. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4281. SaveProject();
  4282. if (!outputHandler->StartReplayBuffer())
  4283. replayBufferButton->setChecked(false);
  4284. }
  4285. void OBSBasic::ReplayBufferStopping()
  4286. {
  4287. if (!outputHandler || !outputHandler->replayBuffer)
  4288. return;
  4289. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4290. if (sysTrayReplayBuffer)
  4291. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4292. replayBufferStopping = true;
  4293. if (api)
  4294. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4295. }
  4296. void OBSBasic::StopReplayBuffer()
  4297. {
  4298. if (!outputHandler || !outputHandler->replayBuffer)
  4299. return;
  4300. SaveProject();
  4301. if (outputHandler->ReplayBufferActive())
  4302. outputHandler->StopReplayBuffer(replayBufferStopping);
  4303. OnDeactivate();
  4304. }
  4305. void OBSBasic::ReplayBufferStart()
  4306. {
  4307. if (!outputHandler || !outputHandler->replayBuffer)
  4308. return;
  4309. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4310. if (sysTrayReplayBuffer)
  4311. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4312. replayBufferStopping = false;
  4313. if (api)
  4314. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4315. OnActivate();
  4316. blog(LOG_INFO, REPLAY_BUFFER_START);
  4317. }
  4318. void OBSBasic::ReplayBufferSave()
  4319. {
  4320. if (!outputHandler || !outputHandler->replayBuffer)
  4321. return;
  4322. if (!outputHandler->ReplayBufferActive())
  4323. return;
  4324. calldata_t cd = {0};
  4325. proc_handler_t *ph = obs_output_get_proc_handler(
  4326. outputHandler->replayBuffer);
  4327. proc_handler_call(ph, "save", &cd);
  4328. calldata_free(&cd);
  4329. }
  4330. void OBSBasic::ReplayBufferStop(int code)
  4331. {
  4332. if (!outputHandler || !outputHandler->replayBuffer)
  4333. return;
  4334. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4335. if (sysTrayReplayBuffer)
  4336. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4337. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4338. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4339. OBSMessageBox::information(this,
  4340. QTStr("Output.RecordFail.Title"),
  4341. QTStr("Output.RecordFail.Unsupported"));
  4342. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4343. OBSMessageBox::information(this,
  4344. QTStr("Output.RecordNoSpace.Title"),
  4345. QTStr("Output.RecordNoSpace.Msg"));
  4346. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4347. OBSMessageBox::information(this,
  4348. QTStr("Output.RecordError.Title"),
  4349. QTStr("Output.RecordError.Msg"));
  4350. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4351. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4352. QSystemTrayIcon::Warning);
  4353. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4354. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4355. QSystemTrayIcon::Warning);
  4356. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4357. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4358. QSystemTrayIcon::Warning);
  4359. }
  4360. if (api)
  4361. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4362. OnDeactivate();
  4363. }
  4364. bool OBSBasic::NoSourcesConfirmation()
  4365. {
  4366. if (CountVideoSources() == 0 && isVisible()) {
  4367. QString msg;
  4368. msg = QTStr("NoSources.Text");
  4369. msg += "\n\n";
  4370. msg += QTStr("NoSources.Text.AddSource");
  4371. QMessageBox messageBox(QMessageBox::Question,
  4372. QTStr("NoSources.title"),
  4373. msg,
  4374. QMessageBox::Yes | QMessageBox::No,
  4375. this);
  4376. messageBox.setDefaultButton(QMessageBox::No);
  4377. if (QMessageBox::No == messageBox.exec())
  4378. return false;
  4379. }
  4380. return true;
  4381. }
  4382. void OBSBasic::on_streamButton_clicked()
  4383. {
  4384. if (outputHandler->StreamingActive()) {
  4385. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4386. "WarnBeforeStoppingStream");
  4387. if (confirm && isVisible()) {
  4388. QMessageBox::StandardButton button =
  4389. OBSMessageBox::question(this,
  4390. QTStr("ConfirmStop.Title"),
  4391. QTStr("ConfirmStop.Text"));
  4392. if (button == QMessageBox::No) {
  4393. ui->streamButton->setChecked(true);
  4394. return;
  4395. }
  4396. }
  4397. StopStreaming();
  4398. } else {
  4399. if (!NoSourcesConfirmation()) {
  4400. ui->streamButton->setChecked(false);
  4401. return;
  4402. }
  4403. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4404. "WarnBeforeStartingStream");
  4405. if (confirm && isVisible()) {
  4406. QMessageBox::StandardButton button =
  4407. OBSMessageBox::question(this,
  4408. QTStr("ConfirmStart.Title"),
  4409. QTStr("ConfirmStart.Text"));
  4410. if (button == QMessageBox::No) {
  4411. ui->streamButton->setChecked(false);
  4412. return;
  4413. }
  4414. }
  4415. StartStreaming();
  4416. }
  4417. }
  4418. void OBSBasic::on_recordButton_clicked()
  4419. {
  4420. if (outputHandler->RecordingActive()) {
  4421. StopRecording();
  4422. } else {
  4423. if (!NoSourcesConfirmation()) {
  4424. ui->recordButton->setChecked(false);
  4425. return;
  4426. }
  4427. StartRecording();
  4428. }
  4429. }
  4430. void OBSBasic::on_settingsButton_clicked()
  4431. {
  4432. on_action_Settings_triggered();
  4433. }
  4434. void OBSBasic::on_actionHelpPortal_triggered()
  4435. {
  4436. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4437. QDesktopServices::openUrl(url);
  4438. }
  4439. void OBSBasic::on_actionWebsite_triggered()
  4440. {
  4441. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4442. QDesktopServices::openUrl(url);
  4443. }
  4444. void OBSBasic::on_actionDiscord_triggered()
  4445. {
  4446. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4447. QDesktopServices::openUrl(url);
  4448. }
  4449. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4450. {
  4451. char path[512];
  4452. int ret = GetConfigPath(path, 512, "obs-studio");
  4453. if (ret <= 0)
  4454. return;
  4455. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4456. }
  4457. void OBSBasic::on_actionShowProfileFolder_triggered()
  4458. {
  4459. char path[512];
  4460. int ret = GetProfilePath(path, 512, "");
  4461. if (ret <= 0)
  4462. return;
  4463. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4464. }
  4465. int OBSBasic::GetTopSelectedSourceItem()
  4466. {
  4467. QModelIndexList selectedItems =
  4468. ui->sources->selectionModel()->selectedIndexes();
  4469. return selectedItems.count() ? selectedItems[0].row() : -1;
  4470. }
  4471. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4472. {
  4473. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4474. UNUSED_PARAMETER(pos);
  4475. }
  4476. void OBSBasic::on_program_customContextMenuRequested(const QPoint&)
  4477. {
  4478. QMenu popup(this);
  4479. QPointer<QMenu> studioProgramProjector;
  4480. studioProgramProjector = new QMenu(
  4481. QTStr("StudioProgramProjector"));
  4482. AddProjectorMenuMonitors(studioProgramProjector, this,
  4483. SLOT(OpenStudioProgramProjector()));
  4484. popup.addMenu(studioProgramProjector);
  4485. QAction *studioProgramWindow = popup.addAction(
  4486. QTStr("StudioProgramWindow"),
  4487. this, SLOT(OpenStudioProgramWindow()));
  4488. popup.addAction(studioProgramWindow);
  4489. popup.exec(QCursor::pos());
  4490. }
  4491. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  4492. const QPoint &pos)
  4493. {
  4494. QMenu popup(this);
  4495. delete previewProjectorMain;
  4496. QAction *action = popup.addAction(
  4497. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4498. this, SLOT(TogglePreview()));
  4499. action->setCheckable(true);
  4500. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4501. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4502. AddProjectorMenuMonitors(previewProjectorMain, this,
  4503. SLOT(OpenPreviewProjector()));
  4504. QAction *previewWindow = popup.addAction(
  4505. QTStr("PreviewWindow"),
  4506. this, SLOT(OpenPreviewWindow()));
  4507. popup.addMenu(previewProjectorMain);
  4508. popup.addAction(previewWindow);
  4509. popup.exec(QCursor::pos());
  4510. UNUSED_PARAMETER(pos);
  4511. }
  4512. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4513. {
  4514. #ifndef _WIN32
  4515. /* Make sure all dialogs are safely and successfully closed before
  4516. * switching the always on top mode due to the fact that windows all
  4517. * have to be recreated, so queue the actual toggle to happen after
  4518. * all events related to closing the dialogs have finished */
  4519. CloseDialogs();
  4520. #endif
  4521. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4522. Qt::QueuedConnection);
  4523. }
  4524. void OBSBasic::ToggleAlwaysOnTop()
  4525. {
  4526. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4527. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4528. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4529. show();
  4530. }
  4531. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4532. {
  4533. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4534. if (strcmp(val, "10") == 0) {
  4535. num = 10;
  4536. den = 1;
  4537. } else if (strcmp(val, "20") == 0) {
  4538. num = 20;
  4539. den = 1;
  4540. } else if (strcmp(val, "24 NTSC") == 0) {
  4541. num = 24000;
  4542. den = 1001;
  4543. } else if (strcmp(val, "25") == 0) {
  4544. num = 25;
  4545. den = 1;
  4546. } else if (strcmp(val, "29.97") == 0) {
  4547. num = 30000;
  4548. den = 1001;
  4549. } else if (strcmp(val, "48") == 0) {
  4550. num = 48;
  4551. den = 1;
  4552. } else if (strcmp(val, "59.94") == 0) {
  4553. num = 60000;
  4554. den = 1001;
  4555. } else if (strcmp(val, "60") == 0) {
  4556. num = 60;
  4557. den = 1;
  4558. } else {
  4559. num = 30;
  4560. den = 1;
  4561. }
  4562. }
  4563. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4564. {
  4565. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4566. den = 1;
  4567. }
  4568. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4569. {
  4570. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4571. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4572. }
  4573. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4574. {
  4575. num = 1000000000;
  4576. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4577. }
  4578. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4579. {
  4580. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4581. if (type == 1) //"Integer"
  4582. GetFPSInteger(num, den);
  4583. else if (type == 2) //"Fraction"
  4584. GetFPSFraction(num, den);
  4585. else if (false) //"Nanoseconds", currently not implemented
  4586. GetFPSNanoseconds(num, den);
  4587. else
  4588. GetFPSCommon(num, den);
  4589. }
  4590. config_t *OBSBasic::Config() const
  4591. {
  4592. return basicConfig;
  4593. }
  4594. void OBSBasic::on_actionEditTransform_triggered()
  4595. {
  4596. if (transformWindow)
  4597. transformWindow->close();
  4598. transformWindow = new OBSBasicTransform(this);
  4599. transformWindow->show();
  4600. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4601. }
  4602. static obs_transform_info copiedTransformInfo;
  4603. static obs_sceneitem_crop copiedCropInfo;
  4604. void OBSBasic::on_actionCopyTransform_triggered()
  4605. {
  4606. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4607. {
  4608. if (!obs_sceneitem_selected(item))
  4609. return true;
  4610. obs_sceneitem_defer_update_begin(item);
  4611. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4612. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4613. obs_sceneitem_defer_update_end(item);
  4614. UNUSED_PARAMETER(scene);
  4615. UNUSED_PARAMETER(param);
  4616. return true;
  4617. };
  4618. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4619. ui->actionPasteTransform->setEnabled(true);
  4620. }
  4621. void OBSBasic::on_actionPasteTransform_triggered()
  4622. {
  4623. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4624. {
  4625. if (!obs_sceneitem_selected(item))
  4626. return true;
  4627. obs_sceneitem_defer_update_begin(item);
  4628. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4629. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4630. obs_sceneitem_defer_update_end(item);
  4631. UNUSED_PARAMETER(scene);
  4632. UNUSED_PARAMETER(param);
  4633. return true;
  4634. };
  4635. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4636. }
  4637. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4638. {
  4639. if (obs_sceneitem_is_group(item))
  4640. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  4641. if (!obs_sceneitem_selected(item))
  4642. return true;
  4643. obs_sceneitem_defer_update_begin(item);
  4644. obs_transform_info info;
  4645. vec2_set(&info.pos, 0.0f, 0.0f);
  4646. vec2_set(&info.scale, 1.0f, 1.0f);
  4647. info.rot = 0.0f;
  4648. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4649. info.bounds_type = OBS_BOUNDS_NONE;
  4650. info.bounds_alignment = OBS_ALIGN_CENTER;
  4651. vec2_set(&info.bounds, 0.0f, 0.0f);
  4652. obs_sceneitem_set_info(item, &info);
  4653. obs_sceneitem_crop crop = {};
  4654. obs_sceneitem_set_crop(item, &crop);
  4655. obs_sceneitem_defer_update_end(item);
  4656. UNUSED_PARAMETER(scene);
  4657. UNUSED_PARAMETER(param);
  4658. return true;
  4659. }
  4660. void OBSBasic::on_actionResetTransform_triggered()
  4661. {
  4662. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  4663. }
  4664. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4665. {
  4666. matrix4 boxTransform;
  4667. obs_sceneitem_get_box_transform(item, &boxTransform);
  4668. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4669. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4670. auto GetMinPos = [&] (float x, float y)
  4671. {
  4672. vec3 pos;
  4673. vec3_set(&pos, x, y, 0.0f);
  4674. vec3_transform(&pos, &pos, &boxTransform);
  4675. vec3_min(&tl, &tl, &pos);
  4676. vec3_max(&br, &br, &pos);
  4677. };
  4678. GetMinPos(0.0f, 0.0f);
  4679. GetMinPos(1.0f, 0.0f);
  4680. GetMinPos(0.0f, 1.0f);
  4681. GetMinPos(1.0f, 1.0f);
  4682. }
  4683. static vec3 GetItemTL(obs_sceneitem_t *item)
  4684. {
  4685. vec3 tl, br;
  4686. GetItemBox(item, tl, br);
  4687. return tl;
  4688. }
  4689. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4690. {
  4691. vec3 newTL;
  4692. vec2 pos;
  4693. obs_sceneitem_get_pos(item, &pos);
  4694. newTL = GetItemTL(item);
  4695. pos.x += tl.x - newTL.x;
  4696. pos.y += tl.y - newTL.y;
  4697. obs_sceneitem_set_pos(item, &pos);
  4698. }
  4699. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4700. void *param)
  4701. {
  4702. if (obs_sceneitem_is_group(item))
  4703. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  4704. param);
  4705. if (!obs_sceneitem_selected(item))
  4706. return true;
  4707. float rot = *reinterpret_cast<float*>(param);
  4708. vec3 tl = GetItemTL(item);
  4709. rot += obs_sceneitem_get_rot(item);
  4710. if (rot >= 360.0f) rot -= 360.0f;
  4711. else if (rot <= -360.0f) rot += 360.0f;
  4712. obs_sceneitem_set_rot(item, rot);
  4713. obs_sceneitem_force_update_transform(item);
  4714. SetItemTL(item, tl);
  4715. UNUSED_PARAMETER(scene);
  4716. return true;
  4717. };
  4718. void OBSBasic::on_actionRotate90CW_triggered()
  4719. {
  4720. float f90CW = 90.0f;
  4721. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4722. }
  4723. void OBSBasic::on_actionRotate90CCW_triggered()
  4724. {
  4725. float f90CCW = -90.0f;
  4726. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4727. }
  4728. void OBSBasic::on_actionRotate180_triggered()
  4729. {
  4730. float f180 = 180.0f;
  4731. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4732. }
  4733. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4734. void *param)
  4735. {
  4736. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4737. if (obs_sceneitem_is_group(item))
  4738. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  4739. param);
  4740. if (!obs_sceneitem_selected(item))
  4741. return true;
  4742. vec3 tl = GetItemTL(item);
  4743. vec2 scale;
  4744. obs_sceneitem_get_scale(item, &scale);
  4745. vec2_mul(&scale, &scale, &mul);
  4746. obs_sceneitem_set_scale(item, &scale);
  4747. obs_sceneitem_force_update_transform(item);
  4748. SetItemTL(item, tl);
  4749. UNUSED_PARAMETER(scene);
  4750. return true;
  4751. }
  4752. void OBSBasic::on_actionFlipHorizontal_triggered()
  4753. {
  4754. vec2 scale;
  4755. vec2_set(&scale, -1.0f, 1.0f);
  4756. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4757. &scale);
  4758. }
  4759. void OBSBasic::on_actionFlipVertical_triggered()
  4760. {
  4761. vec2 scale;
  4762. vec2_set(&scale, 1.0f, -1.0f);
  4763. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4764. &scale);
  4765. }
  4766. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4767. void *param)
  4768. {
  4769. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4770. if (obs_sceneitem_is_group(item))
  4771. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  4772. param);
  4773. if (!obs_sceneitem_selected(item))
  4774. return true;
  4775. obs_video_info ovi;
  4776. obs_get_video_info(&ovi);
  4777. obs_transform_info itemInfo;
  4778. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4779. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4780. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4781. itemInfo.rot = 0.0f;
  4782. vec2_set(&itemInfo.bounds,
  4783. float(ovi.base_width), float(ovi.base_height));
  4784. itemInfo.bounds_type = boundsType;
  4785. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4786. obs_sceneitem_set_info(item, &itemInfo);
  4787. UNUSED_PARAMETER(scene);
  4788. return true;
  4789. }
  4790. void OBSBasic::on_actionFitToScreen_triggered()
  4791. {
  4792. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4793. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4794. &boundsType);
  4795. }
  4796. void OBSBasic::on_actionStretchToScreen_triggered()
  4797. {
  4798. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4799. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4800. &boundsType);
  4801. }
  4802. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *)
  4803. {
  4804. vec3 tl, br, itemCenter, screenCenter, offset;
  4805. obs_video_info ovi;
  4806. if (obs_sceneitem_is_group(item))
  4807. obs_sceneitem_group_enum_items(item, center_to_scene, nullptr);
  4808. if (!obs_sceneitem_selected(item))
  4809. return true;
  4810. obs_get_video_info(&ovi);
  4811. vec3_set(&screenCenter, float(ovi.base_width),
  4812. float(ovi.base_height), 0.0f);
  4813. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4814. GetItemBox(item, tl, br);
  4815. vec3_sub(&itemCenter, &br, &tl);
  4816. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4817. vec3_add(&itemCenter, &itemCenter, &tl);
  4818. vec3_sub(&offset, &screenCenter, &itemCenter);
  4819. vec3_add(&tl, &tl, &offset);
  4820. SetItemTL(item, tl);
  4821. return true;
  4822. };
  4823. void OBSBasic::on_actionCenterToScreen_triggered()
  4824. {
  4825. obs_scene_enum_items(GetCurrentScene(), center_to_scene, nullptr);
  4826. }
  4827. void OBSBasic::EnablePreviewDisplay(bool enable)
  4828. {
  4829. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4830. ui->preview->setVisible(enable);
  4831. ui->previewDisabledLabel->setVisible(!enable);
  4832. }
  4833. void OBSBasic::TogglePreview()
  4834. {
  4835. previewEnabled = !previewEnabled;
  4836. EnablePreviewDisplay(previewEnabled);
  4837. }
  4838. static bool nudge_callback(obs_scene_t*, obs_sceneitem_t *item, void *param)
  4839. {
  4840. if (obs_sceneitem_locked(item))
  4841. return true;
  4842. struct vec2 &offset = *reinterpret_cast<struct vec2*>(param);
  4843. struct vec2 pos;
  4844. if (!obs_sceneitem_selected(item)) {
  4845. if (obs_sceneitem_is_group(item)) {
  4846. struct vec3 offset3;
  4847. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  4848. struct matrix4 matrix;
  4849. obs_sceneitem_get_draw_transform(item, &matrix);
  4850. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  4851. matrix4_inv(&matrix, &matrix);
  4852. vec3_transform(&offset3, &offset3, &matrix);
  4853. struct vec2 new_offset;
  4854. vec2_set(&new_offset, offset3.x, offset3.y);
  4855. obs_sceneitem_group_enum_items(item, nudge_callback,
  4856. &new_offset);
  4857. }
  4858. return true;
  4859. }
  4860. obs_sceneitem_get_pos(item, &pos);
  4861. vec2_add(&pos, &pos, &offset);
  4862. obs_sceneitem_set_pos(item, &pos);
  4863. return true;
  4864. }
  4865. void OBSBasic::Nudge(int dist, MoveDir dir)
  4866. {
  4867. if (ui->preview->Locked())
  4868. return;
  4869. struct vec2 offset;
  4870. vec2_set(&offset, 0.0f, 0.0f);
  4871. switch (dir) {
  4872. case MoveDir::Up: offset.y = (float)-dist; break;
  4873. case MoveDir::Down: offset.y = (float) dist; break;
  4874. case MoveDir::Left: offset.x = (float)-dist; break;
  4875. case MoveDir::Right: offset.x = (float) dist; break;
  4876. }
  4877. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  4878. }
  4879. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4880. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4881. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4882. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4883. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  4884. QString title, ProjectorType type)
  4885. {
  4886. /* seriously? 10 monitors? */
  4887. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4888. return nullptr;
  4889. OBSProjector *projector = new OBSProjector(nullptr, source, monitor,
  4890. title, type);
  4891. if (monitor < 0) {
  4892. for (auto &projPtr : windowProjectors) {
  4893. if (!projPtr) {
  4894. projPtr = projector;
  4895. projector = nullptr;
  4896. }
  4897. }
  4898. if (projector)
  4899. windowProjectors.push_back(projector);
  4900. } else {
  4901. delete projectors[monitor];
  4902. projectors[monitor].clear();
  4903. projectors[monitor] = projector;
  4904. }
  4905. return projector;
  4906. }
  4907. void OBSBasic::OpenStudioProgramProjector()
  4908. {
  4909. int monitor = sender()->property("monitor").toInt();
  4910. OpenProjector(nullptr, monitor, nullptr, ProjectorType::StudioProgram);
  4911. }
  4912. void OBSBasic::OpenPreviewProjector()
  4913. {
  4914. int monitor = sender()->property("monitor").toInt();
  4915. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Preview);
  4916. }
  4917. void OBSBasic::OpenSourceProjector()
  4918. {
  4919. int monitor = sender()->property("monitor").toInt();
  4920. OBSSceneItem item = GetCurrentSceneItem();
  4921. if (!item)
  4922. return;
  4923. OpenProjector(obs_sceneitem_get_source(item), monitor, nullptr,
  4924. ProjectorType::Source);
  4925. }
  4926. void OBSBasic::OpenMultiviewProjector()
  4927. {
  4928. int monitor = sender()->property("monitor").toInt();
  4929. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Multiview);
  4930. }
  4931. void OBSBasic::OpenSceneProjector()
  4932. {
  4933. int monitor = sender()->property("monitor").toInt();
  4934. OBSScene scene = GetCurrentScene();
  4935. if (!scene)
  4936. return;
  4937. OpenProjector(obs_scene_get_source(scene), monitor, nullptr,
  4938. ProjectorType::Scene);
  4939. }
  4940. void OBSBasic::OpenStudioProgramWindow()
  4941. {
  4942. OpenProjector(nullptr, -1, QTStr("StudioProgramWindow"),
  4943. ProjectorType::StudioProgram);
  4944. }
  4945. void OBSBasic::OpenPreviewWindow()
  4946. {
  4947. OpenProjector(nullptr, -1, QTStr("PreviewWindow"),
  4948. ProjectorType::Preview);
  4949. }
  4950. void OBSBasic::OpenSourceWindow()
  4951. {
  4952. OBSSceneItem item = GetCurrentSceneItem();
  4953. if (!item)
  4954. return;
  4955. OBSSource source = obs_sceneitem_get_source(item);
  4956. QString title = QString::fromUtf8(obs_source_get_name(source));
  4957. OpenProjector(obs_sceneitem_get_source(item), -1, title,
  4958. ProjectorType::Source);
  4959. }
  4960. void OBSBasic::OpenMultiviewWindow()
  4961. {
  4962. OpenProjector(nullptr, -1, QTStr("MultiviewWindowed"),
  4963. ProjectorType::Multiview);
  4964. }
  4965. void OBSBasic::OpenSceneWindow()
  4966. {
  4967. OBSScene scene = GetCurrentScene();
  4968. if (!scene)
  4969. return;
  4970. OBSSource source = obs_scene_get_source(scene);
  4971. QString title = QString::fromUtf8(obs_source_get_name(source));
  4972. OpenProjector(obs_scene_get_source(scene), -1, title,
  4973. ProjectorType::Scene);
  4974. }
  4975. void OBSBasic::OpenSavedProjectors()
  4976. {
  4977. for (SavedProjectorInfo *info : savedProjectorsArray) {
  4978. OBSProjector *projector = nullptr;
  4979. switch (info->type) {
  4980. case ProjectorType::Source:
  4981. case ProjectorType::Scene: {
  4982. OBSSource source = obs_get_source_by_name(
  4983. info->name.c_str());
  4984. if (!source)
  4985. continue;
  4986. QString title = nullptr;
  4987. if (info->monitor < 0)
  4988. title = QString::fromUtf8(
  4989. obs_source_get_name(source));
  4990. projector = OpenProjector(source, info->monitor, title,
  4991. info->type);
  4992. obs_source_release(source);
  4993. break;
  4994. }
  4995. case ProjectorType::Preview: {
  4996. projector = OpenProjector(nullptr, info->monitor,
  4997. QTStr("PreviewWindow"),
  4998. ProjectorType::Preview);
  4999. break;
  5000. }
  5001. case ProjectorType::StudioProgram: {
  5002. projector = OpenProjector(nullptr, info->monitor,
  5003. QTStr("StudioProgramWindow"),
  5004. ProjectorType::StudioProgram);
  5005. break;
  5006. }
  5007. case ProjectorType::Multiview: {
  5008. projector = OpenProjector(nullptr, info->monitor,
  5009. QTStr("MultiviewWindowed"),
  5010. ProjectorType::Multiview);
  5011. break;
  5012. }
  5013. }
  5014. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5015. QByteArray byteArray = QByteArray::fromBase64(
  5016. QByteArray(info->geometry.c_str()));
  5017. projector->restoreGeometry(byteArray);
  5018. if (!WindowPositionValid(projector->normalGeometry())) {
  5019. QRect rect = App()->desktop()->geometry();
  5020. projector->setGeometry(QStyle::alignedRect(
  5021. Qt::LeftToRight,
  5022. Qt::AlignCenter, size(), rect));
  5023. }
  5024. }
  5025. }
  5026. }
  5027. void OBSBasic::on_actionFullscreenInterface_triggered()
  5028. {
  5029. if (!fullscreenInterface)
  5030. showFullScreen();
  5031. else
  5032. showNormal();
  5033. fullscreenInterface = !fullscreenInterface;
  5034. }
  5035. void OBSBasic::UpdateTitleBar()
  5036. {
  5037. stringstream name;
  5038. const char *profile = config_get_string(App()->GlobalConfig(),
  5039. "Basic", "Profile");
  5040. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  5041. "Basic", "SceneCollection");
  5042. name << "OBS ";
  5043. if (previewProgramMode)
  5044. name << "Studio ";
  5045. name << App()->GetVersionString();
  5046. if (App()->IsPortableMode())
  5047. name << " - Portable Mode";
  5048. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5049. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5050. setWindowTitle(QT_UTF8(name.str().c_str()));
  5051. }
  5052. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5053. {
  5054. char profiles_path[512];
  5055. const char *profile = config_get_string(App()->GlobalConfig(),
  5056. "Basic", "ProfileDir");
  5057. int ret;
  5058. if (!profile)
  5059. return -1;
  5060. if (!path)
  5061. return -1;
  5062. if (!file)
  5063. file = "";
  5064. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5065. if (ret <= 0)
  5066. return ret;
  5067. if (!*file)
  5068. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5069. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5070. }
  5071. void OBSBasic::on_resetUI_triggered()
  5072. {
  5073. /* prune deleted extra docks */
  5074. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5075. if (!extraDocks[i]) {
  5076. extraDocks.removeAt(i);
  5077. }
  5078. }
  5079. if (extraDocks.size()) {
  5080. QMessageBox::StandardButton button = QMessageBox::question(
  5081. this,
  5082. QTStr("ResetUIWarning.Title"),
  5083. QTStr("ResetUIWarning.Text"));
  5084. if (button == QMessageBox::No)
  5085. return;
  5086. }
  5087. /* undock/hide/center extra docks */
  5088. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5089. if (extraDocks[i]) {
  5090. extraDocks[i]->setVisible(true);
  5091. extraDocks[i]->setFloating(true);
  5092. extraDocks[i]->move(
  5093. frameGeometry().topLeft() +
  5094. rect().center() -
  5095. extraDocks[i]->rect().center());
  5096. extraDocks[i]->setVisible(false);
  5097. }
  5098. }
  5099. restoreState(startingDockLayout);
  5100. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5101. int cx = width();
  5102. int cy = height();
  5103. int cx22_5 = cx * 225 / 1000;
  5104. int cx5 = cx * 5 / 100;
  5105. cy = cy * 225 / 1000;
  5106. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5107. QList<QDockWidget*> docks {
  5108. ui->scenesDock,
  5109. ui->sourcesDock,
  5110. ui->mixerDock,
  5111. ui->transitionsDock,
  5112. ui->controlsDock
  5113. };
  5114. QList<int> sizes {
  5115. cx22_5,
  5116. cx22_5,
  5117. mixerSize,
  5118. cx5,
  5119. cx5
  5120. };
  5121. ui->scenesDock->setVisible(true);
  5122. ui->sourcesDock->setVisible(true);
  5123. ui->mixerDock->setVisible(true);
  5124. ui->transitionsDock->setVisible(true);
  5125. ui->controlsDock->setVisible(true);
  5126. statsDock->setVisible(false);
  5127. statsDock->setFloating(true);
  5128. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5129. resizeDocks(docks, sizes, Qt::Horizontal);
  5130. #endif
  5131. }
  5132. void OBSBasic::on_lockUI_toggled(bool lock)
  5133. {
  5134. QDockWidget::DockWidgetFeatures features = lock
  5135. ? QDockWidget::NoDockWidgetFeatures
  5136. : QDockWidget::AllDockWidgetFeatures;
  5137. ui->scenesDock->setFeatures(features);
  5138. ui->sourcesDock->setFeatures(features);
  5139. ui->mixerDock->setFeatures(features);
  5140. ui->transitionsDock->setFeatures(features);
  5141. ui->controlsDock->setFeatures(features);
  5142. statsDock->setFeatures(features);
  5143. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5144. if (!extraDocks[i]) {
  5145. extraDocks.removeAt(i);
  5146. } else {
  5147. extraDocks[i]->setFeatures(features);
  5148. }
  5149. }
  5150. }
  5151. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5152. {
  5153. ui->sourcesToolbar->setVisible(visible);
  5154. ui->scenesToolbar->setVisible(visible);
  5155. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5156. "ShowListboxToolbars", visible);
  5157. }
  5158. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5159. {
  5160. ui->statusbar->setVisible(visible);
  5161. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5162. "ShowStatusBar", visible);
  5163. }
  5164. void OBSBasic::on_actionLockPreview_triggered()
  5165. {
  5166. ui->preview->ToggleLocked();
  5167. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5168. }
  5169. void OBSBasic::on_scalingMenu_aboutToShow()
  5170. {
  5171. obs_video_info ovi;
  5172. obs_get_video_info(&ovi);
  5173. QAction *action = ui->actionScaleCanvas;
  5174. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5175. text = text.arg(QString::number(ovi.base_width),
  5176. QString::number(ovi.base_height));
  5177. action->setText(text);
  5178. action = ui->actionScaleOutput;
  5179. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5180. text = text.arg(QString::number(ovi.output_width),
  5181. QString::number(ovi.output_height));
  5182. action->setText(text);
  5183. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5184. ovi.output_height == ovi.base_height));
  5185. UpdatePreviewScalingMenu();
  5186. }
  5187. void OBSBasic::on_actionScaleWindow_triggered()
  5188. {
  5189. ui->preview->SetFixedScaling(false);
  5190. ui->preview->ResetScrollingOffset();
  5191. emit ui->preview->DisplayResized();
  5192. }
  5193. void OBSBasic::on_actionScaleCanvas_triggered()
  5194. {
  5195. ui->preview->SetFixedScaling(true);
  5196. ui->preview->SetScalingLevel(0);
  5197. emit ui->preview->DisplayResized();
  5198. }
  5199. void OBSBasic::on_actionScaleOutput_triggered()
  5200. {
  5201. obs_video_info ovi;
  5202. obs_get_video_info(&ovi);
  5203. ui->preview->SetFixedScaling(true);
  5204. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5205. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5206. int32_t approxScalingLevel = int32_t(
  5207. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5208. ui->preview->SetScalingLevel(approxScalingLevel);
  5209. ui->preview->SetScalingAmount(scalingAmount);
  5210. emit ui->preview->DisplayResized();
  5211. }
  5212. void OBSBasic::SetShowing(bool showing)
  5213. {
  5214. if (!showing && isVisible()) {
  5215. config_set_string(App()->GlobalConfig(),
  5216. "BasicWindow", "geometry",
  5217. saveGeometry().toBase64().constData());
  5218. /* hide all visible child dialogs */
  5219. visDlgPositions.clear();
  5220. if (!visDialogs.isEmpty()) {
  5221. for (QDialog *dlg : visDialogs) {
  5222. visDlgPositions.append(dlg->pos());
  5223. dlg->hide();
  5224. }
  5225. }
  5226. if (showHide)
  5227. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5228. QTimer::singleShot(250, this, SLOT(hide()));
  5229. if (previewEnabled)
  5230. EnablePreviewDisplay(false);
  5231. setVisible(false);
  5232. #ifdef __APPLE__
  5233. EnableOSXDockIcon(false);
  5234. #endif
  5235. } else if (showing && !isVisible()) {
  5236. if (showHide)
  5237. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5238. QTimer::singleShot(250, this, SLOT(show()));
  5239. if (previewEnabled)
  5240. EnablePreviewDisplay(true);
  5241. setVisible(true);
  5242. #ifdef __APPLE__
  5243. EnableOSXDockIcon(true);
  5244. #endif
  5245. /* raise and activate window to ensure it is on top */
  5246. raise();
  5247. activateWindow();
  5248. /* show all child dialogs that was visible earlier */
  5249. if (!visDialogs.isEmpty()) {
  5250. for (int i = 0; i < visDialogs.size(); ++i) {
  5251. QDialog *dlg = visDialogs[i];
  5252. dlg->move(visDlgPositions[i]);
  5253. dlg->show();
  5254. }
  5255. }
  5256. /* Unminimize window if it was hidden to tray instead of task
  5257. * bar. */
  5258. if (sysTrayMinimizeToTray()) {
  5259. Qt::WindowStates state;
  5260. state = windowState() & ~Qt::WindowMinimized;
  5261. state |= Qt::WindowActive;
  5262. setWindowState(state);
  5263. }
  5264. }
  5265. }
  5266. void OBSBasic::ToggleShowHide()
  5267. {
  5268. bool showing = isVisible();
  5269. if (showing) {
  5270. /* check for modal dialogs */
  5271. EnumDialogs();
  5272. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5273. return;
  5274. }
  5275. SetShowing(!showing);
  5276. }
  5277. void OBSBasic::SystemTrayInit()
  5278. {
  5279. trayIcon.reset(new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  5280. this));
  5281. trayIcon->setToolTip("OBS Studio");
  5282. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  5283. trayIcon.data());
  5284. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5285. trayIcon.data());
  5286. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5287. trayIcon.data());
  5288. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5289. trayIcon.data());
  5290. exit = new QAction(QTStr("Exit"),
  5291. trayIcon.data());
  5292. trayMenu = new QMenu;
  5293. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5294. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5295. AddProjectorMenuMonitors(previewProjector, this,
  5296. SLOT(OpenPreviewProjector()));
  5297. AddProjectorMenuMonitors(studioProgramProjector, this,
  5298. SLOT(OpenStudioProgramProjector()));
  5299. trayMenu->addAction(showHide);
  5300. trayMenu->addMenu(previewProjector);
  5301. trayMenu->addMenu(studioProgramProjector);
  5302. trayMenu->addAction(sysTrayStream);
  5303. trayMenu->addAction(sysTrayRecord);
  5304. trayMenu->addAction(sysTrayReplayBuffer);
  5305. trayMenu->addAction(exit);
  5306. trayIcon->setContextMenu(trayMenu);
  5307. if (outputHandler && !outputHandler->replayBuffer)
  5308. sysTrayReplayBuffer->setEnabled(false);
  5309. connect(trayIcon.data(),
  5310. SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  5311. this,
  5312. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5313. connect(showHide, SIGNAL(triggered()),
  5314. this, SLOT(ToggleShowHide()));
  5315. connect(sysTrayStream, SIGNAL(triggered()),
  5316. this, SLOT(on_streamButton_clicked()));
  5317. connect(sysTrayRecord, SIGNAL(triggered()),
  5318. this, SLOT(on_recordButton_clicked()));
  5319. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  5320. this, &OBSBasic::ReplayBufferClicked);
  5321. connect(exit, SIGNAL(triggered()),
  5322. this, SLOT(close()));
  5323. }
  5324. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5325. {
  5326. // Refresh projector list
  5327. previewProjector->clear();
  5328. studioProgramProjector->clear();
  5329. AddProjectorMenuMonitors(previewProjector, this,
  5330. SLOT(OpenPreviewProjector()));
  5331. AddProjectorMenuMonitors(studioProgramProjector, this,
  5332. SLOT(OpenStudioProgramProjector()));
  5333. if (reason == QSystemTrayIcon::Trigger)
  5334. ToggleShowHide();
  5335. }
  5336. void OBSBasic::SysTrayNotify(const QString &text,
  5337. QSystemTrayIcon::MessageIcon n)
  5338. {
  5339. if (QSystemTrayIcon::supportsMessages()) {
  5340. QSystemTrayIcon::MessageIcon icon =
  5341. QSystemTrayIcon::MessageIcon(n);
  5342. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5343. }
  5344. }
  5345. void OBSBasic::SystemTray(bool firstStarted)
  5346. {
  5347. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5348. return;
  5349. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  5350. "BasicWindow", "SysTrayWhenStarted");
  5351. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  5352. "BasicWindow", "SysTrayEnabled");
  5353. if (firstStarted)
  5354. SystemTrayInit();
  5355. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5356. trayIcon->hide();
  5357. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  5358. || opt_minimize_tray) {
  5359. trayIcon->show();
  5360. if (firstStarted) {
  5361. QTimer::singleShot(50, this, SLOT(hide()));
  5362. EnablePreviewDisplay(false);
  5363. setVisible(false);
  5364. #ifdef __APPLE__
  5365. EnableOSXDockIcon(false);
  5366. #endif
  5367. opt_minimize_tray = false;
  5368. }
  5369. } else if (sysTrayEnabled) {
  5370. trayIcon->show();
  5371. } else if (!sysTrayEnabled) {
  5372. trayIcon->hide();
  5373. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5374. trayIcon->hide();
  5375. }
  5376. if (isVisible())
  5377. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5378. else
  5379. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5380. }
  5381. bool OBSBasic::sysTrayMinimizeToTray()
  5382. {
  5383. return config_get_bool(GetGlobalConfig(),
  5384. "BasicWindow", "SysTrayMinimizeToTray");
  5385. }
  5386. void OBSBasic::on_actionCopySource_triggered()
  5387. {
  5388. OBSSceneItem item = GetCurrentSceneItem();
  5389. if (!item)
  5390. return;
  5391. on_actionCopyTransform_triggered();
  5392. OBSSource source = obs_sceneitem_get_source(item);
  5393. copyString = obs_source_get_name(source);
  5394. copyVisible = obs_sceneitem_visible(item);
  5395. ui->actionPasteRef->setEnabled(true);
  5396. uint32_t output_flags = obs_source_get_output_flags(source);
  5397. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5398. ui->actionPasteDup->setEnabled(true);
  5399. else
  5400. ui->actionPasteDup->setEnabled(false);
  5401. }
  5402. void OBSBasic::on_actionPasteRef_triggered()
  5403. {
  5404. /* do not allow duplicate refs of the same group in the same scene */
  5405. OBSScene scene = GetCurrentScene();
  5406. if (!!obs_scene_get_group(scene, copyString))
  5407. return;
  5408. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  5409. on_actionPasteTransform_triggered();
  5410. }
  5411. void OBSBasic::on_actionPasteDup_triggered()
  5412. {
  5413. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  5414. on_actionPasteTransform_triggered();
  5415. }
  5416. void OBSBasic::on_actionCopyFilters_triggered()
  5417. {
  5418. OBSSceneItem item = GetCurrentSceneItem();
  5419. if (!item)
  5420. return;
  5421. OBSSource source = obs_sceneitem_get_source(item);
  5422. copyFiltersString = obs_source_get_name(source);
  5423. ui->actionPasteFilters->setEnabled(true);
  5424. }
  5425. void OBSBasic::on_actionPasteFilters_triggered()
  5426. {
  5427. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5428. obs_source_release(source);
  5429. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5430. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5431. if (source == dstSource)
  5432. return;
  5433. obs_source_copy_filters(dstSource, source);
  5434. }
  5435. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5436. QModelIndexList selectedItems)
  5437. {
  5438. for (int x = 0; x < selectedItems.count(); x++) {
  5439. SourceTreeItem *treeItem = sources
  5440. ->GetItemWidget(selectedItems[x].row());
  5441. treeItem->setStyleSheet("background: "
  5442. + color.name(QColor::HexArgb));
  5443. treeItem->style()->unpolish(treeItem);
  5444. treeItem->style()->polish(treeItem);
  5445. OBSSceneItem sceneItem = sources->Get(
  5446. selectedItems[x].row());
  5447. obs_data_t *privData =
  5448. obs_sceneitem_get_private_settings(sceneItem);
  5449. obs_data_set_int(privData, "color-preset", 1);
  5450. obs_data_set_string(privData, "color",
  5451. QT_TO_UTF8(color.name(
  5452. QColor::HexArgb)));
  5453. obs_data_release(privData);
  5454. }
  5455. }
  5456. void OBSBasic::ColorChange()
  5457. {
  5458. QModelIndexList selectedItems =
  5459. ui->sources->selectionModel()->selectedIndexes();
  5460. QAction *action = qobject_cast<QAction*>(sender());
  5461. QPushButton *colorButton = qobject_cast<QPushButton*>(sender());
  5462. if (selectedItems.count() == 0)
  5463. return;
  5464. if (colorButton) {
  5465. int preset = colorButton->property("bgColor").value<int>();
  5466. for (int x = 0; x < selectedItems.count(); x++) {
  5467. SourceTreeItem *treeItem = ui->sources
  5468. ->GetItemWidget(selectedItems[x].row());
  5469. treeItem->setStyleSheet("");
  5470. treeItem->setProperty("bgColor", preset);
  5471. treeItem->style()->unpolish(treeItem);
  5472. treeItem->style()->polish(treeItem);
  5473. OBSSceneItem sceneItem = ui->sources->Get(
  5474. selectedItems[x].row());
  5475. obs_data_t *privData =
  5476. obs_sceneitem_get_private_settings(sceneItem);
  5477. obs_data_set_int(privData, "color-preset", preset + 1);
  5478. obs_data_set_string(privData, "color", "");
  5479. obs_data_release(privData);
  5480. }
  5481. for (int i = 1; i < 9; i++) {
  5482. stringstream button;
  5483. button << "preset" << i;
  5484. QPushButton *cButton = colorButton->parentWidget()
  5485. ->findChild<QPushButton *>(button.str().c_str());
  5486. cButton->setStyleSheet("border: 1px solid black");
  5487. }
  5488. colorButton->setStyleSheet("border: 2px solid black");
  5489. } else if (action) {
  5490. int preset = action->property("bgColor").value<int>();
  5491. if (preset == 1) {
  5492. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5493. SourceTreeItem *curTreeItem =
  5494. GetItemWidgetFromSceneItem(curSceneItem);
  5495. obs_data_t *curPrivData =
  5496. obs_sceneitem_get_private_settings(curSceneItem);
  5497. int oldPreset = obs_data_get_int(
  5498. curPrivData, "color-preset");
  5499. const QString oldSheet = curTreeItem->styleSheet();
  5500. auto liveChangeColor = [=](const QColor &color) {
  5501. if (color.isValid()) {
  5502. curTreeItem->setStyleSheet(
  5503. "background: "
  5504. + color.name(QColor::HexArgb));
  5505. }
  5506. };
  5507. auto changedColor = [=](const QColor &color) {
  5508. if (color.isValid()) {
  5509. ConfirmColor(ui->sources, color,
  5510. selectedItems);
  5511. }
  5512. };
  5513. auto rejected = [=]() {
  5514. if (oldPreset == 1) {
  5515. curTreeItem->setStyleSheet(oldSheet);
  5516. curTreeItem->setProperty("bgColor", 0);
  5517. } else if (oldPreset == 0) {
  5518. curTreeItem->setStyleSheet(
  5519. "background: none");
  5520. curTreeItem->setProperty("bgColor", 0);
  5521. } else {
  5522. curTreeItem->setStyleSheet("");
  5523. curTreeItem->setProperty("bgColor",
  5524. oldPreset - 1);
  5525. }
  5526. curTreeItem->style()->unpolish(curTreeItem);
  5527. curTreeItem->style()->polish(curTreeItem);
  5528. };
  5529. QColorDialog::ColorDialogOptions options =
  5530. QColorDialog::ShowAlphaChannel;
  5531. const char *oldColor = obs_data_get_string(curPrivData,
  5532. "color");
  5533. const char *customColor = *oldColor != 0 ? oldColor
  5534. : "#55FF0000";
  5535. #ifdef __APPLE__
  5536. options |= QColorDialog::DontUseNativeDialog;
  5537. #endif
  5538. QColorDialog *colorDialog = new QColorDialog(this);
  5539. colorDialog->setOptions(options);
  5540. colorDialog->setCurrentColor(
  5541. QColor(customColor));
  5542. connect(colorDialog, &QColorDialog::currentColorChanged,
  5543. liveChangeColor);
  5544. connect(colorDialog, &QColorDialog::colorSelected,
  5545. changedColor);
  5546. connect(colorDialog, &QColorDialog::rejected,
  5547. rejected);
  5548. colorDialog->open();
  5549. obs_data_release(curPrivData);
  5550. } else {
  5551. for (int x = 0; x < selectedItems.count(); x++) {
  5552. SourceTreeItem *treeItem = ui->sources
  5553. ->GetItemWidget(selectedItems[x].row());
  5554. treeItem->setStyleSheet("background: none");
  5555. treeItem->setProperty("bgColor", preset);
  5556. treeItem->style()->unpolish(treeItem);
  5557. treeItem->style()->polish(treeItem);
  5558. OBSSceneItem sceneItem = ui->sources->Get(
  5559. selectedItems[x].row());
  5560. obs_data_t *privData =
  5561. obs_sceneitem_get_private_settings(
  5562. sceneItem);
  5563. obs_data_set_int(privData, "color-preset",
  5564. preset);
  5565. obs_data_set_string(privData, "color", "");
  5566. obs_data_release(privData);
  5567. }
  5568. }
  5569. }
  5570. }
  5571. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(
  5572. obs_sceneitem_t *sceneItem)
  5573. {
  5574. int i = 0;
  5575. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  5576. OBSSceneItem item = ui->sources->Get(i);
  5577. int64_t id = obs_sceneitem_get_id(sceneItem);
  5578. while (treeItem && obs_sceneitem_get_id(item) != id) {
  5579. i++;
  5580. treeItem = ui->sources->GetItemWidget(i);
  5581. item = ui->sources->Get(i);
  5582. }
  5583. if(treeItem)
  5584. return treeItem;
  5585. return nullptr;
  5586. }
  5587. void OBSBasic::on_autoConfigure_triggered()
  5588. {
  5589. AutoConfig test(this);
  5590. test.setModal(true);
  5591. test.show();
  5592. test.exec();
  5593. }
  5594. void OBSBasic::on_stats_triggered()
  5595. {
  5596. if (!stats.isNull()) {
  5597. stats->show();
  5598. stats->raise();
  5599. return;
  5600. }
  5601. OBSBasicStats *statsDlg;
  5602. statsDlg = new OBSBasicStats(nullptr);
  5603. statsDlg->show();
  5604. stats = statsDlg;
  5605. }
  5606. void OBSBasic::on_actionShowAbout_triggered()
  5607. {
  5608. if (about)
  5609. about->close();
  5610. about = new OBSAbout(this);
  5611. about->show();
  5612. about->setAttribute(Qt::WA_DeleteOnClose, true);
  5613. }
  5614. void OBSBasic::ResizeOutputSizeOfSource()
  5615. {
  5616. if (ui->streamButton->isChecked() || ui->recordButton->isChecked() ||
  5617. (replayBufferButton && replayBufferButton->isChecked()))
  5618. return;
  5619. QMessageBox resize_output(this);
  5620. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") +
  5621. "\n\n" + QTStr("ResizeOutputSizeOfSource.Continue"));
  5622. QAbstractButton *Yes = resize_output.addButton(QTStr("Yes"),
  5623. QMessageBox::YesRole);
  5624. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  5625. resize_output.setIcon(QMessageBox::Warning);
  5626. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  5627. resize_output.exec();
  5628. if (resize_output.clickedButton() != Yes)
  5629. return;
  5630. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  5631. int width = obs_source_get_width(source);
  5632. int height = obs_source_get_height(source);
  5633. config_set_uint(basicConfig, "Video", "BaseCX", width);
  5634. config_set_uint(basicConfig, "Video", "BaseCY", height);
  5635. config_set_uint(basicConfig, "Video", "OutputCX", width);
  5636. config_set_uint(basicConfig, "Video", "OutputCY", height);
  5637. ResetVideo();
  5638. on_actionFitToScreen_triggered();
  5639. }
  5640. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  5641. {
  5642. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  5643. action->setCheckable(true);
  5644. assignDockToggle(dock, action);
  5645. extraDocks.push_back(dock);
  5646. bool lock = ui->lockUI->isChecked();
  5647. QDockWidget::DockWidgetFeatures features = lock
  5648. ? QDockWidget::NoDockWidgetFeatures
  5649. : QDockWidget::AllDockWidgetFeatures;
  5650. dock->setFeatures(features);
  5651. /* prune deleted docks */
  5652. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5653. if (!extraDocks[i]) {
  5654. extraDocks.removeAt(i);
  5655. }
  5656. }
  5657. return action;
  5658. }
  5659. OBSBasic *OBSBasic::Get()
  5660. {
  5661. return reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  5662. }
  5663. bool OBSBasic::StreamingActive()
  5664. {
  5665. if (!outputHandler)
  5666. return false;
  5667. return outputHandler->StreamingActive();
  5668. }
  5669. bool OBSBasic::RecordingActive()
  5670. {
  5671. if (!outputHandler)
  5672. return false;
  5673. return outputHandler->RecordingActive();
  5674. }
  5675. bool OBSBasic::ReplayBufferActive()
  5676. {
  5677. if (!outputHandler)
  5678. return false;
  5679. return outputHandler->ReplayBufferActive();
  5680. }