window-basic-main.cpp 185 KB

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