window-basic-main.cpp 197 KB

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