window-basic-main.cpp 192 KB

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