window-basic-main.cpp 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314
  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_unregister(forceStreamingStopHotkey);
  1798. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1799. obs_hotkey_unregister(transitionHotkey);
  1800. }
  1801. OBSBasic::~OBSBasic()
  1802. {
  1803. if (updateCheckThread && updateCheckThread->isRunning())
  1804. updateCheckThread->wait();
  1805. delete multiviewProjectorMenu;
  1806. delete previewProjector;
  1807. delete studioProgramProjector;
  1808. delete previewProjectorSource;
  1809. delete previewProjectorMain;
  1810. delete sourceProjector;
  1811. delete sceneProjectorMenu;
  1812. delete scaleFilteringMenu;
  1813. delete colorMenu;
  1814. delete colorWidgetAction;
  1815. delete colorSelect;
  1816. delete deinterlaceMenu;
  1817. delete perSceneTransitionMenu;
  1818. delete shortcutFilter;
  1819. delete trayMenu;
  1820. delete programOptions;
  1821. delete program;
  1822. /* XXX: any obs data must be released before calling obs_shutdown.
  1823. * currently, we can't automate this with C++ RAII because of the
  1824. * delicate nature of obs_shutdown needing to be freed before the UI
  1825. * can be freed, and we have no control over the destruction order of
  1826. * the Qt UI stuff, so we have to manually clear any references to
  1827. * libobs. */
  1828. delete cpuUsageTimer;
  1829. os_cpu_usage_info_destroy(cpuUsageInfo);
  1830. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1831. ClearHotkeys();
  1832. service = nullptr;
  1833. outputHandler.reset();
  1834. if (interaction)
  1835. delete interaction;
  1836. if (properties)
  1837. delete properties;
  1838. if (filters)
  1839. delete filters;
  1840. if (transformWindow)
  1841. delete transformWindow;
  1842. if (advAudioWindow)
  1843. delete advAudioWindow;
  1844. if (about)
  1845. delete about;
  1846. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1847. OBSBasic::RenderMain, this);
  1848. obs_enter_graphics();
  1849. gs_vertexbuffer_destroy(box);
  1850. gs_vertexbuffer_destroy(boxLeft);
  1851. gs_vertexbuffer_destroy(boxTop);
  1852. gs_vertexbuffer_destroy(boxRight);
  1853. gs_vertexbuffer_destroy(boxBottom);
  1854. gs_vertexbuffer_destroy(circle);
  1855. obs_leave_graphics();
  1856. /* When shutting down, sometimes source references can get in to the
  1857. * event queue, and if we don't forcibly process those events they
  1858. * won't get processed until after obs_shutdown has been called. I
  1859. * really wish there were a more elegant way to deal with this via C++,
  1860. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1861. * normal C++ behavior for your data to be freed in the order that you
  1862. * expect or want it to. */
  1863. QApplication::sendPostedEvents(this);
  1864. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1865. LIBOBS_API_VER);
  1866. #if OBS_RELEASE_CANDIDATE > 0
  1867. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  1868. OBS_RELEASE_CANDIDATE_VER);
  1869. #endif
  1870. bool alwaysOnTop = IsAlwaysOnTop(this);
  1871. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1872. previewEnabled);
  1873. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1874. alwaysOnTop);
  1875. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1876. "SceneDuplicationMode", sceneDuplicationMode);
  1877. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1878. "SwapScenesMode", swapScenesMode);
  1879. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1880. "EditPropertiesMode", editPropertiesMode);
  1881. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1882. "PreviewProgramMode", IsPreviewProgramMode());
  1883. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1884. "DocksLocked", ui->lockUI->isChecked());
  1885. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1886. #ifdef _WIN32
  1887. uint32_t winVer = GetWindowsVersion();
  1888. if (winVer > 0 && winVer < 0x602) {
  1889. bool disableAero = config_get_bool(basicConfig, "Video",
  1890. "DisableAero");
  1891. if (disableAero) {
  1892. SetAeroEnabled(true);
  1893. }
  1894. }
  1895. #endif
  1896. #ifdef BROWSER_AVAILABLE
  1897. DestroyPanelCookieManager();
  1898. delete cef;
  1899. cef = nullptr;
  1900. #endif
  1901. }
  1902. void OBSBasic::SaveProjectNow()
  1903. {
  1904. if (disableSaving)
  1905. return;
  1906. projectChanged = true;
  1907. SaveProjectDeferred();
  1908. }
  1909. void OBSBasic::SaveProject()
  1910. {
  1911. if (disableSaving)
  1912. return;
  1913. projectChanged = true;
  1914. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1915. Qt::QueuedConnection);
  1916. }
  1917. void OBSBasic::SaveProjectDeferred()
  1918. {
  1919. if (disableSaving)
  1920. return;
  1921. if (!projectChanged)
  1922. return;
  1923. projectChanged = false;
  1924. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1925. "Basic", "SceneCollectionFile");
  1926. char savePath[512];
  1927. char fileName[512];
  1928. int ret;
  1929. if (!sceneCollection)
  1930. return;
  1931. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1932. sceneCollection);
  1933. if (ret <= 0)
  1934. return;
  1935. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1936. if (ret <= 0)
  1937. return;
  1938. Save(savePath);
  1939. }
  1940. OBSSource OBSBasic::GetProgramSource()
  1941. {
  1942. return OBSGetStrongRef(programScene);
  1943. }
  1944. OBSScene OBSBasic::GetCurrentScene()
  1945. {
  1946. QListWidgetItem *item = ui->scenes->currentItem();
  1947. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1948. }
  1949. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1950. {
  1951. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1952. }
  1953. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1954. {
  1955. return ui->sources->Get(GetTopSelectedSourceItem());
  1956. }
  1957. void OBSBasic::UpdatePreviewScalingMenu()
  1958. {
  1959. bool fixedScaling = ui->preview->IsFixedScaling();
  1960. float scalingAmount = ui->preview->GetScalingAmount();
  1961. if (!fixedScaling) {
  1962. ui->actionScaleWindow->setChecked(true);
  1963. ui->actionScaleCanvas->setChecked(false);
  1964. ui->actionScaleOutput->setChecked(false);
  1965. return;
  1966. }
  1967. obs_video_info ovi;
  1968. obs_get_video_info(&ovi);
  1969. ui->actionScaleWindow->setChecked(false);
  1970. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1971. ui->actionScaleOutput->setChecked(
  1972. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1973. }
  1974. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1975. {
  1976. if (interaction)
  1977. interaction->close();
  1978. interaction = new OBSBasicInteraction(this, source);
  1979. interaction->Init();
  1980. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1981. }
  1982. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1983. {
  1984. if (properties)
  1985. properties->close();
  1986. properties = new OBSBasicProperties(this, source);
  1987. properties->Init();
  1988. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1989. }
  1990. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1991. {
  1992. if (filters)
  1993. filters->close();
  1994. filters = new OBSBasicFilters(this, source);
  1995. filters->Init();
  1996. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1997. }
  1998. /* Qt callbacks for invokeMethod */
  1999. void OBSBasic::AddScene(OBSSource source)
  2000. {
  2001. const char *name = obs_source_get_name(source);
  2002. obs_scene_t *scene = obs_scene_from_source(source);
  2003. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2004. SetOBSRef(item, OBSScene(scene));
  2005. ui->scenes->addItem(item);
  2006. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  2007. Str("Basic.Hotkeys.SelectScene"),
  2008. [](void *data,
  2009. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  2010. {
  2011. OBSBasic *main =
  2012. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  2013. auto potential_source = static_cast<obs_source_t*>(data);
  2014. auto source = obs_source_get_ref(potential_source);
  2015. if (source && pressed)
  2016. main->SetCurrentScene(source);
  2017. obs_source_release(source);
  2018. }, static_cast<obs_source_t*>(source));
  2019. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2020. SignalContainer<OBSScene> container;
  2021. container.ref = scene;
  2022. container.handlers.assign({
  2023. std::make_shared<OBSSignal>(handler, "item_add",
  2024. OBSBasic::SceneItemAdded, this),
  2025. std::make_shared<OBSSignal>(handler, "item_select",
  2026. OBSBasic::SceneItemSelected, this),
  2027. std::make_shared<OBSSignal>(handler, "item_deselect",
  2028. OBSBasic::SceneItemDeselected, this),
  2029. std::make_shared<OBSSignal>(handler, "reorder",
  2030. OBSBasic::SceneReordered, this),
  2031. });
  2032. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2033. QVariant::fromValue(container));
  2034. /* if the scene already has items (a duplicated scene) add them */
  2035. auto addSceneItem = [this] (obs_sceneitem_t *item)
  2036. {
  2037. AddSceneItem(item);
  2038. };
  2039. using addSceneItem_t = decltype(addSceneItem);
  2040. obs_scene_enum_items(scene,
  2041. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  2042. {
  2043. addSceneItem_t *func;
  2044. func = reinterpret_cast<addSceneItem_t*>(param);
  2045. (*func)(item);
  2046. return true;
  2047. }, &addSceneItem);
  2048. SaveProject();
  2049. if (!disableSaving) {
  2050. obs_source_t *source = obs_scene_get_source(scene);
  2051. blog(LOG_INFO, "User added scene '%s'",
  2052. obs_source_get_name(source));
  2053. OBSProjector::UpdateMultiviewProjectors();
  2054. }
  2055. if (api)
  2056. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2057. }
  2058. void OBSBasic::RemoveScene(OBSSource source)
  2059. {
  2060. obs_scene_t *scene = obs_scene_from_source(source);
  2061. QListWidgetItem *sel = nullptr;
  2062. int count = ui->scenes->count();
  2063. for (int i = 0; i < count; i++) {
  2064. auto item = ui->scenes->item(i);
  2065. auto cur_scene = GetOBSRef<OBSScene>(item);
  2066. if (cur_scene != scene)
  2067. continue;
  2068. sel = item;
  2069. break;
  2070. }
  2071. if (sel != nullptr) {
  2072. if (sel == ui->scenes->currentItem())
  2073. ui->sources->Clear();
  2074. delete sel;
  2075. }
  2076. SaveProject();
  2077. if (!disableSaving) {
  2078. blog(LOG_INFO, "User Removed scene '%s'",
  2079. obs_source_get_name(source));
  2080. OBSProjector::UpdateMultiviewProjectors();
  2081. }
  2082. if (api)
  2083. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2084. }
  2085. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2086. {
  2087. obs_sceneitem_t *selectedItem =
  2088. reinterpret_cast<obs_sceneitem_t*>(param);
  2089. if (obs_sceneitem_is_group(item))
  2090. obs_sceneitem_group_enum_items(item, select_one, param);
  2091. obs_sceneitem_select(item, (selectedItem == item));
  2092. UNUSED_PARAMETER(scene);
  2093. return true;
  2094. }
  2095. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2096. {
  2097. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2098. if (GetCurrentScene() == scene)
  2099. ui->sources->Add(item);
  2100. SaveProject();
  2101. if (!disableSaving) {
  2102. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2103. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2104. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2105. obs_source_get_name(itemSource),
  2106. obs_source_get_id(itemSource),
  2107. obs_source_get_name(sceneSource));
  2108. obs_scene_enum_items(scene, select_one, (obs_sceneitem_t*)item);
  2109. }
  2110. }
  2111. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2112. {
  2113. if (source) {
  2114. obs_scene_t *scene = obs_scene_from_source(source);
  2115. const char *name = obs_source_get_name(source);
  2116. if (!scene)
  2117. return;
  2118. QList<QListWidgetItem*> items =
  2119. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2120. if (items.count()) {
  2121. sceneChanging = true;
  2122. ui->scenes->setCurrentItem(items.first());
  2123. sceneChanging = false;
  2124. OBSScene curScene =
  2125. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2126. if (api && scene != curScene)
  2127. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2128. }
  2129. }
  2130. }
  2131. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2132. const QString &prevName)
  2133. {
  2134. QList<QListWidgetItem*> items =
  2135. listWidget->findItems(prevName, Qt::MatchExactly);
  2136. for (int i = 0; i < items.count(); i++)
  2137. items[i]->setText(newName);
  2138. }
  2139. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2140. QString prevName)
  2141. {
  2142. RenameListValues(ui->scenes, newName, prevName);
  2143. for (size_t i = 0; i < volumes.size(); i++) {
  2144. if (volumes[i]->GetName().compare(prevName) == 0)
  2145. volumes[i]->SetName(newName);
  2146. }
  2147. OBSProjector::RenameProjector(prevName, newName);
  2148. SaveProject();
  2149. obs_scene_t *scene = obs_scene_from_source(source);
  2150. if (scene)
  2151. OBSProjector::UpdateMultiviewProjectors();
  2152. }
  2153. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  2154. {
  2155. SignalBlocker sourcesSignalBlocker(ui->sources);
  2156. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  2157. return;
  2158. ui->sources->SelectItem(item, select);
  2159. }
  2160. static inline bool SourceMixerHidden(obs_source_t *source)
  2161. {
  2162. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2163. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2164. obs_data_release(priv_settings);
  2165. return hidden;
  2166. }
  2167. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2168. {
  2169. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2170. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2171. obs_data_release(priv_settings);
  2172. }
  2173. void OBSBasic::GetAudioSourceFilters()
  2174. {
  2175. QAction *action = reinterpret_cast<QAction*>(sender());
  2176. VolControl *vol = action->property("volControl").value<VolControl*>();
  2177. obs_source_t *source = vol->GetSource();
  2178. CreateFiltersWindow(source);
  2179. }
  2180. void OBSBasic::GetAudioSourceProperties()
  2181. {
  2182. QAction *action = reinterpret_cast<QAction*>(sender());
  2183. VolControl *vol = action->property("volControl").value<VolControl*>();
  2184. obs_source_t *source = vol->GetSource();
  2185. CreatePropertiesWindow(source);
  2186. }
  2187. void OBSBasic::HideAudioControl()
  2188. {
  2189. QAction *action = reinterpret_cast<QAction*>(sender());
  2190. VolControl *vol = action->property("volControl").value<VolControl*>();
  2191. obs_source_t *source = vol->GetSource();
  2192. if (!SourceMixerHidden(source)) {
  2193. SetSourceMixerHidden(source, true);
  2194. DeactivateAudioSource(source);
  2195. }
  2196. }
  2197. void OBSBasic::UnhideAllAudioControls()
  2198. {
  2199. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  2200. {
  2201. if (!obs_source_active(source))
  2202. return true;
  2203. if (!SourceMixerHidden(source))
  2204. return true;
  2205. SetSourceMixerHidden(source, false);
  2206. ActivateAudioSource(source);
  2207. return true;
  2208. };
  2209. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2210. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  2211. {
  2212. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2213. };
  2214. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2215. }
  2216. void OBSBasic::ToggleHideMixer()
  2217. {
  2218. OBSSceneItem item = GetCurrentSceneItem();
  2219. OBSSource source = obs_sceneitem_get_source(item);
  2220. if (!SourceMixerHidden(source)) {
  2221. SetSourceMixerHidden(source, true);
  2222. DeactivateAudioSource(source);
  2223. } else {
  2224. SetSourceMixerHidden(source, false);
  2225. ActivateAudioSource(source);
  2226. }
  2227. }
  2228. void OBSBasic::MixerRenameSource()
  2229. {
  2230. QAction *action = reinterpret_cast<QAction*>(sender());
  2231. VolControl *vol = action->property("volControl").value<VolControl*>();
  2232. OBSSource source = vol->GetSource();
  2233. const char *prevName = obs_source_get_name(source);
  2234. for (;;) {
  2235. string name;
  2236. bool accepted = NameDialog::AskForName(this,
  2237. QTStr("Basic.Main.MixerRename.Title"),
  2238. QTStr("Basic.Main.MixerRename.Text"),
  2239. name,
  2240. QT_UTF8(prevName));
  2241. if (!accepted)
  2242. return;
  2243. if (name.empty()) {
  2244. OBSMessageBox::warning(this,
  2245. QTStr("NoNameEntered.Title"),
  2246. QTStr("NoNameEntered.Text"));
  2247. continue;
  2248. }
  2249. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2250. obs_source_release(sourceTest);
  2251. if (sourceTest) {
  2252. OBSMessageBox::warning(this,
  2253. QTStr("NameExists.Title"),
  2254. QTStr("NameExists.Text"));
  2255. continue;
  2256. }
  2257. obs_source_set_name(source, name.c_str());
  2258. break;
  2259. }
  2260. }
  2261. void OBSBasic::VolControlContextMenu()
  2262. {
  2263. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  2264. /* ------------------- */
  2265. QAction hideAction(QTStr("Hide"), this);
  2266. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2267. QAction mixerRenameAction(QTStr("Rename"), this);
  2268. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2269. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2270. QAction filtersAction(QTStr("Filters"), this);
  2271. QAction propertiesAction(QTStr("Properties"), this);
  2272. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2273. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2274. toggleControlLayoutAction.setCheckable(true);
  2275. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2276. "BasicWindow", "VerticalVolControl"));
  2277. /* ------------------- */
  2278. connect(&hideAction, &QAction::triggered,
  2279. this, &OBSBasic::HideAudioControl,
  2280. Qt::DirectConnection);
  2281. connect(&unhideAllAction, &QAction::triggered,
  2282. this, &OBSBasic::UnhideAllAudioControls,
  2283. Qt::DirectConnection);
  2284. connect(&mixerRenameAction, &QAction::triggered,
  2285. this, &OBSBasic::MixerRenameSource,
  2286. Qt::DirectConnection);
  2287. connect(&copyFiltersAction, &QAction::triggered,
  2288. this, &OBSBasic::AudioMixerCopyFilters,
  2289. Qt::DirectConnection);
  2290. connect(&pasteFiltersAction, &QAction::triggered,
  2291. this, &OBSBasic::AudioMixerPasteFilters,
  2292. Qt::DirectConnection);
  2293. connect(&filtersAction, &QAction::triggered,
  2294. this, &OBSBasic::GetAudioSourceFilters,
  2295. Qt::DirectConnection);
  2296. connect(&propertiesAction, &QAction::triggered,
  2297. this, &OBSBasic::GetAudioSourceProperties,
  2298. Qt::DirectConnection);
  2299. connect(&advPropAction, &QAction::triggered,
  2300. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2301. Qt::DirectConnection);
  2302. /* ------------------- */
  2303. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2304. &OBSBasic::ToggleVolControlLayout,
  2305. Qt::DirectConnection);
  2306. /* ------------------- */
  2307. hideAction.setProperty("volControl",
  2308. QVariant::fromValue<VolControl*>(vol));
  2309. mixerRenameAction.setProperty("volControl",
  2310. QVariant::fromValue<VolControl*>(vol));
  2311. copyFiltersAction.setProperty("volControl",
  2312. QVariant::fromValue<VolControl*>(vol));
  2313. pasteFiltersAction.setProperty("volControl",
  2314. QVariant::fromValue<VolControl*>(vol));
  2315. filtersAction.setProperty("volControl",
  2316. QVariant::fromValue<VolControl*>(vol));
  2317. propertiesAction.setProperty("volControl",
  2318. QVariant::fromValue<VolControl*>(vol));
  2319. /* ------------------- */
  2320. if (copyFiltersString == nullptr)
  2321. pasteFiltersAction.setEnabled(false);
  2322. else
  2323. pasteFiltersAction.setEnabled(true);
  2324. QMenu popup;
  2325. popup.addAction(&unhideAllAction);
  2326. popup.addAction(&hideAction);
  2327. popup.addAction(&mixerRenameAction);
  2328. popup.addSeparator();
  2329. popup.addAction(&copyFiltersAction);
  2330. popup.addAction(&pasteFiltersAction);
  2331. popup.addSeparator();
  2332. popup.addAction(&toggleControlLayoutAction);
  2333. popup.addSeparator();
  2334. popup.addAction(&filtersAction);
  2335. popup.addAction(&propertiesAction);
  2336. popup.addAction(&advPropAction);
  2337. popup.exec(QCursor::pos());
  2338. }
  2339. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2340. {
  2341. StackedMixerAreaContextMenuRequested();
  2342. }
  2343. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2344. {
  2345. StackedMixerAreaContextMenuRequested();
  2346. }
  2347. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2348. {
  2349. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2350. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2351. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2352. toggleControlLayoutAction.setCheckable(true);
  2353. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2354. "BasicWindow", "VerticalVolControl"));
  2355. /* ------------------- */
  2356. connect(&unhideAllAction, &QAction::triggered,
  2357. this, &OBSBasic::UnhideAllAudioControls,
  2358. Qt::DirectConnection);
  2359. connect(&advPropAction, &QAction::triggered,
  2360. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2361. Qt::DirectConnection);
  2362. /* ------------------- */
  2363. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2364. &OBSBasic::ToggleVolControlLayout,
  2365. Qt::DirectConnection);
  2366. /* ------------------- */
  2367. QMenu popup;
  2368. popup.addAction(&unhideAllAction);
  2369. popup.addSeparator();
  2370. popup.addAction(&toggleControlLayoutAction);
  2371. popup.addSeparator();
  2372. popup.addAction(&advPropAction);
  2373. popup.exec(QCursor::pos());
  2374. }
  2375. void OBSBasic::ToggleMixerLayout(bool vertical)
  2376. {
  2377. if (vertical) {
  2378. ui->stackedMixerArea->setMinimumSize(180, 220);
  2379. ui->stackedMixerArea->setCurrentIndex(1);
  2380. } else {
  2381. ui->stackedMixerArea->setMinimumSize(220, 0);
  2382. ui->stackedMixerArea->setCurrentIndex(0);
  2383. }
  2384. }
  2385. void OBSBasic::ToggleVolControlLayout()
  2386. {
  2387. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2388. "VerticalVolControl");
  2389. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2390. vertical);
  2391. ToggleMixerLayout(vertical);
  2392. // We need to store it so we can delete current and then add
  2393. // at the right order
  2394. vector<OBSSource> sources;
  2395. for (size_t i = 0; i != volumes.size(); i++)
  2396. sources.emplace_back(volumes[i]->GetSource());
  2397. ClearVolumeControls();
  2398. for (const auto &source : sources)
  2399. ActivateAudioSource(source);
  2400. }
  2401. void OBSBasic::ActivateAudioSource(OBSSource source)
  2402. {
  2403. if (SourceMixerHidden(source))
  2404. return;
  2405. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2406. "VerticalVolControl");
  2407. VolControl *vol = new VolControl(source, true, vertical);
  2408. double meterDecayRate = config_get_double(basicConfig, "Audio",
  2409. "MeterDecayRate");
  2410. vol->SetMeterDecayRate(meterDecayRate);
  2411. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  2412. "PeakMeterType");
  2413. enum obs_peak_meter_type peakMeterType;
  2414. switch (peakMeterTypeIdx) {
  2415. case 0:
  2416. peakMeterType = SAMPLE_PEAK_METER;
  2417. break;
  2418. case 1:
  2419. peakMeterType = TRUE_PEAK_METER;
  2420. break;
  2421. default:
  2422. peakMeterType = SAMPLE_PEAK_METER;
  2423. break;
  2424. }
  2425. vol->setPeakMeterType(peakMeterType);
  2426. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2427. connect(vol, &QWidget::customContextMenuRequested,
  2428. this, &OBSBasic::VolControlContextMenu);
  2429. connect(vol, &VolControl::ConfigClicked,
  2430. this, &OBSBasic::VolControlContextMenu);
  2431. InsertQObjectByName(volumes, vol);
  2432. for (auto volume : volumes) {
  2433. if (vertical)
  2434. ui->vVolControlLayout->addWidget(volume);
  2435. else
  2436. ui->hVolControlLayout->addWidget(volume);
  2437. }
  2438. }
  2439. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2440. {
  2441. for (size_t i = 0; i < volumes.size(); i++) {
  2442. if (volumes[i]->GetSource() == source) {
  2443. delete volumes[i];
  2444. volumes.erase(volumes.begin() + i);
  2445. break;
  2446. }
  2447. }
  2448. }
  2449. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2450. {
  2451. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2452. !obs_source_is_group(source)) {
  2453. int count = ui->scenes->count();
  2454. if (count == 1) {
  2455. OBSMessageBox::information(this,
  2456. QTStr("FinalScene.Title"),
  2457. QTStr("FinalScene.Text"));
  2458. return false;
  2459. }
  2460. }
  2461. const char *name = obs_source_get_name(source);
  2462. QString text = QTStr("ConfirmRemove.Text");
  2463. text.replace("$1", QT_UTF8(name));
  2464. QMessageBox remove_source(this);
  2465. remove_source.setText(text);
  2466. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  2467. QMessageBox::YesRole);
  2468. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2469. remove_source.setIcon(QMessageBox::Question);
  2470. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2471. remove_source.exec();
  2472. return Yes == remove_source.clickedButton();
  2473. }
  2474. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  2475. #ifdef UPDATE_SPARKLE
  2476. void init_sparkle_updater(bool update_to_undeployed);
  2477. void trigger_sparkle_update();
  2478. #endif
  2479. void OBSBasic::TimedCheckForUpdates()
  2480. {
  2481. if (!config_get_bool(App()->GlobalConfig(), "General",
  2482. "EnableAutoUpdates"))
  2483. return;
  2484. #ifdef UPDATE_SPARKLE
  2485. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2486. "UpdateToUndeployed"));
  2487. #elif _WIN32
  2488. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2489. "LastUpdateCheck");
  2490. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  2491. "LastVersion");
  2492. if (lastVersion < LIBOBS_API_VER) {
  2493. lastUpdate = 0;
  2494. config_set_int(App()->GlobalConfig(), "General",
  2495. "LastUpdateCheck", 0);
  2496. }
  2497. long long t = (long long)time(nullptr);
  2498. long long secs = t - lastUpdate;
  2499. if (secs > UPDATE_CHECK_INTERVAL)
  2500. CheckForUpdates(false);
  2501. #endif
  2502. }
  2503. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2504. {
  2505. #ifdef UPDATE_SPARKLE
  2506. trigger_sparkle_update();
  2507. #elif _WIN32
  2508. ui->actionCheckForUpdates->setEnabled(false);
  2509. if (updateCheckThread && updateCheckThread->isRunning())
  2510. return;
  2511. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2512. updateCheckThread->start();
  2513. #endif
  2514. UNUSED_PARAMETER(manualUpdate);
  2515. }
  2516. void OBSBasic::updateCheckFinished()
  2517. {
  2518. ui->actionCheckForUpdates->setEnabled(true);
  2519. }
  2520. void OBSBasic::DuplicateSelectedScene()
  2521. {
  2522. OBSScene curScene = GetCurrentScene();
  2523. if (!curScene)
  2524. return;
  2525. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2526. QString format{obs_source_get_name(curSceneSource)};
  2527. format += " %1";
  2528. int i = 2;
  2529. QString placeHolderText = format.arg(i);
  2530. obs_source_t *source = nullptr;
  2531. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2532. obs_source_release(source);
  2533. placeHolderText = format.arg(++i);
  2534. }
  2535. for (;;) {
  2536. string name;
  2537. bool accepted = NameDialog::AskForName(this,
  2538. QTStr("Basic.Main.AddSceneDlg.Title"),
  2539. QTStr("Basic.Main.AddSceneDlg.Text"),
  2540. name,
  2541. placeHolderText);
  2542. if (!accepted)
  2543. return;
  2544. if (name.empty()) {
  2545. OBSMessageBox::warning(this,
  2546. QTStr("NoNameEntered.Title"),
  2547. QTStr("NoNameEntered.Text"));
  2548. continue;
  2549. }
  2550. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2551. if (source) {
  2552. OBSMessageBox::warning(this,
  2553. QTStr("NameExists.Title"),
  2554. QTStr("NameExists.Text"));
  2555. obs_source_release(source);
  2556. continue;
  2557. }
  2558. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2559. name.c_str(), OBS_SCENE_DUP_REFS);
  2560. source = obs_scene_get_source(scene);
  2561. SetCurrentScene(source, true);
  2562. obs_scene_release(scene);
  2563. break;
  2564. }
  2565. }
  2566. void OBSBasic::RemoveSelectedScene()
  2567. {
  2568. OBSScene scene = GetCurrentScene();
  2569. if (scene) {
  2570. obs_source_t *source = obs_scene_get_source(scene);
  2571. if (QueryRemoveSource(source)) {
  2572. obs_source_remove(source);
  2573. if (api)
  2574. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2575. }
  2576. }
  2577. }
  2578. void OBSBasic::RemoveSelectedSceneItem()
  2579. {
  2580. OBSSceneItem item = GetCurrentSceneItem();
  2581. if (item) {
  2582. obs_source_t *source = obs_sceneitem_get_source(item);
  2583. if (QueryRemoveSource(source))
  2584. obs_sceneitem_remove(item);
  2585. }
  2586. }
  2587. void OBSBasic::ReorderSources(OBSScene scene)
  2588. {
  2589. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2590. return;
  2591. ui->sources->ReorderItems();
  2592. SaveProject();
  2593. }
  2594. /* OBS Callbacks */
  2595. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2596. {
  2597. OBSBasic *window = static_cast<OBSBasic*>(data);
  2598. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2599. QMetaObject::invokeMethod(window, "ReorderSources",
  2600. Q_ARG(OBSScene, OBSScene(scene)));
  2601. }
  2602. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2603. {
  2604. OBSBasic *window = static_cast<OBSBasic*>(data);
  2605. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2606. QMetaObject::invokeMethod(window, "AddSceneItem",
  2607. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2608. }
  2609. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2610. {
  2611. OBSBasic *window = static_cast<OBSBasic*>(data);
  2612. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2613. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2614. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2615. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2616. Q_ARG(bool, true));
  2617. }
  2618. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2619. {
  2620. OBSBasic *window = static_cast<OBSBasic*>(data);
  2621. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2622. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2623. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2624. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2625. Q_ARG(bool, false));
  2626. }
  2627. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2628. {
  2629. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2630. if (obs_scene_from_source(source) != NULL)
  2631. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2632. "AddScene", WaitConnection(),
  2633. Q_ARG(OBSSource, OBSSource(source)));
  2634. }
  2635. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2636. {
  2637. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2638. if (obs_scene_from_source(source) != NULL)
  2639. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2640. "RemoveScene",
  2641. Q_ARG(OBSSource, OBSSource(source)));
  2642. }
  2643. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2644. {
  2645. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2646. uint32_t flags = obs_source_get_output_flags(source);
  2647. if (flags & OBS_SOURCE_AUDIO)
  2648. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2649. "ActivateAudioSource",
  2650. Q_ARG(OBSSource, OBSSource(source)));
  2651. }
  2652. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2653. {
  2654. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2655. uint32_t flags = obs_source_get_output_flags(source);
  2656. if (flags & OBS_SOURCE_AUDIO)
  2657. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2658. "DeactivateAudioSource",
  2659. Q_ARG(OBSSource, OBSSource(source)));
  2660. }
  2661. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2662. {
  2663. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2664. const char *newName = calldata_string(params, "new_name");
  2665. const char *prevName = calldata_string(params, "prev_name");
  2666. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2667. "RenameSources",
  2668. Q_ARG(OBSSource, source),
  2669. Q_ARG(QString, QT_UTF8(newName)),
  2670. Q_ARG(QString, QT_UTF8(prevName)));
  2671. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2672. }
  2673. void OBSBasic::DrawBackdrop(float cx, float cy)
  2674. {
  2675. if (!box)
  2676. return;
  2677. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  2678. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2679. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2680. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2681. vec4 colorVal;
  2682. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2683. gs_effect_set_vec4(color, &colorVal);
  2684. gs_technique_begin(tech);
  2685. gs_technique_begin_pass(tech, 0);
  2686. gs_matrix_push();
  2687. gs_matrix_identity();
  2688. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2689. gs_load_vertexbuffer(box);
  2690. gs_draw(GS_TRISTRIP, 0, 0);
  2691. gs_matrix_pop();
  2692. gs_technique_end_pass(tech);
  2693. gs_technique_end(tech);
  2694. gs_load_vertexbuffer(nullptr);
  2695. GS_DEBUG_MARKER_END();
  2696. }
  2697. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2698. {
  2699. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  2700. OBSBasic *window = static_cast<OBSBasic*>(data);
  2701. obs_video_info ovi;
  2702. obs_get_video_info(&ovi);
  2703. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2704. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2705. gs_viewport_push();
  2706. gs_projection_push();
  2707. QSize previewSize = GetPixelSize(window->ui->preview);
  2708. float right = float(previewSize.width()) - window->previewX;
  2709. float bottom = float(previewSize.height()) - window->previewY;
  2710. gs_ortho(-window->previewX, right,
  2711. -window->previewY, bottom,
  2712. -100.0f, 100.0f);
  2713. window->ui->preview->DrawOverflow();
  2714. /* --------------------------------------- */
  2715. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2716. -100.0f, 100.0f);
  2717. gs_set_viewport(window->previewX, window->previewY,
  2718. window->previewCX, window->previewCY);
  2719. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2720. if (window->IsPreviewProgramMode()) {
  2721. OBSScene scene = window->GetCurrentScene();
  2722. obs_source_t *source = obs_scene_get_source(scene);
  2723. if (source)
  2724. obs_source_video_render(source);
  2725. } else {
  2726. obs_render_main_texture();
  2727. }
  2728. gs_load_vertexbuffer(nullptr);
  2729. /* --------------------------------------- */
  2730. gs_ortho(-window->previewX, right,
  2731. -window->previewY, bottom,
  2732. -100.0f, 100.0f);
  2733. gs_reset_viewport();
  2734. window->ui->preview->DrawSceneEditing();
  2735. /* --------------------------------------- */
  2736. gs_projection_pop();
  2737. gs_viewport_pop();
  2738. GS_DEBUG_MARKER_END();
  2739. UNUSED_PARAMETER(cx);
  2740. UNUSED_PARAMETER(cy);
  2741. }
  2742. /* Main class functions */
  2743. obs_service_t *OBSBasic::GetService()
  2744. {
  2745. if (!service) {
  2746. service = obs_service_create("rtmp_common", NULL, NULL,
  2747. nullptr);
  2748. obs_service_release(service);
  2749. }
  2750. return service;
  2751. }
  2752. void OBSBasic::SetService(obs_service_t *newService)
  2753. {
  2754. if (newService)
  2755. service = newService;
  2756. }
  2757. bool OBSBasic::StreamingActive() const
  2758. {
  2759. if (!outputHandler)
  2760. return false;
  2761. return outputHandler->StreamingActive();
  2762. }
  2763. bool OBSBasic::Active() const
  2764. {
  2765. if (!outputHandler)
  2766. return false;
  2767. return outputHandler->Active();
  2768. }
  2769. #ifdef _WIN32
  2770. #define IS_WIN32 1
  2771. #else
  2772. #define IS_WIN32 0
  2773. #endif
  2774. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2775. {
  2776. return obs_reset_video(ovi);
  2777. }
  2778. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2779. {
  2780. const char *scaleTypeStr = config_get_string(basicConfig,
  2781. "Video", "ScaleType");
  2782. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2783. return OBS_SCALE_BILINEAR;
  2784. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2785. return OBS_SCALE_LANCZOS;
  2786. else
  2787. return OBS_SCALE_BICUBIC;
  2788. }
  2789. static inline enum video_format GetVideoFormatFromName(const char *name)
  2790. {
  2791. if (astrcmpi(name, "I420") == 0)
  2792. return VIDEO_FORMAT_I420;
  2793. else if (astrcmpi(name, "NV12") == 0)
  2794. return VIDEO_FORMAT_NV12;
  2795. else if (astrcmpi(name, "I444") == 0)
  2796. return VIDEO_FORMAT_I444;
  2797. #if 0 //currently unsupported
  2798. else if (astrcmpi(name, "YVYU") == 0)
  2799. return VIDEO_FORMAT_YVYU;
  2800. else if (astrcmpi(name, "YUY2") == 0)
  2801. return VIDEO_FORMAT_YUY2;
  2802. else if (astrcmpi(name, "UYVY") == 0)
  2803. return VIDEO_FORMAT_UYVY;
  2804. #endif
  2805. else
  2806. return VIDEO_FORMAT_RGBA;
  2807. }
  2808. void OBSBasic::ResetUI()
  2809. {
  2810. bool studioPortraitLayout = config_get_bool(GetGlobalConfig(),
  2811. "BasicWindow", "StudioPortraitLayout");
  2812. bool labels = config_get_bool(GetGlobalConfig(),
  2813. "BasicWindow", "StudioModeLabels");
  2814. if (studioPortraitLayout)
  2815. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2816. else
  2817. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2818. if (previewProgramMode)
  2819. ui->previewLabel->setHidden(!labels);
  2820. if (programLabel)
  2821. programLabel->setHidden(!labels);
  2822. }
  2823. int OBSBasic::ResetVideo()
  2824. {
  2825. if (outputHandler && outputHandler->Active())
  2826. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2827. ProfileScope("OBSBasic::ResetVideo");
  2828. struct obs_video_info ovi;
  2829. int ret;
  2830. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2831. const char *colorFormat = config_get_string(basicConfig, "Video",
  2832. "ColorFormat");
  2833. const char *colorSpace = config_get_string(basicConfig, "Video",
  2834. "ColorSpace");
  2835. const char *colorRange = config_get_string(basicConfig, "Video",
  2836. "ColorRange");
  2837. ovi.graphics_module = App()->GetRenderModule();
  2838. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2839. "Video", "BaseCX");
  2840. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2841. "Video", "BaseCY");
  2842. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2843. "Video", "OutputCX");
  2844. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2845. "Video", "OutputCY");
  2846. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2847. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2848. VIDEO_CS_601 : VIDEO_CS_709;
  2849. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2850. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2851. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2852. "Video", "AdapterIdx");
  2853. ovi.gpu_conversion = true;
  2854. ovi.scale_type = GetScaleType(basicConfig);
  2855. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2856. ovi.base_width = 1920;
  2857. ovi.base_height = 1080;
  2858. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2859. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2860. }
  2861. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2862. ovi.output_width = ovi.base_width;
  2863. ovi.output_height = ovi.base_height;
  2864. config_set_uint(basicConfig, "Video", "OutputCX",
  2865. ovi.base_width);
  2866. config_set_uint(basicConfig, "Video", "OutputCY",
  2867. ovi.base_height);
  2868. }
  2869. ret = AttemptToResetVideo(&ovi);
  2870. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2871. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2872. blog(LOG_WARNING, "Tried to reset when "
  2873. "already active");
  2874. return ret;
  2875. }
  2876. /* Try OpenGL if DirectX fails on windows */
  2877. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2878. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2879. "with graphics_module='%s', retrying "
  2880. "with graphics_module='%s'",
  2881. ret, ovi.graphics_module,
  2882. DL_OPENGL);
  2883. ovi.graphics_module = DL_OPENGL;
  2884. ret = AttemptToResetVideo(&ovi);
  2885. }
  2886. } else if (ret == OBS_VIDEO_SUCCESS) {
  2887. ResizePreview(ovi.base_width, ovi.base_height);
  2888. if (program)
  2889. ResizeProgram(ovi.base_width, ovi.base_height);
  2890. }
  2891. if (ret == OBS_VIDEO_SUCCESS) {
  2892. OBSBasicStats::InitializeValues();
  2893. OBSProjector::UpdateMultiviewProjectors();
  2894. }
  2895. return ret;
  2896. }
  2897. bool OBSBasic::ResetAudio()
  2898. {
  2899. ProfileScope("OBSBasic::ResetAudio");
  2900. struct obs_audio_info ai;
  2901. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2902. "SampleRate");
  2903. const char *channelSetupStr = config_get_string(basicConfig,
  2904. "Audio", "ChannelSetup");
  2905. if (strcmp(channelSetupStr, "Mono") == 0)
  2906. ai.speakers = SPEAKERS_MONO;
  2907. else if (strcmp(channelSetupStr, "2.1") == 0)
  2908. ai.speakers = SPEAKERS_2POINT1;
  2909. else if (strcmp(channelSetupStr, "4.0") == 0)
  2910. ai.speakers = SPEAKERS_4POINT0;
  2911. else if (strcmp(channelSetupStr, "4.1") == 0)
  2912. ai.speakers = SPEAKERS_4POINT1;
  2913. else if (strcmp(channelSetupStr, "5.1") == 0)
  2914. ai.speakers = SPEAKERS_5POINT1;
  2915. else if (strcmp(channelSetupStr, "7.1") == 0)
  2916. ai.speakers = SPEAKERS_7POINT1;
  2917. else
  2918. ai.speakers = SPEAKERS_STEREO;
  2919. return obs_reset_audio(&ai);
  2920. }
  2921. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2922. const char *deviceDesc, int channel)
  2923. {
  2924. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2925. obs_source_t *source;
  2926. obs_data_t *settings;
  2927. source = obs_get_output_source(channel);
  2928. if (source) {
  2929. if (disable) {
  2930. obs_set_output_source(channel, nullptr);
  2931. } else {
  2932. settings = obs_source_get_settings(source);
  2933. const char *oldId = obs_data_get_string(settings,
  2934. "device_id");
  2935. if (strcmp(oldId, deviceId) != 0) {
  2936. obs_data_set_string(settings, "device_id",
  2937. deviceId);
  2938. obs_source_update(source, settings);
  2939. }
  2940. obs_data_release(settings);
  2941. }
  2942. obs_source_release(source);
  2943. } else if (!disable) {
  2944. settings = obs_data_create();
  2945. obs_data_set_string(settings, "device_id", deviceId);
  2946. source = obs_source_create(sourceId, deviceDesc, settings,
  2947. nullptr);
  2948. obs_data_release(settings);
  2949. obs_set_output_source(channel, source);
  2950. obs_source_release(source);
  2951. }
  2952. }
  2953. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2954. {
  2955. QSize targetSize;
  2956. bool isFixedScaling;
  2957. obs_video_info ovi;
  2958. /* resize preview panel to fix to the top section of the window */
  2959. targetSize = GetPixelSize(ui->preview);
  2960. isFixedScaling = ui->preview->IsFixedScaling();
  2961. obs_get_video_info(&ovi);
  2962. if (isFixedScaling) {
  2963. previewScale = ui->preview->GetScalingAmount();
  2964. GetCenterPosFromFixedScale(int(cx), int(cy),
  2965. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2966. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2967. previewX, previewY, previewScale);
  2968. previewX += ui->preview->GetScrollX();
  2969. previewY += ui->preview->GetScrollY();
  2970. } else {
  2971. GetScaleAndCenterPos(int(cx), int(cy),
  2972. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2973. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2974. previewX, previewY, previewScale);
  2975. }
  2976. previewX += float(PREVIEW_EDGE_SIZE);
  2977. previewY += float(PREVIEW_EDGE_SIZE);
  2978. }
  2979. void OBSBasic::CloseDialogs()
  2980. {
  2981. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2982. if (!childDialogs.isEmpty()) {
  2983. for (int i = 0; i < childDialogs.size(); ++i) {
  2984. childDialogs.at(i)->close();
  2985. }
  2986. }
  2987. for (QPointer<QWidget> &projector : windowProjectors) {
  2988. delete projector;
  2989. projector.clear();
  2990. }
  2991. for (QPointer<QWidget> &projector : projectors) {
  2992. delete projector;
  2993. projector.clear();
  2994. }
  2995. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2996. if (!remux.isNull()) remux->close();
  2997. }
  2998. void OBSBasic::EnumDialogs()
  2999. {
  3000. visDialogs.clear();
  3001. modalDialogs.clear();
  3002. visMsgBoxes.clear();
  3003. /* fill list of Visible dialogs and Modal dialogs */
  3004. QList<QDialog*> dialogs = findChildren<QDialog*>();
  3005. for (QDialog *dialog : dialogs) {
  3006. if (dialog->isVisible())
  3007. visDialogs.append(dialog);
  3008. if (dialog->isModal())
  3009. modalDialogs.append(dialog);
  3010. }
  3011. /* fill list of Visible message boxes */
  3012. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  3013. for (QMessageBox *msgbox : msgBoxes) {
  3014. if (msgbox->isVisible())
  3015. visMsgBoxes.append(msgbox);
  3016. }
  3017. }
  3018. void OBSBasic::ClearSceneData()
  3019. {
  3020. disableSaving++;
  3021. CloseDialogs();
  3022. ClearVolumeControls();
  3023. ClearListItems(ui->scenes);
  3024. ui->sources->Clear();
  3025. ClearQuickTransitions();
  3026. ui->transitions->clear();
  3027. obs_set_output_source(0, nullptr);
  3028. obs_set_output_source(1, nullptr);
  3029. obs_set_output_source(2, nullptr);
  3030. obs_set_output_source(3, nullptr);
  3031. obs_set_output_source(4, nullptr);
  3032. obs_set_output_source(5, nullptr);
  3033. lastScene = nullptr;
  3034. swapScene = nullptr;
  3035. programScene = nullptr;
  3036. auto cb = [](void *unused, obs_source_t *source)
  3037. {
  3038. obs_source_remove(source);
  3039. UNUSED_PARAMETER(unused);
  3040. return true;
  3041. };
  3042. obs_enum_sources(cb, nullptr);
  3043. if (api)
  3044. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3045. disableSaving--;
  3046. blog(LOG_INFO, "All scene data cleared");
  3047. blog(LOG_INFO, "------------------------------------------------");
  3048. }
  3049. void OBSBasic::closeEvent(QCloseEvent *event)
  3050. {
  3051. /* Do not close window if inside of a temporary event loop because we
  3052. * could be inside of an Auth::LoadUI call. Keep trying once per
  3053. * second until we've exit any known sub-loops. */
  3054. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3055. QTimer::singleShot(1000, this, SLOT(close()));
  3056. event->ignore();
  3057. return;
  3058. }
  3059. if (isVisible())
  3060. config_set_string(App()->GlobalConfig(),
  3061. "BasicWindow", "geometry",
  3062. saveGeometry().toBase64().constData());
  3063. if (outputHandler && outputHandler->Active()) {
  3064. SetShowing(true);
  3065. QMessageBox::StandardButton button = OBSMessageBox::question(
  3066. this, QTStr("ConfirmExit.Title"),
  3067. QTStr("ConfirmExit.Text"));
  3068. if (button == QMessageBox::No) {
  3069. event->ignore();
  3070. return;
  3071. }
  3072. }
  3073. QWidget::closeEvent(event);
  3074. if (!event->isAccepted())
  3075. return;
  3076. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3077. if (introCheckThread)
  3078. introCheckThread->wait();
  3079. if (updateCheckThread)
  3080. updateCheckThread->wait();
  3081. if (logUploadThread)
  3082. logUploadThread->wait();
  3083. signalHandlers.clear();
  3084. Auth::Save();
  3085. SaveProjectNow();
  3086. auth.reset();
  3087. config_set_string(App()->GlobalConfig(),
  3088. "BasicWindow", "DockState",
  3089. saveState().toBase64().constData());
  3090. if (api)
  3091. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3092. disableSaving++;
  3093. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3094. * sources, etc) so that all references are released before shutdown */
  3095. ClearSceneData();
  3096. App()->quit();
  3097. }
  3098. void OBSBasic::changeEvent(QEvent *event)
  3099. {
  3100. if (event->type() == QEvent::WindowStateChange &&
  3101. isMinimized() &&
  3102. trayIcon &&
  3103. trayIcon->isVisible() &&
  3104. sysTrayMinimizeToTray()) {
  3105. ToggleShowHide();
  3106. }
  3107. }
  3108. void OBSBasic::on_actionShow_Recordings_triggered()
  3109. {
  3110. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3111. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3112. const char *adv_path = strcmp(type, "Standard") ?
  3113. config_get_string(basicConfig, "AdvOut", "FFFilePath") :
  3114. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3115. const char *path = strcmp(mode, "Advanced") ?
  3116. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3117. adv_path;
  3118. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3119. }
  3120. void OBSBasic::on_actionRemux_triggered()
  3121. {
  3122. if (!remux.isNull()) {
  3123. remux->show();
  3124. remux->raise();
  3125. return;
  3126. }
  3127. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3128. const char *path = strcmp(mode, "Advanced") ?
  3129. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3130. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3131. OBSRemux *remuxDlg;
  3132. remuxDlg = new OBSRemux(path, this);
  3133. remuxDlg->show();
  3134. remux = remuxDlg;
  3135. }
  3136. void OBSBasic::on_action_Settings_triggered()
  3137. {
  3138. static bool settings_already_executing = false;
  3139. /* Do not load settings window if inside of a temporary event loop
  3140. * because we could be inside of an Auth::LoadUI call. Keep trying
  3141. * once per second until we've exit any known sub-loops. */
  3142. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3143. QTimer::singleShot(1000, this,
  3144. SLOT(on_action_Settings_triggered()));
  3145. return;
  3146. }
  3147. if (settings_already_executing) {
  3148. return;
  3149. }
  3150. settings_already_executing = true;
  3151. OBSBasicSettings settings(this);
  3152. settings.exec();
  3153. SystemTray(false);
  3154. settings_already_executing = false;
  3155. }
  3156. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3157. {
  3158. if (advAudioWindow != nullptr) {
  3159. advAudioWindow->raise();
  3160. return;
  3161. }
  3162. advAudioWindow = new OBSBasicAdvAudio(this);
  3163. advAudioWindow->show();
  3164. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3165. connect(advAudioWindow, SIGNAL(destroyed()),
  3166. this, SLOT(on_advAudioProps_destroyed()));
  3167. }
  3168. void OBSBasic::on_advAudioProps_clicked()
  3169. {
  3170. on_actionAdvAudioProperties_triggered();
  3171. }
  3172. void OBSBasic::on_advAudioProps_destroyed()
  3173. {
  3174. advAudioWindow = nullptr;
  3175. }
  3176. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3177. QListWidgetItem *prev)
  3178. {
  3179. obs_source_t *source = NULL;
  3180. if (sceneChanging)
  3181. return;
  3182. if (current) {
  3183. obs_scene_t *scene;
  3184. scene = GetOBSRef<OBSScene>(current);
  3185. source = obs_scene_get_source(scene);
  3186. }
  3187. SetCurrentScene(source);
  3188. if (api)
  3189. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3190. UNUSED_PARAMETER(prev);
  3191. }
  3192. void OBSBasic::EditSceneName()
  3193. {
  3194. QListWidgetItem *item = ui->scenes->currentItem();
  3195. Qt::ItemFlags flags = item->flags();
  3196. item->setFlags(flags | Qt::ItemIsEditable);
  3197. ui->scenes->editItem(item);
  3198. item->setFlags(flags);
  3199. }
  3200. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3201. const char *slot)
  3202. {
  3203. QAction *action;
  3204. QList<QScreen*> screens = QGuiApplication::screens();
  3205. for (int i = 0; i < screens.size(); i++) {
  3206. QRect screenGeometry = screens[i]->geometry();
  3207. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  3208. arg(QTStr("Display"),
  3209. QString::number(i + 1),
  3210. QString::number(screenGeometry.width()),
  3211. QString::number(screenGeometry.height()),
  3212. QString::number(screenGeometry.x()),
  3213. QString::number(screenGeometry.y()));
  3214. action = parent->addAction(str, target, slot);
  3215. action->setProperty("monitor", i);
  3216. }
  3217. }
  3218. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3219. {
  3220. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3221. QMenu popup(this);
  3222. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3223. popup.addAction(QTStr("Add"),
  3224. this, SLOT(on_actionAddScene_triggered()));
  3225. if (item) {
  3226. QAction *pasteFilters = new QAction(
  3227. QTStr("Paste.Filters"), this);
  3228. pasteFilters->setEnabled(copyFiltersString);
  3229. connect(pasteFilters, SIGNAL(triggered()), this,
  3230. SLOT(ScenePasteFilters()));
  3231. popup.addSeparator();
  3232. popup.addAction(QTStr("Duplicate"),
  3233. this, SLOT(DuplicateSelectedScene()));
  3234. popup.addAction(QTStr("Copy.Filters"),
  3235. this, SLOT(SceneCopyFilters()));
  3236. popup.addAction(pasteFilters);
  3237. popup.addSeparator();
  3238. popup.addAction(QTStr("Rename"),
  3239. this, SLOT(EditSceneName()));
  3240. popup.addAction(QTStr("Remove"),
  3241. this, SLOT(RemoveSelectedScene()));
  3242. popup.addSeparator();
  3243. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  3244. this, SLOT(on_actionSceneUp_triggered()));
  3245. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3246. this, SLOT(on_actionSceneDown_triggered()));
  3247. order.addSeparator();
  3248. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3249. this, SLOT(MoveSceneToTop()));
  3250. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3251. this, SLOT(MoveSceneToBottom()));
  3252. popup.addMenu(&order);
  3253. popup.addSeparator();
  3254. delete sceneProjectorMenu;
  3255. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3256. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3257. SLOT(OpenSceneProjector()));
  3258. popup.addMenu(sceneProjectorMenu);
  3259. QAction *sceneWindow = popup.addAction(
  3260. QTStr("SceneWindow"),
  3261. this, SLOT(OpenSceneWindow()));
  3262. popup.addAction(sceneWindow);
  3263. popup.addSeparator();
  3264. popup.addAction(QTStr("Filters"), this,
  3265. SLOT(OpenSceneFilters()));
  3266. popup.addSeparator();
  3267. delete perSceneTransitionMenu;
  3268. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3269. popup.addMenu(perSceneTransitionMenu);
  3270. /* ---------------------- */
  3271. QAction *multiviewAction = popup.addAction(
  3272. QTStr("ShowInMultiview"));
  3273. OBSSource source = GetCurrentSceneSource();
  3274. OBSData data = obs_source_get_private_settings(source);
  3275. obs_data_release(data);
  3276. obs_data_set_default_bool(data, "show_in_multiview",
  3277. true);
  3278. bool show = obs_data_get_bool(data, "show_in_multiview");
  3279. multiviewAction->setCheckable(true);
  3280. multiviewAction->setChecked(show);
  3281. auto showInMultiview = [] (OBSData data)
  3282. {
  3283. bool show = obs_data_get_bool(data,
  3284. "show_in_multiview");
  3285. obs_data_set_bool(data, "show_in_multiview",
  3286. !show);
  3287. OBSProjector::UpdateMultiviewProjectors();
  3288. };
  3289. connect(multiviewAction, &QAction::triggered,
  3290. std::bind(showInMultiview, data));
  3291. }
  3292. popup.exec(QCursor::pos());
  3293. }
  3294. void OBSBasic::on_actionAddScene_triggered()
  3295. {
  3296. string name;
  3297. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3298. int i = 2;
  3299. QString placeHolderText = format.arg(i);
  3300. obs_source_t *source = nullptr;
  3301. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3302. obs_source_release(source);
  3303. placeHolderText = format.arg(++i);
  3304. }
  3305. bool accepted = NameDialog::AskForName(this,
  3306. QTStr("Basic.Main.AddSceneDlg.Title"),
  3307. QTStr("Basic.Main.AddSceneDlg.Text"),
  3308. name,
  3309. placeHolderText);
  3310. if (accepted) {
  3311. if (name.empty()) {
  3312. OBSMessageBox::warning(this,
  3313. QTStr("NoNameEntered.Title"),
  3314. QTStr("NoNameEntered.Text"));
  3315. on_actionAddScene_triggered();
  3316. return;
  3317. }
  3318. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3319. if (source) {
  3320. OBSMessageBox::warning(this,
  3321. QTStr("NameExists.Title"),
  3322. QTStr("NameExists.Text"));
  3323. obs_source_release(source);
  3324. on_actionAddScene_triggered();
  3325. return;
  3326. }
  3327. obs_scene_t *scene = obs_scene_create(name.c_str());
  3328. source = obs_scene_get_source(scene);
  3329. SetCurrentScene(source);
  3330. obs_scene_release(scene);
  3331. }
  3332. }
  3333. void OBSBasic::on_actionRemoveScene_triggered()
  3334. {
  3335. OBSScene scene = GetCurrentScene();
  3336. obs_source_t *source = obs_scene_get_source(scene);
  3337. if (source && QueryRemoveSource(source))
  3338. obs_source_remove(source);
  3339. }
  3340. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3341. {
  3342. int idx = ui->scenes->currentRow();
  3343. if (idx == -1 || idx == invalidIdx)
  3344. return;
  3345. sceneChanging = true;
  3346. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3347. if (!relative)
  3348. idx = 0;
  3349. ui->scenes->insertItem(idx + offset, item);
  3350. ui->scenes->setCurrentRow(idx + offset);
  3351. item->setSelected(true);
  3352. sceneChanging = false;
  3353. OBSProjector::UpdateMultiviewProjectors();
  3354. }
  3355. void OBSBasic::on_actionSceneUp_triggered()
  3356. {
  3357. ChangeSceneIndex(true, -1, 0);
  3358. }
  3359. void OBSBasic::on_actionSceneDown_triggered()
  3360. {
  3361. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3362. }
  3363. void OBSBasic::MoveSceneToTop()
  3364. {
  3365. ChangeSceneIndex(false, 0, 0);
  3366. }
  3367. void OBSBasic::MoveSceneToBottom()
  3368. {
  3369. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3370. ui->scenes->count() - 1);
  3371. }
  3372. void OBSBasic::EditSceneItemName()
  3373. {
  3374. int idx = GetTopSelectedSourceItem();
  3375. ui->sources->Edit(idx);
  3376. }
  3377. void OBSBasic::SetDeinterlacingMode()
  3378. {
  3379. QAction *action = reinterpret_cast<QAction*>(sender());
  3380. obs_deinterlace_mode mode =
  3381. (obs_deinterlace_mode)action->property("mode").toInt();
  3382. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3383. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3384. obs_source_set_deinterlace_mode(source, mode);
  3385. }
  3386. void OBSBasic::SetDeinterlacingOrder()
  3387. {
  3388. QAction *action = reinterpret_cast<QAction*>(sender());
  3389. obs_deinterlace_field_order order =
  3390. (obs_deinterlace_field_order)action->property("order").toInt();
  3391. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3392. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3393. obs_source_set_deinterlace_field_order(source, order);
  3394. }
  3395. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3396. {
  3397. obs_deinterlace_mode deinterlaceMode =
  3398. obs_source_get_deinterlace_mode(source);
  3399. obs_deinterlace_field_order deinterlaceOrder =
  3400. obs_source_get_deinterlace_field_order(source);
  3401. QAction *action;
  3402. #define ADD_MODE(name, mode) \
  3403. action = menu->addAction(QTStr("" name), this, \
  3404. SLOT(SetDeinterlacingMode())); \
  3405. action->setProperty("mode", (int)mode); \
  3406. action->setCheckable(true); \
  3407. action->setChecked(deinterlaceMode == mode);
  3408. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3409. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3410. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3411. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3412. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3413. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3414. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3415. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3416. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3417. #undef ADD_MODE
  3418. menu->addSeparator();
  3419. #define ADD_ORDER(name, order) \
  3420. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3421. SLOT(SetDeinterlacingOrder())); \
  3422. action->setProperty("order", (int)order); \
  3423. action->setCheckable(true); \
  3424. action->setChecked(deinterlaceOrder == order);
  3425. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3426. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3427. #undef ADD_ORDER
  3428. return menu;
  3429. }
  3430. void OBSBasic::SetScaleFilter()
  3431. {
  3432. QAction *action = reinterpret_cast<QAction*>(sender());
  3433. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3434. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3435. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3436. }
  3437. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3438. {
  3439. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3440. QAction *action;
  3441. #define ADD_MODE(name, mode) \
  3442. action = menu->addAction(QTStr("" name), this, \
  3443. SLOT(SetScaleFilter())); \
  3444. action->setProperty("mode", (int)mode); \
  3445. action->setCheckable(true); \
  3446. action->setChecked(scaleFilter == mode);
  3447. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3448. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3449. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3450. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3451. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3452. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3453. #undef ADD_MODE
  3454. return menu;
  3455. }
  3456. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction,
  3457. ColorSelect *select, obs_sceneitem_t *item)
  3458. {
  3459. QAction *action;
  3460. menu->setStyleSheet(QString(
  3461. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" \
  3462. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" \
  3463. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" \
  3464. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" \
  3465. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" \
  3466. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" \
  3467. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" \
  3468. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3469. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3470. obs_data_release(privData);
  3471. obs_data_set_default_int(privData, "color-preset", 0);
  3472. int preset = obs_data_get_int(privData, "color-preset");
  3473. action = menu->addAction(QTStr("Clear"), this,
  3474. + SLOT(ColorChange()));
  3475. action->setCheckable(true);
  3476. action->setProperty("bgColor", 0);
  3477. action->setChecked(preset == 0);
  3478. action = menu->addAction(QTStr("CustomColor"), this,
  3479. + SLOT(ColorChange()));
  3480. action->setCheckable(true);
  3481. action->setProperty("bgColor", 1);
  3482. action->setChecked(preset == 1);
  3483. menu->addSeparator();
  3484. widgetAction->setDefaultWidget(select);
  3485. for (int i = 1; i < 9; i++) {
  3486. stringstream button;
  3487. button << "preset" << i;
  3488. QPushButton *colorButton = select->findChild<QPushButton *>(
  3489. button.str().c_str());
  3490. if (preset == i + 1)
  3491. colorButton->setStyleSheet("border: 2px solid black");
  3492. colorButton->setProperty("bgColor", i);
  3493. select->connect(colorButton, SIGNAL(released()), this,
  3494. SLOT(ColorChange()));
  3495. }
  3496. menu->addAction(widgetAction);
  3497. return menu;
  3498. }
  3499. ColorSelect::ColorSelect(QWidget *parent)
  3500. : QWidget(parent),
  3501. ui(new Ui::ColorSelect)
  3502. {
  3503. ui->setupUi(this);
  3504. }
  3505. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3506. {
  3507. QMenu popup(this);
  3508. delete previewProjectorSource;
  3509. delete sourceProjector;
  3510. delete scaleFilteringMenu;
  3511. delete colorMenu;
  3512. delete colorWidgetAction;
  3513. delete colorSelect;
  3514. delete deinterlaceMenu;
  3515. if (preview) {
  3516. QAction *action = popup.addAction(
  3517. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3518. this, SLOT(TogglePreview()));
  3519. action->setCheckable(true);
  3520. action->setChecked(
  3521. obs_display_enabled(ui->preview->GetDisplay()));
  3522. if (IsPreviewProgramMode())
  3523. action->setEnabled(false);
  3524. popup.addAction(ui->actionLockPreview);
  3525. popup.addMenu(ui->scalingMenu);
  3526. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3527. AddProjectorMenuMonitors(previewProjectorSource, this,
  3528. SLOT(OpenPreviewProjector()));
  3529. popup.addMenu(previewProjectorSource);
  3530. QAction *previewWindow = popup.addAction(
  3531. QTStr("PreviewWindow"),
  3532. this, SLOT(OpenPreviewWindow()));
  3533. popup.addAction(previewWindow);
  3534. popup.addSeparator();
  3535. }
  3536. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3537. if (addSourceMenu)
  3538. popup.addMenu(addSourceMenu);
  3539. ui->actionCopyFilters->setEnabled(false);
  3540. ui->actionCopySource->setEnabled(false);
  3541. if (ui->sources->MultipleBaseSelected()) {
  3542. popup.addSeparator();
  3543. popup.addAction(QTStr("Basic.Main.GroupItems"),
  3544. ui->sources, SLOT(GroupSelectedItems()));
  3545. } else if (ui->sources->GroupsSelected()) {
  3546. popup.addSeparator();
  3547. popup.addAction(QTStr("Basic.Main.Ungroup"),
  3548. ui->sources, SLOT(UngroupSelectedGroups()));
  3549. }
  3550. popup.addSeparator();
  3551. popup.addAction(ui->actionCopySource);
  3552. popup.addAction(ui->actionPasteRef);
  3553. popup.addAction(ui->actionPasteDup);
  3554. popup.addSeparator();
  3555. popup.addSeparator();
  3556. popup.addAction(ui->actionCopyFilters);
  3557. popup.addAction(ui->actionPasteFilters);
  3558. popup.addSeparator();
  3559. if (idx != -1) {
  3560. if (addSourceMenu)
  3561. popup.addSeparator();
  3562. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3563. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3564. uint32_t flags = obs_source_get_output_flags(source);
  3565. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3566. OBS_SOURCE_ASYNC_VIDEO;
  3567. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  3568. OBS_SOURCE_AUDIO;
  3569. QAction *action;
  3570. colorMenu = new QMenu(QTStr("ChangeBG"));
  3571. colorWidgetAction = new QWidgetAction(colorMenu);
  3572. colorSelect = new ColorSelect(colorMenu);
  3573. popup.addMenu(AddBackgroundColorMenu(colorMenu,
  3574. colorWidgetAction, colorSelect, sceneItem));
  3575. popup.addAction(QTStr("Rename"), this,
  3576. SLOT(EditSceneItemName()));
  3577. popup.addAction(QTStr("Remove"), this,
  3578. SLOT(on_actionRemoveSource_triggered()));
  3579. popup.addSeparator();
  3580. popup.addMenu(ui->orderMenu);
  3581. popup.addMenu(ui->transformMenu);
  3582. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3583. AddProjectorMenuMonitors(sourceProjector, this,
  3584. SLOT(OpenSourceProjector()));
  3585. QAction *sourceWindow = popup.addAction(
  3586. QTStr("SourceWindow"),
  3587. this, SLOT(OpenSourceWindow()));
  3588. popup.addAction(sourceWindow);
  3589. popup.addSeparator();
  3590. if (hasAudio) {
  3591. QAction *actionHideMixer = popup.addAction(
  3592. QTStr("HideMixer"),
  3593. this, SLOT(ToggleHideMixer()));
  3594. actionHideMixer->setCheckable(true);
  3595. actionHideMixer->setChecked(SourceMixerHidden(source));
  3596. }
  3597. if (isAsyncVideo) {
  3598. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3599. popup.addMenu(AddDeinterlacingMenu(deinterlaceMenu, source));
  3600. popup.addSeparator();
  3601. }
  3602. QAction *resizeOutput = popup.addAction(
  3603. QTStr("ResizeOutputSizeOfSource"), this,
  3604. SLOT(ResizeOutputSizeOfSource()));
  3605. int width = obs_source_get_width(source);
  3606. int height = obs_source_get_height(source);
  3607. resizeOutput->setEnabled(!obs_video_active());
  3608. if (width == 0 || height == 0)
  3609. resizeOutput->setEnabled(false);
  3610. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3611. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3612. popup.addSeparator();
  3613. popup.addMenu(sourceProjector);
  3614. popup.addAction(sourceWindow);
  3615. popup.addSeparator();
  3616. action = popup.addAction(QTStr("Interact"), this,
  3617. SLOT(on_actionInteract_triggered()));
  3618. action->setEnabled(obs_source_get_output_flags(source) &
  3619. OBS_SOURCE_INTERACTION);
  3620. popup.addAction(QTStr("Filters"), this,
  3621. SLOT(OpenFilters()));
  3622. popup.addAction(QTStr("Properties"), this,
  3623. SLOT(on_actionSourceProperties_triggered()));
  3624. ui->actionCopyFilters->setEnabled(true);
  3625. ui->actionCopySource->setEnabled(true);
  3626. } else {
  3627. ui->actionPasteFilters->setEnabled(false);
  3628. }
  3629. popup.exec(QCursor::pos());
  3630. }
  3631. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3632. {
  3633. if (ui->scenes->count()) {
  3634. QModelIndex idx = ui->sources->indexAt(pos);
  3635. CreateSourcePopupMenu(idx.row(), false);
  3636. }
  3637. }
  3638. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3639. {
  3640. if (!witem)
  3641. return;
  3642. if (IsPreviewProgramMode()) {
  3643. bool doubleClickSwitch = config_get_bool(App()->GlobalConfig(),
  3644. "BasicWindow", "TransitionOnDoubleClick");
  3645. if (doubleClickSwitch) {
  3646. OBSScene scene = GetCurrentScene();
  3647. if (scene)
  3648. SetCurrentScene(scene, false, true);
  3649. }
  3650. }
  3651. }
  3652. void OBSBasic::AddSource(const char *id)
  3653. {
  3654. if (id && *id) {
  3655. OBSBasicSourceSelect sourceSelect(this, id);
  3656. sourceSelect.exec();
  3657. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3658. CreatePropertiesWindow(sourceSelect.newSource);
  3659. }
  3660. }
  3661. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3662. {
  3663. const char *type;
  3664. bool foundValues = false;
  3665. bool foundDeprecated = false;
  3666. size_t idx = 0;
  3667. QMenu *popup = new QMenu(QTStr("Add"), this);
  3668. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3669. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3670. {
  3671. QList<QAction*> actions = menu->actions();
  3672. for (QAction *menuAction : actions) {
  3673. if (menuAction->text().compare(name) >= 0)
  3674. return menuAction;
  3675. }
  3676. return (QAction*)nullptr;
  3677. };
  3678. auto addSource = [this, getActionAfter] (QMenu *popup,
  3679. const char *type, const char *name)
  3680. {
  3681. QString qname = QT_UTF8(name);
  3682. QAction *popupItem = new QAction(qname, this);
  3683. popupItem->setData(QT_UTF8(type));
  3684. connect(popupItem, SIGNAL(triggered(bool)),
  3685. this, SLOT(AddSourceFromAction()));
  3686. QAction *after = getActionAfter(popup, qname);
  3687. popup->insertAction(after, popupItem);
  3688. };
  3689. while (obs_enum_input_types(idx++, &type)) {
  3690. const char *name = obs_source_get_display_name(type);
  3691. uint32_t caps = obs_get_source_output_flags(type);
  3692. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3693. continue;
  3694. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3695. addSource(popup, type, name);
  3696. } else {
  3697. addSource(deprecated, type, name);
  3698. foundDeprecated = true;
  3699. }
  3700. foundValues = true;
  3701. }
  3702. addSource(popup, "scene", Str("Basic.Scene"));
  3703. popup->addSeparator();
  3704. QAction *addGroup = new QAction(QTStr("Group"), this);
  3705. addGroup->setData(QT_UTF8("group"));
  3706. connect(addGroup, SIGNAL(triggered(bool)),
  3707. this, SLOT(AddSourceFromAction()));
  3708. popup->addAction(addGroup);
  3709. if (!foundDeprecated) {
  3710. delete deprecated;
  3711. deprecated = nullptr;
  3712. }
  3713. if (!foundValues) {
  3714. delete popup;
  3715. popup = nullptr;
  3716. } else if (foundDeprecated) {
  3717. popup->addSeparator();
  3718. popup->addMenu(deprecated);
  3719. }
  3720. return popup;
  3721. }
  3722. void OBSBasic::AddSourceFromAction()
  3723. {
  3724. QAction *action = qobject_cast<QAction*>(sender());
  3725. if (!action)
  3726. return;
  3727. AddSource(QT_TO_UTF8(action->data().toString()));
  3728. }
  3729. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3730. {
  3731. if (!GetCurrentScene()) {
  3732. // Tell the user he needs a scene first (help beginners).
  3733. OBSMessageBox::information(this,
  3734. QTStr("Basic.Main.AddSourceHelp.Title"),
  3735. QTStr("Basic.Main.AddSourceHelp.Text"));
  3736. return;
  3737. }
  3738. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3739. if (popup)
  3740. popup->exec(pos);
  3741. }
  3742. void OBSBasic::on_actionAddSource_triggered()
  3743. {
  3744. AddSourcePopupMenu(QCursor::pos());
  3745. }
  3746. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3747. {
  3748. vector<OBSSceneItem> &items =
  3749. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3750. if (obs_sceneitem_selected(item)) {
  3751. items.emplace_back(item);
  3752. } else if (obs_sceneitem_is_group(item)) {
  3753. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3754. }
  3755. return true;
  3756. };
  3757. void OBSBasic::on_actionRemoveSource_triggered()
  3758. {
  3759. vector<OBSSceneItem> items;
  3760. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3761. if (!items.size())
  3762. return;
  3763. auto removeMultiple = [this] (size_t count)
  3764. {
  3765. QString text = QTStr("ConfirmRemove.TextMultiple")
  3766. .arg(QString::number(count));
  3767. QMessageBox remove_items(this);
  3768. remove_items.setText(text);
  3769. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3770. QMessageBox::YesRole);
  3771. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3772. remove_items.setIcon(QMessageBox::Question);
  3773. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3774. remove_items.exec();
  3775. return Yes == remove_items.clickedButton();
  3776. };
  3777. if (items.size() == 1) {
  3778. OBSSceneItem &item = items[0];
  3779. obs_source_t *source = obs_sceneitem_get_source(item);
  3780. if (source && QueryRemoveSource(source))
  3781. obs_sceneitem_remove(item);
  3782. } else {
  3783. if (removeMultiple(items.size())) {
  3784. for (auto &item : items)
  3785. obs_sceneitem_remove(item);
  3786. }
  3787. }
  3788. }
  3789. void OBSBasic::on_actionInteract_triggered()
  3790. {
  3791. OBSSceneItem item = GetCurrentSceneItem();
  3792. OBSSource source = obs_sceneitem_get_source(item);
  3793. if (source)
  3794. CreateInteractionWindow(source);
  3795. }
  3796. void OBSBasic::on_actionSourceProperties_triggered()
  3797. {
  3798. OBSSceneItem item = GetCurrentSceneItem();
  3799. OBSSource source = obs_sceneitem_get_source(item);
  3800. if (source)
  3801. CreatePropertiesWindow(source);
  3802. }
  3803. void OBSBasic::on_actionSourceUp_triggered()
  3804. {
  3805. OBSSceneItem item = GetCurrentSceneItem();
  3806. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3807. }
  3808. void OBSBasic::on_actionSourceDown_triggered()
  3809. {
  3810. OBSSceneItem item = GetCurrentSceneItem();
  3811. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3812. }
  3813. void OBSBasic::on_actionMoveUp_triggered()
  3814. {
  3815. OBSSceneItem item = GetCurrentSceneItem();
  3816. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3817. }
  3818. void OBSBasic::on_actionMoveDown_triggered()
  3819. {
  3820. OBSSceneItem item = GetCurrentSceneItem();
  3821. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3822. }
  3823. void OBSBasic::on_actionMoveToTop_triggered()
  3824. {
  3825. OBSSceneItem item = GetCurrentSceneItem();
  3826. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3827. }
  3828. void OBSBasic::on_actionMoveToBottom_triggered()
  3829. {
  3830. OBSSceneItem item = GetCurrentSceneItem();
  3831. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3832. }
  3833. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3834. {
  3835. char logDir[512];
  3836. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3837. return nullptr;
  3838. string path = (char*)logDir;
  3839. path += "/";
  3840. path += log;
  3841. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3842. if (!file)
  3843. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3844. return file;
  3845. }
  3846. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3847. {
  3848. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3849. if (!fileString)
  3850. return;
  3851. if (!*fileString)
  3852. return;
  3853. ui->menuLogFiles->setEnabled(false);
  3854. stringstream ss;
  3855. ss << "OBS " << App()->GetVersionString()
  3856. << " log file uploaded at " << CurrentDateTimeString()
  3857. << "\n\n" << fileString;
  3858. if (logUploadThread) {
  3859. logUploadThread->wait();
  3860. }
  3861. RemoteTextThread *thread = new RemoteTextThread(
  3862. "https://obsproject.com/logs/upload",
  3863. "text/plain", ss.str().c_str());
  3864. logUploadThread.reset(thread);
  3865. connect(thread, &RemoteTextThread::Result,
  3866. this, &OBSBasic::logUploadFinished);
  3867. logUploadThread->start();
  3868. }
  3869. void OBSBasic::on_actionShowLogs_triggered()
  3870. {
  3871. char logDir[512];
  3872. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3873. return;
  3874. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3875. QDesktopServices::openUrl(url);
  3876. }
  3877. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3878. {
  3879. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3880. }
  3881. void OBSBasic::on_actionUploadLastLog_triggered()
  3882. {
  3883. UploadLog("obs-studio/logs", App()->GetLastLog());
  3884. }
  3885. void OBSBasic::on_actionViewCurrentLog_triggered()
  3886. {
  3887. char logDir[512];
  3888. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3889. return;
  3890. const char* log = App()->GetCurrentLog();
  3891. string path = (char*)logDir;
  3892. path += "/";
  3893. path += log;
  3894. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3895. QDesktopServices::openUrl(url);
  3896. }
  3897. void OBSBasic::on_actionShowCrashLogs_triggered()
  3898. {
  3899. char logDir[512];
  3900. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  3901. return;
  3902. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3903. QDesktopServices::openUrl(url);
  3904. }
  3905. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  3906. {
  3907. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  3908. }
  3909. void OBSBasic::on_actionCheckForUpdates_triggered()
  3910. {
  3911. CheckForUpdates(true);
  3912. }
  3913. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3914. {
  3915. ui->menuLogFiles->setEnabled(true);
  3916. if (text.isEmpty()) {
  3917. OBSMessageBox::critical(this,
  3918. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3919. error);
  3920. return;
  3921. }
  3922. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3923. string resURL = obs_data_get_string(returnData, "url");
  3924. QString logURL = resURL.c_str();
  3925. obs_data_release(returnData);
  3926. OBSLogReply logDialog(this, logURL);
  3927. logDialog.exec();
  3928. }
  3929. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3930. obs_source_t *source, const string &name)
  3931. {
  3932. const char *prevName = obs_source_get_name(source);
  3933. if (name == prevName)
  3934. return;
  3935. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3936. QListWidgetItem *listItem = listWidget->currentItem();
  3937. if (foundSource || name.empty()) {
  3938. listItem->setText(QT_UTF8(prevName));
  3939. if (foundSource) {
  3940. OBSMessageBox::warning(parent,
  3941. QTStr("NameExists.Title"),
  3942. QTStr("NameExists.Text"));
  3943. } else if (name.empty()) {
  3944. OBSMessageBox::warning(parent,
  3945. QTStr("NoNameEntered.Title"),
  3946. QTStr("NoNameEntered.Text"));
  3947. }
  3948. obs_source_release(foundSource);
  3949. } else {
  3950. listItem->setText(QT_UTF8(name.c_str()));
  3951. obs_source_set_name(source, name.c_str());
  3952. }
  3953. }
  3954. void OBSBasic::SceneNameEdited(QWidget *editor,
  3955. QAbstractItemDelegate::EndEditHint endHint)
  3956. {
  3957. OBSScene scene = GetCurrentScene();
  3958. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3959. string text = QT_TO_UTF8(edit->text().trimmed());
  3960. if (!scene)
  3961. return;
  3962. obs_source_t *source = obs_scene_get_source(scene);
  3963. RenameListItem(this, ui->scenes, source, text);
  3964. if (api)
  3965. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3966. UNUSED_PARAMETER(endHint);
  3967. }
  3968. void OBSBasic::OpenFilters()
  3969. {
  3970. OBSSceneItem item = GetCurrentSceneItem();
  3971. OBSSource source = obs_sceneitem_get_source(item);
  3972. CreateFiltersWindow(source);
  3973. }
  3974. void OBSBasic::OpenSceneFilters()
  3975. {
  3976. OBSScene scene = GetCurrentScene();
  3977. OBSSource source = obs_scene_get_source(scene);
  3978. CreateFiltersWindow(source);
  3979. }
  3980. #define RECORDING_START \
  3981. "==== Recording Start ==============================================="
  3982. #define RECORDING_STOP \
  3983. "==== Recording Stop ================================================"
  3984. #define REPLAY_BUFFER_START \
  3985. "==== Replay Buffer Start ==========================================="
  3986. #define REPLAY_BUFFER_STOP \
  3987. "==== Replay Buffer Stop ============================================"
  3988. #define STREAMING_START \
  3989. "==== Streaming Start ==============================================="
  3990. #define STREAMING_STOP \
  3991. "==== Streaming Stop ================================================"
  3992. void OBSBasic::StartStreaming()
  3993. {
  3994. if (outputHandler->StreamingActive())
  3995. return;
  3996. if (disableOutputsRef)
  3997. return;
  3998. if (api)
  3999. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4000. SaveProject();
  4001. ui->streamButton->setEnabled(false);
  4002. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4003. if (sysTrayStream) {
  4004. sysTrayStream->setEnabled(false);
  4005. sysTrayStream->setText(ui->streamButton->text());
  4006. }
  4007. if (!outputHandler->StartStreaming(service)) {
  4008. QString message = !outputHandler->lastError.empty()
  4009. ? QTStr(outputHandler->lastError.c_str())
  4010. : QTStr("Output.StartFailedGeneric");
  4011. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4012. ui->streamButton->setEnabled(true);
  4013. ui->streamButton->setChecked(false);
  4014. if (sysTrayStream) {
  4015. sysTrayStream->setText(ui->streamButton->text());
  4016. sysTrayStream->setEnabled(true);
  4017. }
  4018. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
  4019. message);
  4020. return;
  4021. }
  4022. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4023. "BasicWindow", "RecordWhenStreaming");
  4024. if (recordWhenStreaming)
  4025. StartRecording();
  4026. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4027. "BasicWindow", "ReplayBufferWhileStreaming");
  4028. if (replayBufferWhileStreaming)
  4029. StartReplayBuffer();
  4030. }
  4031. #ifdef _WIN32
  4032. static inline void UpdateProcessPriority()
  4033. {
  4034. const char *priority = config_get_string(App()->GlobalConfig(),
  4035. "General", "ProcessPriority");
  4036. if (priority && strcmp(priority, "Normal") != 0)
  4037. SetProcessPriority(priority);
  4038. }
  4039. static inline void ClearProcessPriority()
  4040. {
  4041. const char *priority = config_get_string(App()->GlobalConfig(),
  4042. "General", "ProcessPriority");
  4043. if (priority && strcmp(priority, "Normal") != 0)
  4044. SetProcessPriority("Normal");
  4045. }
  4046. #else
  4047. #define UpdateProcessPriority() do {} while(false)
  4048. #define ClearProcessPriority() do {} while(false)
  4049. #endif
  4050. inline void OBSBasic::OnActivate()
  4051. {
  4052. if (ui->profileMenu->isEnabled()) {
  4053. ui->profileMenu->setEnabled(false);
  4054. ui->autoConfigure->setEnabled(false);
  4055. App()->IncrementSleepInhibition();
  4056. UpdateProcessPriority();
  4057. if (trayIcon)
  4058. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  4059. QIcon(":/res/images/tray_active.png")));
  4060. }
  4061. }
  4062. inline void OBSBasic::OnDeactivate()
  4063. {
  4064. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4065. ui->profileMenu->setEnabled(true);
  4066. ui->autoConfigure->setEnabled(true);
  4067. App()->DecrementSleepInhibition();
  4068. ClearProcessPriority();
  4069. if (trayIcon)
  4070. trayIcon->setIcon(QIcon::fromTheme("obs-tray",
  4071. QIcon(":/res/images/obs.png")));
  4072. }
  4073. }
  4074. void OBSBasic::StopStreaming()
  4075. {
  4076. SaveProject();
  4077. if (outputHandler->StreamingActive())
  4078. outputHandler->StopStreaming(streamingStopping);
  4079. OnDeactivate();
  4080. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4081. "BasicWindow", "RecordWhenStreaming");
  4082. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4083. "BasicWindow", "KeepRecordingWhenStreamStops");
  4084. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4085. StopRecording();
  4086. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4087. "BasicWindow", "ReplayBufferWhileStreaming");
  4088. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4089. "BasicWindow", "KeepReplayBufferStreamStops");
  4090. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4091. StopReplayBuffer();
  4092. }
  4093. void OBSBasic::ForceStopStreaming()
  4094. {
  4095. SaveProject();
  4096. if (outputHandler->StreamingActive())
  4097. outputHandler->StopStreaming(true);
  4098. OnDeactivate();
  4099. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4100. "BasicWindow", "RecordWhenStreaming");
  4101. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4102. "BasicWindow", "KeepRecordingWhenStreamStops");
  4103. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4104. StopRecording();
  4105. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4106. "BasicWindow", "ReplayBufferWhileStreaming");
  4107. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4108. "BasicWindow", "KeepReplayBufferStreamStops");
  4109. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4110. StopReplayBuffer();
  4111. }
  4112. void OBSBasic::StreamDelayStarting(int sec)
  4113. {
  4114. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4115. ui->streamButton->setEnabled(true);
  4116. ui->streamButton->setChecked(true);
  4117. if (sysTrayStream) {
  4118. sysTrayStream->setText(ui->streamButton->text());
  4119. sysTrayStream->setEnabled(true);
  4120. }
  4121. if (!startStreamMenu.isNull())
  4122. startStreamMenu->deleteLater();
  4123. startStreamMenu = new QMenu();
  4124. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  4125. this, SLOT(StopStreaming()));
  4126. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4127. this, SLOT(ForceStopStreaming()));
  4128. ui->streamButton->setMenu(startStreamMenu);
  4129. ui->statusbar->StreamDelayStarting(sec);
  4130. OnActivate();
  4131. }
  4132. void OBSBasic::StreamDelayStopping(int sec)
  4133. {
  4134. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4135. ui->streamButton->setEnabled(true);
  4136. ui->streamButton->setChecked(false);
  4137. if (sysTrayStream) {
  4138. sysTrayStream->setText(ui->streamButton->text());
  4139. sysTrayStream->setEnabled(true);
  4140. }
  4141. if (!startStreamMenu.isNull())
  4142. startStreamMenu->deleteLater();
  4143. startStreamMenu = new QMenu();
  4144. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  4145. this, SLOT(StartStreaming()));
  4146. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4147. this, SLOT(ForceStopStreaming()));
  4148. ui->streamButton->setMenu(startStreamMenu);
  4149. ui->statusbar->StreamDelayStopping(sec);
  4150. if (api)
  4151. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4152. }
  4153. void OBSBasic::StreamingStart()
  4154. {
  4155. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4156. ui->streamButton->setEnabled(true);
  4157. ui->streamButton->setChecked(true);
  4158. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4159. if (sysTrayStream) {
  4160. sysTrayStream->setText(ui->streamButton->text());
  4161. sysTrayStream->setEnabled(true);
  4162. }
  4163. if (api)
  4164. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4165. OnActivate();
  4166. blog(LOG_INFO, STREAMING_START);
  4167. }
  4168. void OBSBasic::StreamStopping()
  4169. {
  4170. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4171. if (sysTrayStream)
  4172. sysTrayStream->setText(ui->streamButton->text());
  4173. streamingStopping = true;
  4174. if (api)
  4175. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4176. }
  4177. void OBSBasic::StreamingStop(int code, QString last_error)
  4178. {
  4179. const char *errorDescription;
  4180. DStr errorMessage;
  4181. bool use_last_error = false;
  4182. switch (code) {
  4183. case OBS_OUTPUT_BAD_PATH:
  4184. errorDescription = Str("Output.ConnectFail.BadPath");
  4185. break;
  4186. case OBS_OUTPUT_CONNECT_FAILED:
  4187. use_last_error = true;
  4188. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4189. break;
  4190. case OBS_OUTPUT_INVALID_STREAM:
  4191. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4192. break;
  4193. default:
  4194. case OBS_OUTPUT_ERROR:
  4195. use_last_error = true;
  4196. errorDescription = Str("Output.ConnectFail.Error");
  4197. break;
  4198. case OBS_OUTPUT_DISCONNECTED:
  4199. /* doesn't happen if output is set to reconnect. note that
  4200. * reconnects are handled in the output, not in the UI */
  4201. use_last_error = true;
  4202. errorDescription = Str("Output.ConnectFail.Disconnected");
  4203. }
  4204. if (use_last_error && !last_error.isEmpty())
  4205. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4206. QT_TO_UTF8(last_error));
  4207. else
  4208. dstr_copy(errorMessage, errorDescription);
  4209. ui->statusbar->StreamStopped();
  4210. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4211. ui->streamButton->setEnabled(true);
  4212. ui->streamButton->setChecked(false);
  4213. if (sysTrayStream) {
  4214. sysTrayStream->setText(ui->streamButton->text());
  4215. sysTrayStream->setEnabled(true);
  4216. }
  4217. streamingStopping = false;
  4218. if (api)
  4219. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4220. OnDeactivate();
  4221. blog(LOG_INFO, STREAMING_STOP);
  4222. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4223. OBSMessageBox::information(this,
  4224. QTStr("Output.ConnectFail.Title"),
  4225. QT_UTF8(errorMessage));
  4226. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4227. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  4228. }
  4229. if (!startStreamMenu.isNull()) {
  4230. ui->streamButton->setMenu(nullptr);
  4231. startStreamMenu->deleteLater();
  4232. startStreamMenu = nullptr;
  4233. }
  4234. }
  4235. void OBSBasic::AutoRemux()
  4236. {
  4237. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4238. bool advanced = astrcmpi(mode, "Advanced") == 0;
  4239. const char *path = !advanced
  4240. ? config_get_string(basicConfig, "SimpleOutput", "FilePath")
  4241. : config_get_string(basicConfig, "AdvOut", "RecFilePath");
  4242. /* do not save if using FFmpeg output in advanced output mode */
  4243. if (advanced) {
  4244. const char *type = config_get_string(basicConfig, "AdvOut",
  4245. "RecType");
  4246. if (astrcmpi(type, "FFmpeg") == 0) {
  4247. return;
  4248. }
  4249. }
  4250. QString input;
  4251. input += path;
  4252. input += "/";
  4253. input += remuxFilename.c_str();
  4254. QFileInfo fi(remuxFilename.c_str());
  4255. /* do not remux if lossless */
  4256. if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
  4257. return;
  4258. }
  4259. QString output;
  4260. output += path;
  4261. output += "/";
  4262. output += fi.completeBaseName();
  4263. output += ".mp4";
  4264. OBSRemux *remux = new OBSRemux(path, this, true);
  4265. remux->show();
  4266. remux->AutoRemux(input, output);
  4267. }
  4268. void OBSBasic::StartRecording()
  4269. {
  4270. if (outputHandler->RecordingActive())
  4271. return;
  4272. if (disableOutputsRef)
  4273. return;
  4274. if (api)
  4275. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4276. SaveProject();
  4277. if (!outputHandler->StartRecording())
  4278. ui->recordButton->setChecked(false);
  4279. }
  4280. void OBSBasic::RecordStopping()
  4281. {
  4282. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4283. if (sysTrayRecord)
  4284. sysTrayRecord->setText(ui->recordButton->text());
  4285. recordingStopping = true;
  4286. if (api)
  4287. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4288. }
  4289. void OBSBasic::StopRecording()
  4290. {
  4291. SaveProject();
  4292. if (outputHandler->RecordingActive())
  4293. outputHandler->StopRecording(recordingStopping);
  4294. OnDeactivate();
  4295. }
  4296. void OBSBasic::RecordingStart()
  4297. {
  4298. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4299. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4300. ui->recordButton->setChecked(true);
  4301. if (sysTrayRecord)
  4302. sysTrayRecord->setText(ui->recordButton->text());
  4303. recordingStopping = false;
  4304. if (api)
  4305. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4306. OnActivate();
  4307. blog(LOG_INFO, RECORDING_START);
  4308. }
  4309. void OBSBasic::RecordingStop(int code, QString last_error)
  4310. {
  4311. ui->statusbar->RecordingStopped();
  4312. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4313. ui->recordButton->setChecked(false);
  4314. if (sysTrayRecord)
  4315. sysTrayRecord->setText(ui->recordButton->text());
  4316. blog(LOG_INFO, RECORDING_STOP);
  4317. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4318. OBSMessageBox::critical(this,
  4319. QTStr("Output.RecordFail.Title"),
  4320. QTStr("Output.RecordFail.Unsupported"));
  4321. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4322. OBSMessageBox::warning(this,
  4323. QTStr("Output.RecordNoSpace.Title"),
  4324. QTStr("Output.RecordNoSpace.Msg"));
  4325. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4326. const char *errorDescription;
  4327. DStr errorMessage;
  4328. bool use_last_error = true;
  4329. errorDescription = Str("Output.RecordError.Msg");
  4330. if (use_last_error && !last_error.isEmpty())
  4331. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4332. QT_TO_UTF8(last_error));
  4333. else
  4334. dstr_copy(errorMessage, errorDescription);
  4335. OBSMessageBox::critical(this,
  4336. QTStr("Output.RecordError.Title"),
  4337. QT_UTF8(errorMessage));
  4338. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4339. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4340. QSystemTrayIcon::Warning);
  4341. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4342. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4343. QSystemTrayIcon::Warning);
  4344. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4345. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4346. QSystemTrayIcon::Warning);
  4347. }
  4348. if (api)
  4349. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4350. if (remuxAfterRecord)
  4351. AutoRemux();
  4352. OnDeactivate();
  4353. }
  4354. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4355. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4356. void OBSBasic::StartReplayBuffer()
  4357. {
  4358. if (!outputHandler || !outputHandler->replayBuffer)
  4359. return;
  4360. if (outputHandler->ReplayBufferActive())
  4361. return;
  4362. if (disableOutputsRef)
  4363. return;
  4364. if (!NoSourcesConfirmation()) {
  4365. replayBufferButton->setChecked(false);
  4366. return;
  4367. }
  4368. obs_output_t *output = outputHandler->replayBuffer;
  4369. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4370. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  4371. "ReplayBuffer.Save");
  4372. size_t count = obs_data_array_count(bindings);
  4373. obs_data_array_release(bindings);
  4374. obs_data_release(hotkeys);
  4375. if (!count) {
  4376. OBSMessageBox::information(this,
  4377. RP_NO_HOTKEY_TITLE,
  4378. RP_NO_HOTKEY_TEXT);
  4379. replayBufferButton->setChecked(false);
  4380. return;
  4381. }
  4382. if (api)
  4383. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4384. SaveProject();
  4385. if (!outputHandler->StartReplayBuffer())
  4386. replayBufferButton->setChecked(false);
  4387. }
  4388. void OBSBasic::ReplayBufferStopping()
  4389. {
  4390. if (!outputHandler || !outputHandler->replayBuffer)
  4391. return;
  4392. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4393. if (sysTrayReplayBuffer)
  4394. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4395. replayBufferStopping = true;
  4396. if (api)
  4397. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4398. }
  4399. void OBSBasic::StopReplayBuffer()
  4400. {
  4401. if (!outputHandler || !outputHandler->replayBuffer)
  4402. return;
  4403. SaveProject();
  4404. if (outputHandler->ReplayBufferActive())
  4405. outputHandler->StopReplayBuffer(replayBufferStopping);
  4406. OnDeactivate();
  4407. }
  4408. void OBSBasic::ReplayBufferStart()
  4409. {
  4410. if (!outputHandler || !outputHandler->replayBuffer)
  4411. return;
  4412. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4413. replayBufferButton->setChecked(true);
  4414. if (sysTrayReplayBuffer)
  4415. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4416. replayBufferStopping = false;
  4417. if (api)
  4418. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4419. OnActivate();
  4420. blog(LOG_INFO, REPLAY_BUFFER_START);
  4421. }
  4422. void OBSBasic::ReplayBufferSave()
  4423. {
  4424. if (!outputHandler || !outputHandler->replayBuffer)
  4425. return;
  4426. if (!outputHandler->ReplayBufferActive())
  4427. return;
  4428. calldata_t cd = {0};
  4429. proc_handler_t *ph = obs_output_get_proc_handler(
  4430. outputHandler->replayBuffer);
  4431. proc_handler_call(ph, "save", &cd);
  4432. calldata_free(&cd);
  4433. }
  4434. void OBSBasic::ReplayBufferStop(int code)
  4435. {
  4436. if (!outputHandler || !outputHandler->replayBuffer)
  4437. return;
  4438. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4439. replayBufferButton->setChecked(false);
  4440. if (sysTrayReplayBuffer)
  4441. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4442. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4443. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4444. OBSMessageBox::critical(this,
  4445. QTStr("Output.RecordFail.Title"),
  4446. QTStr("Output.RecordFail.Unsupported"));
  4447. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4448. OBSMessageBox::warning(this,
  4449. QTStr("Output.RecordNoSpace.Title"),
  4450. QTStr("Output.RecordNoSpace.Msg"));
  4451. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4452. OBSMessageBox::critical(this,
  4453. QTStr("Output.RecordError.Title"),
  4454. QTStr("Output.RecordError.Msg"));
  4455. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4456. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4457. QSystemTrayIcon::Warning);
  4458. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4459. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4460. QSystemTrayIcon::Warning);
  4461. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4462. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4463. QSystemTrayIcon::Warning);
  4464. }
  4465. if (api)
  4466. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4467. OnDeactivate();
  4468. }
  4469. bool OBSBasic::NoSourcesConfirmation()
  4470. {
  4471. if (CountVideoSources() == 0 && isVisible()) {
  4472. QString msg;
  4473. msg = QTStr("NoSources.Text");
  4474. msg += "\n\n";
  4475. msg += QTStr("NoSources.Text.AddSource");
  4476. QMessageBox messageBox(this);
  4477. messageBox.setWindowTitle(QTStr("NoSources.Title"));
  4478. messageBox.setText(msg);
  4479. QAbstractButton *Yes = messageBox.addButton(QTStr("Yes"),
  4480. QMessageBox::YesRole);
  4481. messageBox.addButton(QTStr("No"), QMessageBox::NoRole);
  4482. messageBox.setIcon(QMessageBox::Question);
  4483. messageBox.exec();
  4484. if (messageBox.clickedButton() != Yes)
  4485. return false;
  4486. }
  4487. return true;
  4488. }
  4489. void OBSBasic::on_streamButton_clicked()
  4490. {
  4491. if (outputHandler->StreamingActive()) {
  4492. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4493. "WarnBeforeStoppingStream");
  4494. if (confirm && isVisible()) {
  4495. QMessageBox::StandardButton button =
  4496. OBSMessageBox::question(this,
  4497. QTStr("ConfirmStop.Title"),
  4498. QTStr("ConfirmStop.Text"));
  4499. if (button == QMessageBox::No) {
  4500. ui->streamButton->setChecked(true);
  4501. return;
  4502. }
  4503. }
  4504. StopStreaming();
  4505. } else {
  4506. if (!NoSourcesConfirmation()) {
  4507. ui->streamButton->setChecked(false);
  4508. return;
  4509. }
  4510. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4511. "WarnBeforeStartingStream");
  4512. obs_data_t *settings = obs_service_get_settings(service);
  4513. bool bwtest = obs_data_get_bool(settings, "bwtest");
  4514. obs_data_release(settings);
  4515. if (bwtest && isVisible()) {
  4516. QMessageBox::StandardButton button =
  4517. OBSMessageBox::question(this,
  4518. QTStr("ConfirmBWTest.Title"),
  4519. QTStr("ConfirmBWTest.Text"));
  4520. if (button == QMessageBox::No) {
  4521. ui->streamButton->setChecked(false);
  4522. return;
  4523. }
  4524. } else if (confirm && isVisible()) {
  4525. QMessageBox::StandardButton button =
  4526. OBSMessageBox::question(this,
  4527. QTStr("ConfirmStart.Title"),
  4528. QTStr("ConfirmStart.Text"));
  4529. if (button == QMessageBox::No) {
  4530. ui->streamButton->setChecked(false);
  4531. return;
  4532. }
  4533. }
  4534. StartStreaming();
  4535. }
  4536. }
  4537. void OBSBasic::on_recordButton_clicked()
  4538. {
  4539. if (outputHandler->RecordingActive()) {
  4540. StopRecording();
  4541. } else {
  4542. if (!NoSourcesConfirmation()) {
  4543. ui->recordButton->setChecked(false);
  4544. return;
  4545. }
  4546. StartRecording();
  4547. }
  4548. }
  4549. void OBSBasic::on_settingsButton_clicked()
  4550. {
  4551. on_action_Settings_triggered();
  4552. }
  4553. void OBSBasic::on_actionHelpPortal_triggered()
  4554. {
  4555. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4556. QDesktopServices::openUrl(url);
  4557. }
  4558. void OBSBasic::on_actionWebsite_triggered()
  4559. {
  4560. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4561. QDesktopServices::openUrl(url);
  4562. }
  4563. void OBSBasic::on_actionDiscord_triggered()
  4564. {
  4565. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4566. QDesktopServices::openUrl(url);
  4567. }
  4568. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4569. {
  4570. char path[512];
  4571. int ret = GetConfigPath(path, 512, "obs-studio");
  4572. if (ret <= 0)
  4573. return;
  4574. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4575. }
  4576. void OBSBasic::on_actionShowProfileFolder_triggered()
  4577. {
  4578. char path[512];
  4579. int ret = GetProfilePath(path, 512, "");
  4580. if (ret <= 0)
  4581. return;
  4582. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4583. }
  4584. int OBSBasic::GetTopSelectedSourceItem()
  4585. {
  4586. QModelIndexList selectedItems =
  4587. ui->sources->selectionModel()->selectedIndexes();
  4588. return selectedItems.count() ? selectedItems[0].row() : -1;
  4589. }
  4590. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4591. {
  4592. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4593. UNUSED_PARAMETER(pos);
  4594. }
  4595. void OBSBasic::on_program_customContextMenuRequested(const QPoint&)
  4596. {
  4597. QMenu popup(this);
  4598. QPointer<QMenu> studioProgramProjector;
  4599. studioProgramProjector = new QMenu(
  4600. QTStr("StudioProgramProjector"));
  4601. AddProjectorMenuMonitors(studioProgramProjector, this,
  4602. SLOT(OpenStudioProgramProjector()));
  4603. popup.addMenu(studioProgramProjector);
  4604. QAction *studioProgramWindow = popup.addAction(
  4605. QTStr("StudioProgramWindow"),
  4606. this, SLOT(OpenStudioProgramWindow()));
  4607. popup.addAction(studioProgramWindow);
  4608. popup.exec(QCursor::pos());
  4609. }
  4610. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  4611. const QPoint &pos)
  4612. {
  4613. QMenu popup(this);
  4614. delete previewProjectorMain;
  4615. QAction *action = popup.addAction(
  4616. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4617. this, SLOT(TogglePreview()));
  4618. action->setCheckable(true);
  4619. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4620. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4621. AddProjectorMenuMonitors(previewProjectorMain, this,
  4622. SLOT(OpenPreviewProjector()));
  4623. QAction *previewWindow = popup.addAction(
  4624. QTStr("PreviewWindow"),
  4625. this, SLOT(OpenPreviewWindow()));
  4626. popup.addMenu(previewProjectorMain);
  4627. popup.addAction(previewWindow);
  4628. popup.exec(QCursor::pos());
  4629. UNUSED_PARAMETER(pos);
  4630. }
  4631. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4632. {
  4633. #ifndef _WIN32
  4634. /* Make sure all dialogs are safely and successfully closed before
  4635. * switching the always on top mode due to the fact that windows all
  4636. * have to be recreated, so queue the actual toggle to happen after
  4637. * all events related to closing the dialogs have finished */
  4638. CloseDialogs();
  4639. #endif
  4640. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4641. Qt::QueuedConnection);
  4642. }
  4643. void OBSBasic::ToggleAlwaysOnTop()
  4644. {
  4645. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4646. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4647. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4648. show();
  4649. }
  4650. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4651. {
  4652. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4653. if (strcmp(val, "10") == 0) {
  4654. num = 10;
  4655. den = 1;
  4656. } else if (strcmp(val, "20") == 0) {
  4657. num = 20;
  4658. den = 1;
  4659. } else if (strcmp(val, "24 NTSC") == 0) {
  4660. num = 24000;
  4661. den = 1001;
  4662. } else if (strcmp(val, "25 PAL") == 0) {
  4663. num = 25;
  4664. den = 1;
  4665. } else if (strcmp(val, "29.97") == 0) {
  4666. num = 30000;
  4667. den = 1001;
  4668. } else if (strcmp(val, "48") == 0) {
  4669. num = 48;
  4670. den = 1;
  4671. } else if (strcmp(val, "50 PAL") == 0) {
  4672. num = 50;
  4673. den = 1;
  4674. } else if (strcmp(val, "59.94") == 0) {
  4675. num = 60000;
  4676. den = 1001;
  4677. } else if (strcmp(val, "60") == 0) {
  4678. num = 60;
  4679. den = 1;
  4680. } else {
  4681. num = 30;
  4682. den = 1;
  4683. }
  4684. }
  4685. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4686. {
  4687. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4688. den = 1;
  4689. }
  4690. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4691. {
  4692. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4693. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4694. }
  4695. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4696. {
  4697. num = 1000000000;
  4698. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4699. }
  4700. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4701. {
  4702. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4703. if (type == 1) //"Integer"
  4704. GetFPSInteger(num, den);
  4705. else if (type == 2) //"Fraction"
  4706. GetFPSFraction(num, den);
  4707. else if (false) //"Nanoseconds", currently not implemented
  4708. GetFPSNanoseconds(num, den);
  4709. else
  4710. GetFPSCommon(num, den);
  4711. }
  4712. config_t *OBSBasic::Config() const
  4713. {
  4714. return basicConfig;
  4715. }
  4716. void OBSBasic::on_actionEditTransform_triggered()
  4717. {
  4718. if (transformWindow)
  4719. transformWindow->close();
  4720. transformWindow = new OBSBasicTransform(this);
  4721. transformWindow->show();
  4722. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4723. }
  4724. static obs_transform_info copiedTransformInfo;
  4725. static obs_sceneitem_crop copiedCropInfo;
  4726. void OBSBasic::on_actionCopyTransform_triggered()
  4727. {
  4728. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4729. {
  4730. if (!obs_sceneitem_selected(item))
  4731. return true;
  4732. obs_sceneitem_defer_update_begin(item);
  4733. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4734. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4735. obs_sceneitem_defer_update_end(item);
  4736. UNUSED_PARAMETER(scene);
  4737. UNUSED_PARAMETER(param);
  4738. return true;
  4739. };
  4740. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4741. ui->actionPasteTransform->setEnabled(true);
  4742. }
  4743. void OBSBasic::on_actionPasteTransform_triggered()
  4744. {
  4745. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4746. {
  4747. if (!obs_sceneitem_selected(item))
  4748. return true;
  4749. obs_sceneitem_defer_update_begin(item);
  4750. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4751. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4752. obs_sceneitem_defer_update_end(item);
  4753. UNUSED_PARAMETER(scene);
  4754. UNUSED_PARAMETER(param);
  4755. return true;
  4756. };
  4757. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4758. }
  4759. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4760. {
  4761. if (obs_sceneitem_is_group(item))
  4762. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  4763. if (!obs_sceneitem_selected(item))
  4764. return true;
  4765. obs_sceneitem_defer_update_begin(item);
  4766. obs_transform_info info;
  4767. vec2_set(&info.pos, 0.0f, 0.0f);
  4768. vec2_set(&info.scale, 1.0f, 1.0f);
  4769. info.rot = 0.0f;
  4770. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4771. info.bounds_type = OBS_BOUNDS_NONE;
  4772. info.bounds_alignment = OBS_ALIGN_CENTER;
  4773. vec2_set(&info.bounds, 0.0f, 0.0f);
  4774. obs_sceneitem_set_info(item, &info);
  4775. obs_sceneitem_crop crop = {};
  4776. obs_sceneitem_set_crop(item, &crop);
  4777. obs_sceneitem_defer_update_end(item);
  4778. UNUSED_PARAMETER(scene);
  4779. UNUSED_PARAMETER(param);
  4780. return true;
  4781. }
  4782. void OBSBasic::on_actionResetTransform_triggered()
  4783. {
  4784. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  4785. }
  4786. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4787. {
  4788. matrix4 boxTransform;
  4789. obs_sceneitem_get_box_transform(item, &boxTransform);
  4790. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4791. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4792. auto GetMinPos = [&] (float x, float y)
  4793. {
  4794. vec3 pos;
  4795. vec3_set(&pos, x, y, 0.0f);
  4796. vec3_transform(&pos, &pos, &boxTransform);
  4797. vec3_min(&tl, &tl, &pos);
  4798. vec3_max(&br, &br, &pos);
  4799. };
  4800. GetMinPos(0.0f, 0.0f);
  4801. GetMinPos(1.0f, 0.0f);
  4802. GetMinPos(0.0f, 1.0f);
  4803. GetMinPos(1.0f, 1.0f);
  4804. }
  4805. static vec3 GetItemTL(obs_sceneitem_t *item)
  4806. {
  4807. vec3 tl, br;
  4808. GetItemBox(item, tl, br);
  4809. return tl;
  4810. }
  4811. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4812. {
  4813. vec3 newTL;
  4814. vec2 pos;
  4815. obs_sceneitem_get_pos(item, &pos);
  4816. newTL = GetItemTL(item);
  4817. pos.x += tl.x - newTL.x;
  4818. pos.y += tl.y - newTL.y;
  4819. obs_sceneitem_set_pos(item, &pos);
  4820. }
  4821. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4822. void *param)
  4823. {
  4824. if (obs_sceneitem_is_group(item))
  4825. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  4826. param);
  4827. if (!obs_sceneitem_selected(item))
  4828. return true;
  4829. float rot = *reinterpret_cast<float*>(param);
  4830. vec3 tl = GetItemTL(item);
  4831. rot += obs_sceneitem_get_rot(item);
  4832. if (rot >= 360.0f) rot -= 360.0f;
  4833. else if (rot <= -360.0f) rot += 360.0f;
  4834. obs_sceneitem_set_rot(item, rot);
  4835. obs_sceneitem_force_update_transform(item);
  4836. SetItemTL(item, tl);
  4837. UNUSED_PARAMETER(scene);
  4838. return true;
  4839. };
  4840. void OBSBasic::on_actionRotate90CW_triggered()
  4841. {
  4842. float f90CW = 90.0f;
  4843. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4844. }
  4845. void OBSBasic::on_actionRotate90CCW_triggered()
  4846. {
  4847. float f90CCW = -90.0f;
  4848. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4849. }
  4850. void OBSBasic::on_actionRotate180_triggered()
  4851. {
  4852. float f180 = 180.0f;
  4853. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4854. }
  4855. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4856. void *param)
  4857. {
  4858. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4859. if (obs_sceneitem_is_group(item))
  4860. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  4861. param);
  4862. if (!obs_sceneitem_selected(item))
  4863. return true;
  4864. vec3 tl = GetItemTL(item);
  4865. vec2 scale;
  4866. obs_sceneitem_get_scale(item, &scale);
  4867. vec2_mul(&scale, &scale, &mul);
  4868. obs_sceneitem_set_scale(item, &scale);
  4869. obs_sceneitem_force_update_transform(item);
  4870. SetItemTL(item, tl);
  4871. UNUSED_PARAMETER(scene);
  4872. return true;
  4873. }
  4874. void OBSBasic::on_actionFlipHorizontal_triggered()
  4875. {
  4876. vec2 scale;
  4877. vec2_set(&scale, -1.0f, 1.0f);
  4878. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4879. &scale);
  4880. }
  4881. void OBSBasic::on_actionFlipVertical_triggered()
  4882. {
  4883. vec2 scale;
  4884. vec2_set(&scale, 1.0f, -1.0f);
  4885. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4886. &scale);
  4887. }
  4888. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4889. void *param)
  4890. {
  4891. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4892. if (obs_sceneitem_is_group(item))
  4893. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  4894. param);
  4895. if (!obs_sceneitem_selected(item))
  4896. return true;
  4897. obs_video_info ovi;
  4898. obs_get_video_info(&ovi);
  4899. obs_transform_info itemInfo;
  4900. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4901. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4902. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4903. itemInfo.rot = 0.0f;
  4904. vec2_set(&itemInfo.bounds,
  4905. float(ovi.base_width), float(ovi.base_height));
  4906. itemInfo.bounds_type = boundsType;
  4907. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4908. obs_sceneitem_set_info(item, &itemInfo);
  4909. UNUSED_PARAMETER(scene);
  4910. return true;
  4911. }
  4912. void OBSBasic::on_actionFitToScreen_triggered()
  4913. {
  4914. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4915. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4916. &boundsType);
  4917. }
  4918. void OBSBasic::on_actionStretchToScreen_triggered()
  4919. {
  4920. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4921. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4922. &boundsType);
  4923. }
  4924. enum class CenterType {
  4925. Scene,
  4926. Vertical,
  4927. Horizontal
  4928. };
  4929. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4930. {
  4931. CenterType centerType = *reinterpret_cast<CenterType*>(param);
  4932. vec3 tl, br, itemCenter, screenCenter, offset;
  4933. obs_video_info ovi;
  4934. obs_transform_info oti;
  4935. if (obs_sceneitem_is_group(item))
  4936. obs_sceneitem_group_enum_items(item, center_to_scene,
  4937. &centerType);
  4938. if (!obs_sceneitem_selected(item))
  4939. return true;
  4940. obs_get_video_info(&ovi);
  4941. obs_sceneitem_get_info(item, &oti);
  4942. if (centerType == CenterType::Scene)
  4943. vec3_set(&screenCenter, float(ovi.base_width),
  4944. float(ovi.base_height), 0.0f);
  4945. else if (centerType == CenterType::Vertical)
  4946. vec3_set(&screenCenter, float(oti.bounds.x),
  4947. float(ovi.base_height), 0.0f);
  4948. else if (centerType == CenterType::Horizontal)
  4949. vec3_set(&screenCenter, float(ovi.base_width),
  4950. float(oti.bounds.y), 0.0f);
  4951. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4952. GetItemBox(item, tl, br);
  4953. vec3_sub(&itemCenter, &br, &tl);
  4954. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4955. vec3_add(&itemCenter, &itemCenter, &tl);
  4956. vec3_sub(&offset, &screenCenter, &itemCenter);
  4957. vec3_add(&tl, &tl, &offset);
  4958. if (centerType == CenterType::Vertical)
  4959. tl.x = oti.pos.x;
  4960. else if (centerType == CenterType::Horizontal)
  4961. tl.y = oti.pos.y;
  4962. SetItemTL(item, tl);
  4963. return true;
  4964. };
  4965. void OBSBasic::on_actionCenterToScreen_triggered()
  4966. {
  4967. CenterType centerType = CenterType::Scene;
  4968. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  4969. }
  4970. void OBSBasic::on_actionVerticalCenter_triggered()
  4971. {
  4972. CenterType centerType = CenterType::Vertical;
  4973. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  4974. }
  4975. void OBSBasic::on_actionHorizontalCenter_triggered()
  4976. {
  4977. CenterType centerType = CenterType::Horizontal;
  4978. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  4979. }
  4980. void OBSBasic::EnablePreviewDisplay(bool enable)
  4981. {
  4982. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4983. ui->preview->setVisible(enable);
  4984. ui->previewDisabledLabel->setVisible(!enable);
  4985. }
  4986. void OBSBasic::TogglePreview()
  4987. {
  4988. previewEnabled = !previewEnabled;
  4989. EnablePreviewDisplay(previewEnabled);
  4990. }
  4991. void OBSBasic::EnablePreview()
  4992. {
  4993. if (previewProgramMode)
  4994. return;
  4995. previewEnabled = true;
  4996. EnablePreviewDisplay(true);
  4997. }
  4998. void OBSBasic::DisablePreview()
  4999. {
  5000. if (previewProgramMode)
  5001. return;
  5002. previewEnabled = false;
  5003. EnablePreviewDisplay(false);
  5004. }
  5005. static bool nudge_callback(obs_scene_t*, obs_sceneitem_t *item, void *param)
  5006. {
  5007. if (obs_sceneitem_locked(item))
  5008. return true;
  5009. struct vec2 &offset = *reinterpret_cast<struct vec2*>(param);
  5010. struct vec2 pos;
  5011. if (!obs_sceneitem_selected(item)) {
  5012. if (obs_sceneitem_is_group(item)) {
  5013. struct vec3 offset3;
  5014. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5015. struct matrix4 matrix;
  5016. obs_sceneitem_get_draw_transform(item, &matrix);
  5017. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5018. matrix4_inv(&matrix, &matrix);
  5019. vec3_transform(&offset3, &offset3, &matrix);
  5020. struct vec2 new_offset;
  5021. vec2_set(&new_offset, offset3.x, offset3.y);
  5022. obs_sceneitem_group_enum_items(item, nudge_callback,
  5023. &new_offset);
  5024. }
  5025. return true;
  5026. }
  5027. obs_sceneitem_get_pos(item, &pos);
  5028. vec2_add(&pos, &pos, &offset);
  5029. obs_sceneitem_set_pos(item, &pos);
  5030. return true;
  5031. }
  5032. void OBSBasic::Nudge(int dist, MoveDir dir)
  5033. {
  5034. if (ui->preview->Locked())
  5035. return;
  5036. struct vec2 offset;
  5037. vec2_set(&offset, 0.0f, 0.0f);
  5038. switch (dir) {
  5039. case MoveDir::Up: offset.y = (float)-dist; break;
  5040. case MoveDir::Down: offset.y = (float) dist; break;
  5041. case MoveDir::Left: offset.x = (float)-dist; break;
  5042. case MoveDir::Right: offset.x = (float) dist; break;
  5043. }
  5044. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5045. }
  5046. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  5047. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  5048. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  5049. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  5050. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5051. QString title, ProjectorType type)
  5052. {
  5053. /* seriously? 10 monitors? */
  5054. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5055. return nullptr;
  5056. OBSProjector *projector = new OBSProjector(nullptr, source, monitor,
  5057. title, type);
  5058. if (monitor < 0) {
  5059. for (auto &projPtr : windowProjectors) {
  5060. if (!projPtr) {
  5061. projPtr = projector;
  5062. projector = nullptr;
  5063. }
  5064. }
  5065. if (projector)
  5066. windowProjectors.push_back(projector);
  5067. } else {
  5068. delete projectors[monitor];
  5069. projectors[monitor].clear();
  5070. projectors[monitor] = projector;
  5071. }
  5072. return projector;
  5073. }
  5074. void OBSBasic::OpenStudioProgramProjector()
  5075. {
  5076. int monitor = sender()->property("monitor").toInt();
  5077. OpenProjector(nullptr, monitor, nullptr, ProjectorType::StudioProgram);
  5078. }
  5079. void OBSBasic::OpenPreviewProjector()
  5080. {
  5081. int monitor = sender()->property("monitor").toInt();
  5082. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Preview);
  5083. }
  5084. void OBSBasic::OpenSourceProjector()
  5085. {
  5086. int monitor = sender()->property("monitor").toInt();
  5087. OBSSceneItem item = GetCurrentSceneItem();
  5088. if (!item)
  5089. return;
  5090. OpenProjector(obs_sceneitem_get_source(item), monitor, nullptr,
  5091. ProjectorType::Source);
  5092. }
  5093. void OBSBasic::OpenMultiviewProjector()
  5094. {
  5095. int monitor = sender()->property("monitor").toInt();
  5096. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Multiview);
  5097. }
  5098. void OBSBasic::OpenSceneProjector()
  5099. {
  5100. int monitor = sender()->property("monitor").toInt();
  5101. OBSScene scene = GetCurrentScene();
  5102. if (!scene)
  5103. return;
  5104. OpenProjector(obs_scene_get_source(scene), monitor, nullptr,
  5105. ProjectorType::Scene);
  5106. }
  5107. void OBSBasic::OpenStudioProgramWindow()
  5108. {
  5109. OpenProjector(nullptr, -1, QTStr("StudioProgramWindow"),
  5110. ProjectorType::StudioProgram);
  5111. }
  5112. void OBSBasic::OpenPreviewWindow()
  5113. {
  5114. OpenProjector(nullptr, -1, QTStr("PreviewWindow"),
  5115. ProjectorType::Preview);
  5116. }
  5117. void OBSBasic::OpenSourceWindow()
  5118. {
  5119. OBSSceneItem item = GetCurrentSceneItem();
  5120. if (!item)
  5121. return;
  5122. OBSSource source = obs_sceneitem_get_source(item);
  5123. QString title = QString::fromUtf8(obs_source_get_name(source));
  5124. OpenProjector(obs_sceneitem_get_source(item), -1, title,
  5125. ProjectorType::Source);
  5126. }
  5127. void OBSBasic::OpenMultiviewWindow()
  5128. {
  5129. OpenProjector(nullptr, -1, QTStr("MultiviewWindowed"),
  5130. ProjectorType::Multiview);
  5131. }
  5132. void OBSBasic::OpenSceneWindow()
  5133. {
  5134. OBSScene scene = GetCurrentScene();
  5135. if (!scene)
  5136. return;
  5137. OBSSource source = obs_scene_get_source(scene);
  5138. QString title = QString::fromUtf8(obs_source_get_name(source));
  5139. OpenProjector(obs_scene_get_source(scene), -1, title,
  5140. ProjectorType::Scene);
  5141. }
  5142. void OBSBasic::OpenSavedProjectors()
  5143. {
  5144. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5145. OBSProjector *projector = nullptr;
  5146. switch (info->type) {
  5147. case ProjectorType::Source:
  5148. case ProjectorType::Scene: {
  5149. OBSSource source = obs_get_source_by_name(
  5150. info->name.c_str());
  5151. if (!source)
  5152. continue;
  5153. QString title = nullptr;
  5154. if (info->monitor < 0)
  5155. title = QString::fromUtf8(
  5156. obs_source_get_name(source));
  5157. projector = OpenProjector(source, info->monitor, title,
  5158. info->type);
  5159. obs_source_release(source);
  5160. break;
  5161. }
  5162. case ProjectorType::Preview: {
  5163. projector = OpenProjector(nullptr, info->monitor,
  5164. QTStr("PreviewWindow"),
  5165. ProjectorType::Preview);
  5166. break;
  5167. }
  5168. case ProjectorType::StudioProgram: {
  5169. projector = OpenProjector(nullptr, info->monitor,
  5170. QTStr("StudioProgramWindow"),
  5171. ProjectorType::StudioProgram);
  5172. break;
  5173. }
  5174. case ProjectorType::Multiview: {
  5175. projector = OpenProjector(nullptr, info->monitor,
  5176. QTStr("MultiviewWindowed"),
  5177. ProjectorType::Multiview);
  5178. break;
  5179. }
  5180. }
  5181. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5182. QByteArray byteArray = QByteArray::fromBase64(
  5183. QByteArray(info->geometry.c_str()));
  5184. projector->restoreGeometry(byteArray);
  5185. if (!WindowPositionValid(projector->normalGeometry())) {
  5186. QRect rect = App()->desktop()->geometry();
  5187. projector->setGeometry(QStyle::alignedRect(
  5188. Qt::LeftToRight,
  5189. Qt::AlignCenter, size(), rect));
  5190. }
  5191. }
  5192. }
  5193. }
  5194. void OBSBasic::on_actionFullscreenInterface_triggered()
  5195. {
  5196. if (!fullscreenInterface)
  5197. showFullScreen();
  5198. else
  5199. showNormal();
  5200. fullscreenInterface = !fullscreenInterface;
  5201. }
  5202. void OBSBasic::UpdateTitleBar()
  5203. {
  5204. stringstream name;
  5205. const char *profile = config_get_string(App()->GlobalConfig(),
  5206. "Basic", "Profile");
  5207. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  5208. "Basic", "SceneCollection");
  5209. name << "OBS ";
  5210. if (previewProgramMode)
  5211. name << "Studio ";
  5212. name << App()->GetVersionString();
  5213. if (App()->IsPortableMode())
  5214. name << " - Portable Mode";
  5215. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5216. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5217. setWindowTitle(QT_UTF8(name.str().c_str()));
  5218. }
  5219. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5220. {
  5221. char profiles_path[512];
  5222. const char *profile = config_get_string(App()->GlobalConfig(),
  5223. "Basic", "ProfileDir");
  5224. int ret;
  5225. if (!profile)
  5226. return -1;
  5227. if (!path)
  5228. return -1;
  5229. if (!file)
  5230. file = "";
  5231. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5232. if (ret <= 0)
  5233. return ret;
  5234. if (!*file)
  5235. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5236. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5237. }
  5238. void OBSBasic::on_resetUI_triggered()
  5239. {
  5240. /* prune deleted extra docks */
  5241. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5242. if (!extraDocks[i]) {
  5243. extraDocks.removeAt(i);
  5244. }
  5245. }
  5246. if (extraDocks.size()) {
  5247. QMessageBox::StandardButton button = QMessageBox::question(
  5248. this,
  5249. QTStr("ResetUIWarning.Title"),
  5250. QTStr("ResetUIWarning.Text"));
  5251. if (button == QMessageBox::No)
  5252. return;
  5253. }
  5254. /* undock/hide/center extra docks */
  5255. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5256. if (extraDocks[i]) {
  5257. extraDocks[i]->setVisible(true);
  5258. extraDocks[i]->setFloating(true);
  5259. extraDocks[i]->move(
  5260. frameGeometry().topLeft() +
  5261. rect().center() -
  5262. extraDocks[i]->rect().center());
  5263. extraDocks[i]->setVisible(false);
  5264. }
  5265. }
  5266. restoreState(startingDockLayout);
  5267. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5268. int cx = width();
  5269. int cy = height();
  5270. int cx22_5 = cx * 225 / 1000;
  5271. int cx5 = cx * 5 / 100;
  5272. cy = cy * 225 / 1000;
  5273. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5274. QList<QDockWidget*> docks {
  5275. ui->scenesDock,
  5276. ui->sourcesDock,
  5277. ui->mixerDock,
  5278. ui->transitionsDock,
  5279. ui->controlsDock
  5280. };
  5281. QList<int> sizes {
  5282. cx22_5,
  5283. cx22_5,
  5284. mixerSize,
  5285. cx5,
  5286. cx5
  5287. };
  5288. ui->scenesDock->setVisible(true);
  5289. ui->sourcesDock->setVisible(true);
  5290. ui->mixerDock->setVisible(true);
  5291. ui->transitionsDock->setVisible(true);
  5292. ui->controlsDock->setVisible(true);
  5293. statsDock->setVisible(false);
  5294. statsDock->setFloating(true);
  5295. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5296. resizeDocks(docks, sizes, Qt::Horizontal);
  5297. #endif
  5298. }
  5299. void OBSBasic::on_lockUI_toggled(bool lock)
  5300. {
  5301. QDockWidget::DockWidgetFeatures features = lock
  5302. ? QDockWidget::NoDockWidgetFeatures
  5303. : QDockWidget::AllDockWidgetFeatures;
  5304. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5305. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5306. ui->scenesDock->setFeatures(mainFeatures);
  5307. ui->sourcesDock->setFeatures(mainFeatures);
  5308. ui->mixerDock->setFeatures(mainFeatures);
  5309. ui->transitionsDock->setFeatures(mainFeatures);
  5310. ui->controlsDock->setFeatures(mainFeatures);
  5311. statsDock->setFeatures(features);
  5312. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5313. if (!extraDocks[i]) {
  5314. extraDocks.removeAt(i);
  5315. } else {
  5316. extraDocks[i]->setFeatures(features);
  5317. }
  5318. }
  5319. }
  5320. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5321. {
  5322. ui->sourcesToolbar->setVisible(visible);
  5323. ui->scenesToolbar->setVisible(visible);
  5324. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5325. "ShowListboxToolbars", visible);
  5326. }
  5327. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5328. {
  5329. ui->statusbar->setVisible(visible);
  5330. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5331. "ShowStatusBar", visible);
  5332. }
  5333. void OBSBasic::on_actionLockPreview_triggered()
  5334. {
  5335. ui->preview->ToggleLocked();
  5336. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5337. }
  5338. void OBSBasic::on_scalingMenu_aboutToShow()
  5339. {
  5340. obs_video_info ovi;
  5341. obs_get_video_info(&ovi);
  5342. QAction *action = ui->actionScaleCanvas;
  5343. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5344. text = text.arg(QString::number(ovi.base_width),
  5345. QString::number(ovi.base_height));
  5346. action->setText(text);
  5347. action = ui->actionScaleOutput;
  5348. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5349. text = text.arg(QString::number(ovi.output_width),
  5350. QString::number(ovi.output_height));
  5351. action->setText(text);
  5352. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5353. ovi.output_height == ovi.base_height));
  5354. UpdatePreviewScalingMenu();
  5355. }
  5356. void OBSBasic::on_actionScaleWindow_triggered()
  5357. {
  5358. ui->preview->SetFixedScaling(false);
  5359. ui->preview->ResetScrollingOffset();
  5360. emit ui->preview->DisplayResized();
  5361. }
  5362. void OBSBasic::on_actionScaleCanvas_triggered()
  5363. {
  5364. ui->preview->SetFixedScaling(true);
  5365. ui->preview->SetScalingLevel(0);
  5366. emit ui->preview->DisplayResized();
  5367. }
  5368. void OBSBasic::on_actionScaleOutput_triggered()
  5369. {
  5370. obs_video_info ovi;
  5371. obs_get_video_info(&ovi);
  5372. ui->preview->SetFixedScaling(true);
  5373. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5374. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5375. int32_t approxScalingLevel = int32_t(
  5376. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5377. ui->preview->SetScalingLevel(approxScalingLevel);
  5378. ui->preview->SetScalingAmount(scalingAmount);
  5379. emit ui->preview->DisplayResized();
  5380. }
  5381. void OBSBasic::SetShowing(bool showing)
  5382. {
  5383. if (!showing && isVisible()) {
  5384. config_set_string(App()->GlobalConfig(),
  5385. "BasicWindow", "geometry",
  5386. saveGeometry().toBase64().constData());
  5387. /* hide all visible child dialogs */
  5388. visDlgPositions.clear();
  5389. if (!visDialogs.isEmpty()) {
  5390. for (QDialog *dlg : visDialogs) {
  5391. visDlgPositions.append(dlg->pos());
  5392. dlg->hide();
  5393. }
  5394. }
  5395. if (showHide)
  5396. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5397. QTimer::singleShot(250, this, SLOT(hide()));
  5398. if (previewEnabled)
  5399. EnablePreviewDisplay(false);
  5400. setVisible(false);
  5401. #ifdef __APPLE__
  5402. EnableOSXDockIcon(false);
  5403. #endif
  5404. } else if (showing && !isVisible()) {
  5405. if (showHide)
  5406. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5407. QTimer::singleShot(250, this, SLOT(show()));
  5408. if (previewEnabled)
  5409. EnablePreviewDisplay(true);
  5410. setVisible(true);
  5411. #ifdef __APPLE__
  5412. EnableOSXDockIcon(true);
  5413. #endif
  5414. /* raise and activate window to ensure it is on top */
  5415. raise();
  5416. activateWindow();
  5417. /* show all child dialogs that was visible earlier */
  5418. if (!visDialogs.isEmpty()) {
  5419. for (int i = 0; i < visDialogs.size(); ++i) {
  5420. QDialog *dlg = visDialogs[i];
  5421. dlg->move(visDlgPositions[i]);
  5422. dlg->show();
  5423. }
  5424. }
  5425. /* Unminimize window if it was hidden to tray instead of task
  5426. * bar. */
  5427. if (sysTrayMinimizeToTray()) {
  5428. Qt::WindowStates state;
  5429. state = windowState() & ~Qt::WindowMinimized;
  5430. state |= Qt::WindowActive;
  5431. setWindowState(state);
  5432. }
  5433. }
  5434. }
  5435. void OBSBasic::ToggleShowHide()
  5436. {
  5437. bool showing = isVisible();
  5438. if (showing) {
  5439. /* check for modal dialogs */
  5440. EnumDialogs();
  5441. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5442. return;
  5443. }
  5444. SetShowing(!showing);
  5445. }
  5446. void OBSBasic::SystemTrayInit()
  5447. {
  5448. trayIcon.reset(new QSystemTrayIcon(QIcon::fromTheme("obs-tray",
  5449. QIcon(":/res/images/obs.png")), this));
  5450. trayIcon->setToolTip("OBS Studio");
  5451. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  5452. trayIcon.data());
  5453. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5454. trayIcon.data());
  5455. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5456. trayIcon.data());
  5457. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5458. trayIcon.data());
  5459. exit = new QAction(QTStr("Exit"),
  5460. trayIcon.data());
  5461. trayMenu = new QMenu;
  5462. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5463. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5464. AddProjectorMenuMonitors(previewProjector, this,
  5465. SLOT(OpenPreviewProjector()));
  5466. AddProjectorMenuMonitors(studioProgramProjector, this,
  5467. SLOT(OpenStudioProgramProjector()));
  5468. trayMenu->addAction(showHide);
  5469. trayMenu->addMenu(previewProjector);
  5470. trayMenu->addMenu(studioProgramProjector);
  5471. trayMenu->addAction(sysTrayStream);
  5472. trayMenu->addAction(sysTrayRecord);
  5473. trayMenu->addAction(sysTrayReplayBuffer);
  5474. trayMenu->addAction(exit);
  5475. trayIcon->setContextMenu(trayMenu);
  5476. if (outputHandler && !outputHandler->replayBuffer)
  5477. sysTrayReplayBuffer->setEnabled(false);
  5478. connect(trayIcon.data(),
  5479. SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  5480. this,
  5481. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5482. connect(showHide, SIGNAL(triggered()),
  5483. this, SLOT(ToggleShowHide()));
  5484. connect(sysTrayStream, SIGNAL(triggered()),
  5485. this, SLOT(on_streamButton_clicked()));
  5486. connect(sysTrayRecord, SIGNAL(triggered()),
  5487. this, SLOT(on_recordButton_clicked()));
  5488. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  5489. this, &OBSBasic::ReplayBufferClicked);
  5490. connect(exit, SIGNAL(triggered()),
  5491. this, SLOT(close()));
  5492. }
  5493. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5494. {
  5495. // Refresh projector list
  5496. previewProjector->clear();
  5497. studioProgramProjector->clear();
  5498. AddProjectorMenuMonitors(previewProjector, this,
  5499. SLOT(OpenPreviewProjector()));
  5500. AddProjectorMenuMonitors(studioProgramProjector, this,
  5501. SLOT(OpenStudioProgramProjector()));
  5502. if (reason == QSystemTrayIcon::Trigger)
  5503. ToggleShowHide();
  5504. }
  5505. void OBSBasic::SysTrayNotify(const QString &text,
  5506. QSystemTrayIcon::MessageIcon n)
  5507. {
  5508. if (trayIcon && QSystemTrayIcon::supportsMessages()) {
  5509. QSystemTrayIcon::MessageIcon icon =
  5510. QSystemTrayIcon::MessageIcon(n);
  5511. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5512. }
  5513. }
  5514. void OBSBasic::SystemTray(bool firstStarted)
  5515. {
  5516. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5517. return;
  5518. if (!trayIcon && !firstStarted)
  5519. return;
  5520. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  5521. "BasicWindow", "SysTrayWhenStarted");
  5522. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  5523. "BasicWindow", "SysTrayEnabled");
  5524. if (firstStarted)
  5525. SystemTrayInit();
  5526. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5527. trayIcon->hide();
  5528. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  5529. || opt_minimize_tray) {
  5530. trayIcon->show();
  5531. if (firstStarted) {
  5532. QTimer::singleShot(50, this, SLOT(hide()));
  5533. EnablePreviewDisplay(false);
  5534. setVisible(false);
  5535. #ifdef __APPLE__
  5536. EnableOSXDockIcon(false);
  5537. #endif
  5538. opt_minimize_tray = false;
  5539. }
  5540. } else if (sysTrayEnabled) {
  5541. trayIcon->show();
  5542. } else if (!sysTrayEnabled) {
  5543. trayIcon->hide();
  5544. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5545. trayIcon->hide();
  5546. }
  5547. if (isVisible())
  5548. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5549. else
  5550. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5551. }
  5552. bool OBSBasic::sysTrayMinimizeToTray()
  5553. {
  5554. return config_get_bool(GetGlobalConfig(),
  5555. "BasicWindow", "SysTrayMinimizeToTray");
  5556. }
  5557. void OBSBasic::on_actionCopySource_triggered()
  5558. {
  5559. OBSSceneItem item = GetCurrentSceneItem();
  5560. if (!item)
  5561. return;
  5562. on_actionCopyTransform_triggered();
  5563. OBSSource source = obs_sceneitem_get_source(item);
  5564. copyString = obs_source_get_name(source);
  5565. copyVisible = obs_sceneitem_visible(item);
  5566. ui->actionPasteRef->setEnabled(true);
  5567. uint32_t output_flags = obs_source_get_output_flags(source);
  5568. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5569. ui->actionPasteDup->setEnabled(true);
  5570. else
  5571. ui->actionPasteDup->setEnabled(false);
  5572. }
  5573. void OBSBasic::on_actionPasteRef_triggered()
  5574. {
  5575. /* do not allow duplicate refs of the same group in the same scene */
  5576. OBSScene scene = GetCurrentScene();
  5577. if (!!obs_scene_get_group(scene, copyString))
  5578. return;
  5579. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  5580. on_actionPasteTransform_triggered();
  5581. }
  5582. void OBSBasic::on_actionPasteDup_triggered()
  5583. {
  5584. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  5585. on_actionPasteTransform_triggered();
  5586. }
  5587. void OBSBasic::AudioMixerCopyFilters()
  5588. {
  5589. QAction *action = reinterpret_cast<QAction*>(sender());
  5590. VolControl *vol = action->property("volControl").value<VolControl*>();
  5591. obs_source_t *source = vol->GetSource();
  5592. copyFiltersString = obs_source_get_name(source);
  5593. }
  5594. void OBSBasic::AudioMixerPasteFilters()
  5595. {
  5596. QAction *action = reinterpret_cast<QAction*>(sender());
  5597. VolControl *vol = action->property("volControl").value<VolControl*>();
  5598. obs_source_t *dstSource = vol->GetSource();
  5599. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5600. obs_source_release(source);
  5601. if (source == dstSource)
  5602. return;
  5603. obs_source_copy_filters(dstSource, source);
  5604. }
  5605. void OBSBasic::SceneCopyFilters()
  5606. {
  5607. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  5608. }
  5609. void OBSBasic::ScenePasteFilters()
  5610. {
  5611. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5612. obs_source_release(source);
  5613. OBSSource dstSource = GetCurrentSceneSource();
  5614. if (source == dstSource)
  5615. return;
  5616. obs_source_copy_filters(dstSource, source);
  5617. }
  5618. void OBSBasic::on_actionCopyFilters_triggered()
  5619. {
  5620. OBSSceneItem item = GetCurrentSceneItem();
  5621. if (!item)
  5622. return;
  5623. OBSSource source = obs_sceneitem_get_source(item);
  5624. copyFiltersString = obs_source_get_name(source);
  5625. ui->actionPasteFilters->setEnabled(true);
  5626. }
  5627. void OBSBasic::on_actionPasteFilters_triggered()
  5628. {
  5629. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5630. obs_source_release(source);
  5631. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5632. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5633. if (source == dstSource)
  5634. return;
  5635. obs_source_copy_filters(dstSource, source);
  5636. }
  5637. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5638. QModelIndexList selectedItems)
  5639. {
  5640. for (int x = 0; x < selectedItems.count(); x++) {
  5641. SourceTreeItem *treeItem = sources
  5642. ->GetItemWidget(selectedItems[x].row());
  5643. treeItem->setStyleSheet("background: "
  5644. + color.name(QColor::HexArgb));
  5645. treeItem->style()->unpolish(treeItem);
  5646. treeItem->style()->polish(treeItem);
  5647. OBSSceneItem sceneItem = sources->Get(
  5648. selectedItems[x].row());
  5649. obs_data_t *privData =
  5650. obs_sceneitem_get_private_settings(sceneItem);
  5651. obs_data_set_int(privData, "color-preset", 1);
  5652. obs_data_set_string(privData, "color",
  5653. QT_TO_UTF8(color.name(
  5654. QColor::HexArgb)));
  5655. obs_data_release(privData);
  5656. }
  5657. }
  5658. void OBSBasic::ColorChange()
  5659. {
  5660. QModelIndexList selectedItems =
  5661. ui->sources->selectionModel()->selectedIndexes();
  5662. QAction *action = qobject_cast<QAction*>(sender());
  5663. QPushButton *colorButton = qobject_cast<QPushButton*>(sender());
  5664. if (selectedItems.count() == 0)
  5665. return;
  5666. if (colorButton) {
  5667. int preset = colorButton->property("bgColor").value<int>();
  5668. for (int x = 0; x < selectedItems.count(); x++) {
  5669. SourceTreeItem *treeItem = ui->sources
  5670. ->GetItemWidget(selectedItems[x].row());
  5671. treeItem->setStyleSheet("");
  5672. treeItem->setProperty("bgColor", preset);
  5673. treeItem->style()->unpolish(treeItem);
  5674. treeItem->style()->polish(treeItem);
  5675. OBSSceneItem sceneItem = ui->sources->Get(
  5676. selectedItems[x].row());
  5677. obs_data_t *privData =
  5678. obs_sceneitem_get_private_settings(sceneItem);
  5679. obs_data_set_int(privData, "color-preset", preset + 1);
  5680. obs_data_set_string(privData, "color", "");
  5681. obs_data_release(privData);
  5682. }
  5683. for (int i = 1; i < 9; i++) {
  5684. stringstream button;
  5685. button << "preset" << i;
  5686. QPushButton *cButton = colorButton->parentWidget()
  5687. ->findChild<QPushButton *>(button.str().c_str());
  5688. cButton->setStyleSheet("border: 1px solid black");
  5689. }
  5690. colorButton->setStyleSheet("border: 2px solid black");
  5691. } else if (action) {
  5692. int preset = action->property("bgColor").value<int>();
  5693. if (preset == 1) {
  5694. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5695. SourceTreeItem *curTreeItem =
  5696. GetItemWidgetFromSceneItem(curSceneItem);
  5697. obs_data_t *curPrivData =
  5698. obs_sceneitem_get_private_settings(curSceneItem);
  5699. int oldPreset = obs_data_get_int(
  5700. curPrivData, "color-preset");
  5701. const QString oldSheet = curTreeItem->styleSheet();
  5702. auto liveChangeColor = [=](const QColor &color) {
  5703. if (color.isValid()) {
  5704. curTreeItem->setStyleSheet(
  5705. "background: "
  5706. + color.name(QColor::HexArgb));
  5707. }
  5708. };
  5709. auto changedColor = [=](const QColor &color) {
  5710. if (color.isValid()) {
  5711. ConfirmColor(ui->sources, color,
  5712. selectedItems);
  5713. }
  5714. };
  5715. auto rejected = [=]() {
  5716. if (oldPreset == 1) {
  5717. curTreeItem->setStyleSheet(oldSheet);
  5718. curTreeItem->setProperty("bgColor", 0);
  5719. } else if (oldPreset == 0) {
  5720. curTreeItem->setStyleSheet(
  5721. "background: none");
  5722. curTreeItem->setProperty("bgColor", 0);
  5723. } else {
  5724. curTreeItem->setStyleSheet("");
  5725. curTreeItem->setProperty("bgColor",
  5726. oldPreset - 1);
  5727. }
  5728. curTreeItem->style()->unpolish(curTreeItem);
  5729. curTreeItem->style()->polish(curTreeItem);
  5730. };
  5731. QColorDialog::ColorDialogOptions options =
  5732. QColorDialog::ShowAlphaChannel;
  5733. const char *oldColor = obs_data_get_string(curPrivData,
  5734. "color");
  5735. const char *customColor = *oldColor != 0 ? oldColor
  5736. : "#55FF0000";
  5737. #ifdef __APPLE__
  5738. options |= QColorDialog::DontUseNativeDialog;
  5739. #endif
  5740. QColorDialog *colorDialog = new QColorDialog(this);
  5741. colorDialog->setOptions(options);
  5742. colorDialog->setCurrentColor(
  5743. QColor(customColor));
  5744. connect(colorDialog, &QColorDialog::currentColorChanged,
  5745. liveChangeColor);
  5746. connect(colorDialog, &QColorDialog::colorSelected,
  5747. changedColor);
  5748. connect(colorDialog, &QColorDialog::rejected,
  5749. rejected);
  5750. colorDialog->open();
  5751. obs_data_release(curPrivData);
  5752. } else {
  5753. for (int x = 0; x < selectedItems.count(); x++) {
  5754. SourceTreeItem *treeItem = ui->sources
  5755. ->GetItemWidget(selectedItems[x].row());
  5756. treeItem->setStyleSheet("background: none");
  5757. treeItem->setProperty("bgColor", preset);
  5758. treeItem->style()->unpolish(treeItem);
  5759. treeItem->style()->polish(treeItem);
  5760. OBSSceneItem sceneItem = ui->sources->Get(
  5761. selectedItems[x].row());
  5762. obs_data_t *privData =
  5763. obs_sceneitem_get_private_settings(
  5764. sceneItem);
  5765. obs_data_set_int(privData, "color-preset",
  5766. preset);
  5767. obs_data_set_string(privData, "color", "");
  5768. obs_data_release(privData);
  5769. }
  5770. }
  5771. }
  5772. }
  5773. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(
  5774. obs_sceneitem_t *sceneItem)
  5775. {
  5776. int i = 0;
  5777. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  5778. OBSSceneItem item = ui->sources->Get(i);
  5779. int64_t id = obs_sceneitem_get_id(sceneItem);
  5780. while (treeItem && obs_sceneitem_get_id(item) != id) {
  5781. i++;
  5782. treeItem = ui->sources->GetItemWidget(i);
  5783. item = ui->sources->Get(i);
  5784. }
  5785. if(treeItem)
  5786. return treeItem;
  5787. return nullptr;
  5788. }
  5789. void OBSBasic::on_autoConfigure_triggered()
  5790. {
  5791. AutoConfig test(this);
  5792. test.setModal(true);
  5793. test.show();
  5794. test.exec();
  5795. }
  5796. void OBSBasic::on_stats_triggered()
  5797. {
  5798. if (!stats.isNull()) {
  5799. stats->show();
  5800. stats->raise();
  5801. return;
  5802. }
  5803. OBSBasicStats *statsDlg;
  5804. statsDlg = new OBSBasicStats(nullptr);
  5805. statsDlg->show();
  5806. stats = statsDlg;
  5807. }
  5808. void OBSBasic::on_actionShowAbout_triggered()
  5809. {
  5810. if (about)
  5811. about->close();
  5812. about = new OBSAbout(this);
  5813. about->show();
  5814. about->setAttribute(Qt::WA_DeleteOnClose, true);
  5815. }
  5816. void OBSBasic::ResizeOutputSizeOfSource()
  5817. {
  5818. if (ui->streamButton->isChecked() || ui->recordButton->isChecked() ||
  5819. (replayBufferButton && replayBufferButton->isChecked()))
  5820. return;
  5821. QMessageBox resize_output(this);
  5822. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") +
  5823. "\n\n" + QTStr("ResizeOutputSizeOfSource.Continue"));
  5824. QAbstractButton *Yes = resize_output.addButton(QTStr("Yes"),
  5825. QMessageBox::YesRole);
  5826. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  5827. resize_output.setIcon(QMessageBox::Warning);
  5828. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  5829. resize_output.exec();
  5830. if (resize_output.clickedButton() != Yes)
  5831. return;
  5832. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  5833. int width = obs_source_get_width(source);
  5834. int height = obs_source_get_height(source);
  5835. config_set_uint(basicConfig, "Video", "BaseCX", width);
  5836. config_set_uint(basicConfig, "Video", "BaseCY", height);
  5837. config_set_uint(basicConfig, "Video", "OutputCX", width);
  5838. config_set_uint(basicConfig, "Video", "OutputCY", height);
  5839. ResetVideo();
  5840. on_actionFitToScreen_triggered();
  5841. }
  5842. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  5843. {
  5844. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  5845. action->setCheckable(true);
  5846. assignDockToggle(dock, action);
  5847. extraDocks.push_back(dock);
  5848. bool lock = ui->lockUI->isChecked();
  5849. QDockWidget::DockWidgetFeatures features = lock
  5850. ? QDockWidget::NoDockWidgetFeatures
  5851. : QDockWidget::AllDockWidgetFeatures;
  5852. dock->setFeatures(features);
  5853. /* prune deleted docks */
  5854. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5855. if (!extraDocks[i]) {
  5856. extraDocks.removeAt(i);
  5857. }
  5858. }
  5859. return action;
  5860. }
  5861. OBSBasic *OBSBasic::Get()
  5862. {
  5863. return reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  5864. }
  5865. bool OBSBasic::StreamingActive()
  5866. {
  5867. if (!outputHandler)
  5868. return false;
  5869. return outputHandler->StreamingActive();
  5870. }
  5871. bool OBSBasic::RecordingActive()
  5872. {
  5873. if (!outputHandler)
  5874. return false;
  5875. return outputHandler->RecordingActive();
  5876. }
  5877. bool OBSBasic::ReplayBufferActive()
  5878. {
  5879. if (!outputHandler)
  5880. return false;
  5881. return outputHandler->ReplayBufferActive();
  5882. }
  5883. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  5884. : QStyledItemDelegate(parent)
  5885. {
  5886. }
  5887. void SceneRenameDelegate::setEditorData(QWidget *editor,
  5888. const QModelIndex &index) const
  5889. {
  5890. QStyledItemDelegate::setEditorData(editor, index);
  5891. QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
  5892. if (lineEdit)
  5893. lineEdit->selectAll();
  5894. }
  5895. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  5896. {
  5897. if (event->type() == QEvent::KeyPress) {
  5898. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  5899. if (keyEvent->key() == Qt::Key_Escape) {
  5900. QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
  5901. if (lineEdit)
  5902. lineEdit->undo();
  5903. }
  5904. }
  5905. return QStyledItemDelegate::eventFilter(editor, event);
  5906. }